diff --git a/.gitignore b/.gitignore index 729dea62d5..d3a5dae06d 100644 --- a/.gitignore +++ b/.gitignore @@ -73,8 +73,6 @@ ninja/devDb.mv.db **/out-tsc **/nbproject/ **/nb-configuration.xml -core-scala/.cache-main -core-scala/.cache-tests persistence-modules/hibernate5/transaction.log diff --git a/README.md b/README.md index 5307efa008..b08a93f23e 100644 --- a/README.md +++ b/README.md @@ -22,10 +22,38 @@ This project is **a collection of small and focused tutorials** - each covering A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security. In additional to Spring, the modules here are covering a number of aspects in Java. +Profile based segregation +==================== + +We are using maven build profiles to segregate the huge list of individual projects we have in our repository. + +The projects are broadly divided into 3 list: first, second and heavy. + +Next, they are segregated further on the basis of tests that we want to execute. + +Therefore, we have a total of 6 profiles: + +| Profile | Includes | Type of test enabled | +| ----------------------- | --------------------------- | -------------------- | +| default-first | First set of projects | *UnitTest | +| integration-lite-first | First set of projects | *IntegrationTest | +| default-second | Second set of projects | *UnitTest | +| integration-lite-second | Second set of projects | *IntegrationTest | +| default-heavy | Heavy/long running projects | *UnitTest | +| integration-heavy | Heavy/long running projects | *IntegrationTest | Building the project ==================== -To do the full build, do: `mvn clean install` + +Though it should not be needed often to build the entire repository at once because we are usually concerned with a specific module. + +But if we want to, we can invoke the below command from the root of the repository if we want to build the entire repository with only Unit Tests enabled: + +`mvn clean install -Pdefault-first,default-second,default-heavy` + +or if we want to build the entire repository with Integration Tests enabled, we can do: + +`mvn clean install -Pintegration-lite-first,integration-lite-second,integration-heavy` Building a single module @@ -46,8 +74,18 @@ When you're working with an individual module, there's no need to import all of Running Tests ============= -The command `mvn clean install` will run the unit tests in a module. -To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` +The command `mvn clean install` from within a module will run the unit tests in that module. +For Spring modules this will also run the `SpringContextTest` if present. + +To run the integration tests, use the command: + +`mvn clean install -Pintegration-lite-first` or + +`mvn clean install -Pintegration-lite-second` or + +`mvn clean install -Pintegration-heavy` + +depending on the list where our module exists diff --git a/algorithms-searching/README.md b/algorithms-searching/README.md index 9b85995235..aed3c7d21f 100644 --- a/algorithms-searching/README.md +++ b/algorithms-searching/README.md @@ -10,3 +10,4 @@ This module contains articles about searching algorithms. - [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms) - [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search) - [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search) +- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree) diff --git a/apache-beam/README.md b/apache-beam/README.md new file mode 100644 index 0000000000..a71e5256a8 --- /dev/null +++ b/apache-beam/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Apache Beam](https://www.baeldung.com/apache-beam) diff --git a/aws-reactive/pom.xml b/aws-reactive/pom.xml index 950b3f373a..d4f0e5e231 100644 --- a/aws-reactive/pom.xml +++ b/aws-reactive/pom.xml @@ -16,12 +16,6 @@ aws-reactive AWS Reactive Sample - - 1.8 - 2.2.1.RELEASE - 2.10.27 - - @@ -105,4 +99,9 @@ + + 1.8 + 2.2.1.RELEASE + 2.10.27 + diff --git a/core-java-modules/core-java-14/README.md b/core-java-modules/core-java-14/README.md index 0648d087be..0e8278c4f6 100644 --- a/core-java-modules/core-java-14/README.md +++ b/core-java-modules/core-java-14/README.md @@ -5,3 +5,5 @@ This module contains articles about Java 14. ### Relevant articles - [Guide to the @Serial Annotation in Java 14](https://www.baeldung.com/java-14-serial-annotation) +- [Java Text Blocks](https://www.baeldung.com/java-text-blocks) +- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof) diff --git a/core-java-modules/core-java-arrays-3/README.md b/core-java-modules/core-java-arrays-3/README.md new file mode 100644 index 0000000000..255d3d097d --- /dev/null +++ b/core-java-modules/core-java-arrays-3/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals) diff --git a/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/atomic/AtomicMarkableReferenceUnitTest.java b/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/atomic/AtomicMarkableReferenceUnitTest.java new file mode 100644 index 0000000000..5f526344be --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/atomic/AtomicMarkableReferenceUnitTest.java @@ -0,0 +1,189 @@ +package com.baeldung.concurrent.atomic; + +import java.util.concurrent.atomic.AtomicMarkableReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class AtomicMarkableReferenceUnitTest { + + class Employee { + private int id; + private String name; + + Employee(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @Test + void givenMarkValueAsTrue_whenUsingIsMarkedMethod_thenMarkValueShouldBeTrue() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenMarkValueAsFalse_whenUsingIsMarkedMethod_thenMarkValueShouldBeFalse() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, false); + + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void whenUsingGetReferenceMethod_thenCurrentReferenceShouldBeReturned() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Assertions.assertEquals(employee, employeeNode.getReference()); + } + + @Test + void whenUsingGetMethod_thenCurrentReferenceAndMarkShouldBeReturned() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + boolean[] markHolder = new boolean[1]; + Employee currentEmployee = employeeNode.get(markHolder); + + Assertions.assertEquals(employee, currentEmployee); + Assertions.assertTrue(markHolder[0]); + } + + @Test + void givenNewReferenceAndMark_whenUsingSetMethod_thenCurrentReferenceAndMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Employee newEmployee = new Employee(124, "John"); + employeeNode.set(newEmployee, false); + + Assertions.assertEquals(newEmployee, employeeNode.getReference()); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenTheSameObjectReference_whenUsingAttemptMarkMethod_thenMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Assertions.assertTrue(employeeNode.attemptMark(employee, false)); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenDifferentObjectReference_whenUsingAttemptMarkMethod_thenMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee expectedEmployee = new Employee(123, "Mike"); + + Assertions.assertFalse(employeeNode.attemptMark(expectedEmployee, false)); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertTrue(employeeNode.compareAndSet(employee, newEmployee, true, false)); + Assertions.assertEquals(newEmployee, employeeNode.getReference()); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.compareAndSet(new Employee(1234, "Steve"), newEmployee, true, false)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndNotCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.compareAndSet(employee, newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndNotCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.compareAndSet(new Employee(1234, "Steve"), newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertTrue(employeeNode.weakCompareAndSet(employee, newEmployee, true, false)); + Assertions.assertEquals(newEmployee, employeeNode.getReference()); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.weakCompareAndSet(new Employee(1234, "Steve"), newEmployee, true, false)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndNotCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.weakCompareAndSet(employee, newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndNotCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.weakCompareAndSet(new Employee(1234, "Steve"), newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } +} diff --git a/core-java-modules/core-java-concurrency-collections-2/pom.xml b/core-java-modules/core-java-concurrency-collections-2/pom.xml new file mode 100644 index 0000000000..65a91c9a9c --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + com.baeldung.concurrent.lock + core-java-concurrency-collections-2 + 0.0.1-SNAPSHOT + + + + com.google.guava + guava + ${guava.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + src + + + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + + + + 1.21 + 28.2-jre + + + \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessBenchmark.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessBenchmark.java new file mode 100644 index 0000000000..ceb53ce077 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessBenchmark.java @@ -0,0 +1,54 @@ +package com.baeldung.concurrent.lock; + +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.Map; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +@State(Scope.Thread) +@Fork(value = 2) +@Warmup(iterations = 0) +public class ConcurrentAccessBenchmark { + static final int SLOTS = 4; + static final int THREADS = 10000; + static final int BUCKETS = Runtime.getRuntime().availableProcessors() * SLOTS; + SingleLock singleLock = new SingleLock(); + StripedLock stripedLock = new StripedLock(BUCKETS); + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map singleLockHashMap() throws InterruptedException { + return singleLock.doWork(new HashMap(), THREADS, SLOTS); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map stripedLockHashMap() throws InterruptedException { + return stripedLock.doWork(new HashMap(), THREADS, SLOTS); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map singleLockConcurrentHashMap() throws InterruptedException { + return singleLock.doWork(new ConcurrentHashMap(), THREADS, SLOTS); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map stripedLockConcurrentHashMap() throws InterruptedException { + return stripedLock.doWork(new ConcurrentHashMap(), THREADS, SLOTS); + } +} diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessExperiment.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessExperiment.java new file mode 100644 index 0000000000..ec6d3895da --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessExperiment.java @@ -0,0 +1,26 @@ +package com.baeldung.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +import com.google.common.base.Supplier; + +public abstract class ConcurrentAccessExperiment { + + public final Map doWork(Map map, int threads, int slots) { + CompletableFuture[] requests = new CompletableFuture[threads * slots]; + + for (int i = 0; i < threads; i++) { + requests[slots * i + 0] = CompletableFuture.supplyAsync(putSupplier(map, i)); + requests[slots * i + 1] = CompletableFuture.supplyAsync(getSupplier(map, i)); + requests[slots * i + 2] = CompletableFuture.supplyAsync(getSupplier(map, i)); + requests[slots * i + 3] = CompletableFuture.supplyAsync(getSupplier(map, i)); + } + CompletableFuture.allOf(requests).join(); + + return map; + } + + protected abstract Supplier putSupplier(Map map, int key); + protected abstract Supplier getSupplier(Map map, int key); +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/SingleLock.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/SingleLock.java new file mode 100644 index 0000000000..4dff459df6 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/SingleLock.java @@ -0,0 +1,36 @@ +package com.baeldung.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.locks.ReentrantLock; + +import com.google.common.base.Supplier; + +public class SingleLock extends ConcurrentAccessExperiment { + ReentrantLock lock; + + public SingleLock() { + lock = new ReentrantLock(); + } + + protected Supplier putSupplier(Map map, int key) { + return (()-> { + lock.lock(); + try { + return map.put("key" + key, "value" + key); + } finally { + lock.unlock(); + } + }); + } + + protected Supplier getSupplier(Map map, int key) { + return (()-> { + lock.lock(); + try { + return map.get("key" + key); + } finally { + lock.unlock(); + } + }); + } +} diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/StripedLock.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/StripedLock.java new file mode 100644 index 0000000000..47c47d8813 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/StripedLock.java @@ -0,0 +1,41 @@ +package com.baeldung.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.locks.Lock; + +import com.google.common.base.Supplier; +import com.google.common.util.concurrent.Striped; + +public class StripedLock extends ConcurrentAccessExperiment { + Striped stripedLock; + + public StripedLock(int buckets) { + stripedLock = Striped.lock(buckets); + } + + protected Supplier putSupplier(Map map, int key) { + return (()-> { + int bucket = key % stripedLock.size(); + Lock lock = stripedLock.get(bucket); + lock.lock(); + try { + return map.put("key" + key, "value" + key); + } finally { + lock.unlock(); + } + }); + } + + protected Supplier getSupplier(Map map, int key) { + return (()-> { + int bucket = key % stripedLock.size(); + Lock lock = stripedLock.get(bucket); + lock.lock(); + try { + return map.get("key" + key); + } finally { + lock.unlock(); + } + }); + } +} diff --git a/core-java-modules/core-java-exceptions-2/README.md b/core-java-modules/core-java-exceptions-2/README.md index 49ce897e60..1b8457acc4 100644 --- a/core-java-modules/core-java-exceptions-2/README.md +++ b/core-java-modules/core-java-exceptions-2/README.md @@ -7,3 +7,5 @@ This module contains articles about core java exceptions - [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice) - [Wrapping vs Rethrowing Exceptions in Java](https://www.baeldung.com/java-wrapping-vs-rethrowing-exceptions) - [java.net.UnknownHostException: Invalid Hostname for Server](https://www.baeldung.com/java-unknownhostexception) +- [How to Handle Java SocketException](https://www.baeldung.com/java-socketexception) +- [Java Suppressed Exceptions](https://www.baeldung.com/java-suppressed-exceptions) diff --git a/core-java-modules/core-java-io-2/pom.xml b/core-java-modules/core-java-io-2/pom.xml index ee7d82b610..ec27c76435 100644 --- a/core-java-modules/core-java-io-2/pom.xml +++ b/core-java-modules/core-java-io-2/pom.xml @@ -47,6 +47,14 @@ ${assertj.version} test + + + com.github.tomakehurst + wiremock + 2.26.3 + test + + diff --git a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/BlockingClientUnitTest.java b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/BlockingClientUnitTest.java new file mode 100644 index 0000000000..cd3d688763 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/BlockingClientUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.blockingnonblocking; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.io.*; +import java.net.Socket; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.Assert.assertTrue; + +public class BlockingClientUnitTest { + private static final String REQUESTED_RESOURCE = "/test.json"; + + @Rule public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort()); + + @Before + public void setup() { + stubFor(get(urlEqualTo(REQUESTED_RESOURCE)).willReturn(aResponse() + .withStatus(200) + .withBody("{ \"response\" : \"It worked!\" }\r\n\r\n"))); + } + + @Test + public void givenJavaIOSocket_whenReadingAndWritingWithStreams_thenSuccess() throws IOException { + // given an IO socket and somewhere to store our result + Socket socket = new Socket("localhost", wireMockRule.port()); + StringBuilder ourStore = new StringBuilder(); + + // when we write and read (using try-with-resources so our resources are auto-closed) + try (InputStream serverInput = socket.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(serverInput)); + OutputStream clientOutput = socket.getOutputStream(); + PrintWriter writer = new PrintWriter(new OutputStreamWriter(clientOutput))) { + writer.print("GET " + REQUESTED_RESOURCE + " HTTP/1.0\r\n\r\n"); + writer.flush(); // important - without this the request is never sent, and the test will hang on readLine() + + for (String line; (line = reader.readLine()) != null; ) { + ourStore.append(line); + ourStore.append(System.lineSeparator()); + } + } + + // then we read and saved our data + assertTrue(ourStore + .toString() + .contains("It worked!")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/NonBlockingClientUnitTest.java b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/NonBlockingClientUnitTest.java new file mode 100644 index 0000000000..3e606476e6 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/NonBlockingClientUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.blockingnonblocking; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.channels.SocketChannel; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.StandardCharsets; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.Assert.assertTrue; + +public class NonBlockingClientUnitTest { + private String REQUESTED_RESOURCE = "/test.json"; + + @Rule public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort()); + + @Before + public void setup() { + stubFor(get(urlEqualTo(REQUESTED_RESOURCE)).willReturn(aResponse() + .withStatus(200) + .withBody("{ \"response\" : \"It worked!\" }"))); + } + + @Test + public void givenJavaNIOSocketChannel_whenReadingAndWritingWithBuffers_thenSuccess() throws IOException { + // given a NIO SocketChannel and a charset + InetSocketAddress address = new InetSocketAddress("localhost", wireMockRule.port()); + SocketChannel socketChannel = SocketChannel.open(address); + Charset charset = StandardCharsets.UTF_8; + + // when we write and read using buffers + socketChannel.write(charset.encode(CharBuffer.wrap("GET " + REQUESTED_RESOURCE + " HTTP/1.0\r\n\r\n"))); + + ByteBuffer byteBuffer = ByteBuffer.allocate(8192); // or allocateDirect if we need direct memory access + CharBuffer charBuffer = CharBuffer.allocate(8192); + CharsetDecoder charsetDecoder = charset.newDecoder(); + StringBuilder ourStore = new StringBuilder(); + while (socketChannel.read(byteBuffer) != -1 || byteBuffer.position() > 0) { + byteBuffer.flip(); + storeBufferContents(byteBuffer, charBuffer, charsetDecoder, ourStore); + byteBuffer.compact(); + } + socketChannel.close(); + + // then we read and saved our data + assertTrue(ourStore + .toString() + .contains("It worked!")); + } + + @Test + public void givenJavaNIOSocketChannel_whenReadingAndWritingWithSmallBuffers_thenSuccess() throws IOException { + // given a NIO SocketChannel and a charset + InetSocketAddress address = new InetSocketAddress("localhost", wireMockRule.port()); + SocketChannel socketChannel = SocketChannel.open(address); + Charset charset = StandardCharsets.UTF_8; + + // when we write and read using buffers that are too small for our message + socketChannel.write(charset.encode(CharBuffer.wrap("GET " + REQUESTED_RESOURCE + " HTTP/1.0\r\n\r\n"))); + + ByteBuffer byteBuffer = ByteBuffer.allocate(8); // or allocateDirect if we need direct memory access + CharBuffer charBuffer = CharBuffer.allocate(8); + CharsetDecoder charsetDecoder = charset.newDecoder(); + StringBuilder ourStore = new StringBuilder(); + while (socketChannel.read(byteBuffer) != -1 || byteBuffer.position() > 0) { + byteBuffer.flip(); + storeBufferContents(byteBuffer, charBuffer, charsetDecoder, ourStore); + byteBuffer.compact(); + } + socketChannel.close(); + + // then we read and saved our data + assertTrue(ourStore + .toString() + .contains("It worked!")); + } + + void storeBufferContents(ByteBuffer byteBuffer, CharBuffer charBuffer, CharsetDecoder charsetDecoder, StringBuilder ourStore) { + charsetDecoder.decode(byteBuffer, charBuffer, true); + charBuffer.flip(); + ourStore.append(charBuffer); + charBuffer.clear(); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-2/README.md b/core-java-modules/core-java-lang-2/README.md index a9604d1032..65d40c6a26 100644 --- a/core-java-modules/core-java-lang-2/README.md +++ b/core-java-modules/core-java-lang-2/README.md @@ -9,4 +9,5 @@ This module contains articles about core features in the Java language - [Java Default Parameters Using Method Overloading](https://www.baeldung.com/java-default-parameters-method-overloading) - [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values) - [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword) +- [The Java Headless Mode](https://www.baeldung.com/java-headless-mode) - [[<-- Prev]](/core-java-modules/core-java-lang) diff --git a/core-java-modules/core-java-nio-2/README.md b/core-java-modules/core-java-nio-2/README.md index 8b29c97385..ef73159f66 100644 --- a/core-java-modules/core-java-nio-2/README.md +++ b/core-java-modules/core-java-nio-2/README.md @@ -8,4 +8,5 @@ This module contains articles about core Java non-blocking input and output (IO) - [Create a Symbolic Link with Java](https://www.baeldung.com/java-symlink) - [Introduction to the Java NIO Selector](https://www.baeldung.com/java-nio-selector) - [Using Java MappedByteBuffer](https://www.baeldung.com/java-mapped-byte-buffer) -- [[<-- Prev]](/core-java-modules/core-java-nio) \ No newline at end of file +- [How to Lock a File in Java](https://www.baeldung.com/java-lock-files) +- [[<-- Prev]](/core-java-modules/core-java-nio) diff --git a/core-java-modules/core-java-perf/README.md b/core-java-modules/core-java-perf/README.md index 4204c2b012..d52fd2d733 100644 --- a/core-java-modules/core-java-perf/README.md +++ b/core-java-modules/core-java-perf/README.md @@ -10,3 +10,4 @@ This module contains articles about performance of Java applications - [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions) - [Monitoring Java Applications with Flight Recorder](https://www.baeldung.com/java-flight-recorder-monitoring) - [Branch Prediction in Java](https://www.baeldung.com/java-branch-prediction) +- [Capturing a Java Thread Dump](https://www.baeldung.com/java-thread-dump) diff --git a/core-java-modules/core-java-regex/README.md b/core-java-modules/core-java-regex/README.md index 7a8f6d9293..21cd7a95a3 100644 --- a/core-java-modules/core-java-regex/README.md +++ b/core-java-modules/core-java-regex/README.md @@ -8,3 +8,4 @@ - [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char) - [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile) - [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches) +- [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement) diff --git a/core-java-modules/core-java-security-2/README.md b/core-java-modules/core-java-security-2/README.md new file mode 100644 index 0000000000..c250e24078 --- /dev/null +++ b/core-java-modules/core-java-security-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide To The Java Authentication And Authorization Service (JAAS)](https://www.baeldung.com/java-authentication-authorization-service) diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index 8687ac19ba..5e92738f5c 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -10,4 +10,5 @@ This module contains articles about string operations. - [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase) - [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching) - [L-Trim and R-Trim in Java](https://www.baeldung.com/l-trim-and-r-trim-in-java) +- [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives) - More articles: [[<-- prev]](../core-java-string-operations) diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index 079556712e..a00ae80f13 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -64,6 +64,11 @@ jmh-generator-annprocess ${jmh-generator.version} + + commons-codec + commons-codec + ${commons-codec.version} + org.assertj @@ -113,6 +118,7 @@ 6.0.2.Final 3.0.0 2.2.6 + 1.14 diff --git a/pdf/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java similarity index 100% rename from pdf/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java diff --git a/pdf/src/test/resources/input.pdf b/core-java-modules/core-java-string-operations-2/src/test/resources/input.pdf similarity index 100% rename from pdf/src/test/resources/input.pdf rename to core-java-modules/core-java-string-operations-2/src/test/resources/input.pdf diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml index 24bdc189be..de41aecf73 100644 --- a/core-kotlin-modules/pom.xml +++ b/core-kotlin-modules/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.core-kotlin-modules core-kotlin-modules diff --git a/core-scala/README.md b/core-scala/README.md deleted file mode 100644 index 13929ff721..0000000000 --- a/core-scala/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Core Scala - -This module contains articles about Scala's core features - -### Relevant Articles: - -- [Introduction to Scala](https://www.baeldung.com/scala-intro) -- [Regular Expressions in Scala](https://www.baeldung.com/scala/regular-expressions) diff --git a/core-scala/pom.xml b/core-scala/pom.xml index d72727dd39..8277b0f856 100644 --- a/core-scala/pom.xml +++ b/core-scala/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-scala 1.0-SNAPSHOT @@ -51,5 +53,5 @@ 2.12.7 3.3.2 - + diff --git a/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala b/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala deleted file mode 100644 index 7c1281e573..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.scala - -/** - * Sample code demonstrating the various control structured. - * - * @author Chandra Prakash - * - */ -object ControlStructuresDemo { - def gcd(x : Int, y : Int) : Int = { - if (y == 0) x else gcd(y, x % y) - } - - def gcdIter(x : Int, y : Int) : Int = { - var a = x - var b = y - while (b > 0) { - a = a % b - val t = a - a = b - b = t - } - a - } - - def rangeSum(a : Int, b : Int) = { - var sum = 0; - for (i <- a to b) { - sum += i - } - sum - } - - def factorial(a : Int) : Int = { - var result = 1; - var i = 1; - do { - result *= i - i = i + 1 - } while (i <= a) - result - } - -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/Employee.scala b/core-scala/src/main/scala/com/baeldung/scala/Employee.scala deleted file mode 100644 index 9291d958b3..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/Employee.scala +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.scala - -/** - * Sample Code demonstrating a class. - * - * @author Chandra Prakash - * - */ -class Employee(val name : String, - var salary : Int, - annualIncrement : Int = 20) { - - def incrementSalary() : Unit = { - salary += annualIncrement - } - - override def toString = - s"Employee(name=$name, salary=$salary)" -} - -/** - * A Trait which will make the toString return upper case value. - */ -trait UpperCasePrinter { - override def toString: String = super.toString toUpperCase -} - diff --git a/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala b/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala deleted file mode 100644 index b3f0ce09a5..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.scala - -object HelloWorld extends App { - println("Hello World!") - args foreach println -} diff --git a/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala b/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala deleted file mode 100644 index 02c41a5f8c..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.scala - -/** - * Sample higher order functions. - * - * @author Chandra Prakash - * - */ -object HigherOrderFunctions { - - def mapReduce(r : (Int, Int) => Int, - i : Int, - m : Int => Int, - a : Int, b : Int): Int = { - def iter(a : Int, result : Int) : Int = { - if (a > b) result - else iter(a + 1, r(m(a), result)) - } - iter(a, i) - } - - def whileLoop(condition : => Boolean)(body : => Unit) : Unit = - if (condition) { - body - whileLoop(condition)(body) - } -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala b/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala deleted file mode 100644 index f1a5722a4e..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.scala - -/** - * An abstract class for set of integers and its implementation. - * - * @author Chandra Prakash - * - */ -abstract class IntSet { - // add an element to the set - def incl(x : Int) : IntSet - - // whether an element belongs to the set - def contains(x : Int) : Boolean -} - -class EmptyIntSet extends IntSet { - - def contains(x : Int) : Boolean = false - - def incl(x : Int) = - new NonEmptyIntSet(x, this) -} - -class NonEmptyIntSet(val head : Int, val tail : IntSet) - extends IntSet { - - def contains(x : Int) : Boolean = - head == x || (tail contains x) - - def incl(x : Int) : IntSet = - if (this contains x) this - else new NonEmptyIntSet(x, this) -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala b/core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala deleted file mode 100644 index 71458237d6..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala +++ /dev/null @@ -1,137 +0,0 @@ -package com.baeldung.scala - -// Case Class -abstract class Animal - -case class Mammal(name: String, fromSea: Boolean) extends Animal - -case class Bird(name: String) extends Animal - -case class Fish(name: String) extends Animal - -// Sealed Class -sealed abstract class CardSuit - -case class Spike() extends CardSuit - -case class Diamond() extends CardSuit - -case class Heart() extends CardSuit - -case class Club() extends CardSuit - -object Person { - def apply(fullName: String) = fullName - - def unapply(fullName: String): Option[String] = { - if (!fullName.isEmpty) - Some(fullName.replaceAll("(?<=\\w)(\\w+)", ".")) - else - None - } -} - -class PatternMatching { - - def caseClassesPatternMatching(animal: Animal): String = { - animal match { - case Mammal(name, fromSea) => s"I'm a $name, a kind of mammal. Am I from the sea? $fromSea" - case Bird(name) => s"I'm a $name, a kind of bird" - case _ => "I'm an unknown animal" - } - } - - def constantsPatternMatching(constant: Any): String = { - constant match { - case 0 => "I'm equal to zero" - case 4.5d => "I'm a double" - case false => "I'm the contrary of true" - case _ => s"I'm unknown and equal to $constant" - } - } - - def sequencesPatternMatching(sequence: Any): String = { - sequence match { - case List(singleElement) => s"I'm a list with one element: $singleElement" - case List(_, _*) => s"I'm a list with one or multiple elements: $sequence" - case Vector(1, 2, _*) => s"I'm a vector: $sequence" - case _ => s"I'm an unrecognized sequence. My value: $sequence" - } - } - - def tuplesPatternMatching(tuple: Any): String = { - tuple match { - case (first, second) => s"I'm a tuple with two elements: $first & $second" - case (first, second, third) => s"I'm a tuple with three elements: $first & $second & $third" - case _ => s"Unrecognized pattern. My value: $tuple" - } - } - - def typedPatternMatching(any: Any): String = { - any match { - case string: String => s"I'm a string. My value: $string" - case integer: Int => s"I'm an integer. My value: $integer" - case _ => s"I'm from an unknown type. My value: $any" - } - } - - def regexPatterns(toMatch: String): String = { - val numeric = """([0-9]+)""".r - val alphabetic = """([a-zA-Z]+)""".r - val alphanumeric = """([a-zA-Z0-9]+)""".r - - toMatch match { - case numeric(value) => s"I'm a numeric with value $value" - case alphabetic(value) => s"I'm an alphabetic with value $value" - case alphanumeric(value) => s"I'm an alphanumeric with value $value" - case _ => s"I contain other characters than alphanumerics. My value $toMatch" - } - } - - def optionsPatternMatching(option: Option[String]): String = { - option match { - case Some(value) => s"I'm not an empty option. Value $value" - case None => "I'm an empty option" - } - } - - def patternGuards(toMatch: Any, maxLength: Int): String = { - toMatch match { - case list: List[Any] if (list.size <= maxLength) => "List is of acceptable size" - case list: List[Any] => "List has not an acceptable size" - case string: String if (string.length <= maxLength) => "String is of acceptable size" - case string: String => "String has not an acceptable size" - case _ => "Input is neither a List or a String" - } - } - - def sealedClass(cardSuit: CardSuit): String = { - cardSuit match { - case Spike() => "Card is spike" - case Club() => "Card is club" - case Heart() => "Card is heart" - case Diamond() => "Card is diamond" - } - } - - def extractors(person: Any): String = { - person match { - case Person(initials) => s"My initials are $initials" - case _ => "Could not extract initials" - } - } - - def closuresPatternMatching(list: List[Any]): List[Any] = { - list.collect { case i: Int if (i < 10) => i } - } - - def catchBlocksPatternMatching(exception: Exception): String = { - try { - throw exception - } catch { - case ex: IllegalArgumentException => "It's an IllegalArgumentException" - case ex: RuntimeException => "It's a RuntimeException" - case _ => "It's an unknown kind of exception" - } - } -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/Utils.scala b/core-scala/src/main/scala/com/baeldung/scala/Utils.scala deleted file mode 100644 index 20bc413646..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/Utils.scala +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.scala - -/** - * Some utility methods. - * - * @author Chandra Prakash - * - */ -object Utils { - def average(x : Double, y : Double): Double = (x + y) / 2 - - def randomLessThan(d : Double): Double = { - var random = 0d - do { - random = Math.random() - } while (random >= d) - random - } - - def power(x : Int, y : Int) : Int = { - def powNested(i : Int, accumulator : Int) : Int = { - if (i <= 0) accumulator - else powNested(i - 1, x * accumulator) - } - powNested(y, 1) - } - - def fibonacci(n : Int) : Int = n match { - case 0 | 1 => 1 - case x if x > 1 => - fibonacci(x - 1) + fibonacci(x - 2) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala deleted file mode 100644 index 584038ee2c..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.scala - -import com.baeldung.scala.ControlStructuresDemo._ -import org.junit.Assert.assertEquals -import org.junit.Test - -class ControlStructuresDemoUnitTest { - @Test - def givenTwoIntegers_whenGcdCalled_thenCorrectValueReturned() = { - assertEquals(3, gcd(15, 27)) - } - - @Test - def givenTwoIntegers_whenGcdIterCalled_thenCorrectValueReturned() = { - assertEquals(3, gcdIter(15, 27)) - } - - @Test - def givenTwoIntegers_whenRangeSumcalled_thenCorrectValueReturned() = { - assertEquals(55, rangeSum(1, 10)) - } - - @Test - def givenPositiveInteger_whenFactorialInvoked_thenCorrectValueReturned() = { - assertEquals(720, factorial(6)) - } - - @Test - def whenFactorialOf0Invoked_then1Returned() = { - assertEquals(1, factorial(0)) - } - -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala deleted file mode 100644 index 0828752a8a..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.scala - -import org.junit.Assert.assertEquals -import org.junit.Test - -class EmployeeUnitTest { - - @Test - def whenEmployeeSalaryIncremented_thenCorrectSalary() = { - val employee = new Employee("John Doe", 1000) - employee.incrementSalary() - assertEquals(1020, employee.salary) - } - - @Test - def givenEmployee_whenToStringCalled_thenCorrectStringReturned() = { - val employee = new Employee("John Doe", 1000) - assertEquals("Employee(name=John Doe, salary=1000)", employee.toString) - } - - @Test - def givenEmployeeWithTrait_whenToStringCalled_thenCorrectStringReturned() = { - val employee = - new Employee("John Doe", 1000) with UpperCasePrinter - assertEquals("EMPLOYEE(NAME=JOHN DOE, SALARY=1000)", employee.toString) - } - -} - - diff --git a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsExamplesUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsExamplesUnitTest.scala deleted file mode 100644 index cb43266a48..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsExamplesUnitTest.scala +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.scala - -import org.junit.Assert.assertEquals -import org.junit.Test - - -class HigherOrderFunctionsExamplesUnitTest { - - @Test - def whenCallingMapWithAnonymousFunction_thenTransformationIsApplied() = { - val expected = Seq("sir Alex Ferguson", "sir Bobby Charlton", "sir Frank Lampard") - - val names = Seq("Alex Ferguson", "Bobby Charlton", "Frank Lampard") - val sirNames = names.map(name => "sir " + name) - - assertEquals(expected, sirNames) - } - - @Test - def whenCallingMapWithDefined_thenTransformationIsApplied() = { - val expected = Seq("sir Alex Ferguson", "sir Bobby Charlton", "sir Frank Lampard") - - val names = Seq("Alex Ferguson", "Bobby Charlton", "Frank Lampard") - - def prefixWithSir(name: String) = "sir " + name - val sirNames = names.map(prefixWithSir) - - assertEquals(expected, sirNames) - } - - @Test - def whenCallingFilter_thenUnecessaryElementsAreRemoved() = { - val expected = Seq("John O'Shea", "John Hartson") - - val names = Seq("John O'Shea", "Aiden McGeady", "John Hartson") - val johns = names.filter(name => name.matches("^John .*")) - - assertEquals(expected, johns) - } - - @Test - def whenCallingReduce_thenProperSumIsCalculated() = { - val expected = 2750 - - val earnings = Seq(1000, 1300, 450) - val sumEarnings = earnings.reduce((acc, x) => acc + x) - - assertEquals(expected, sumEarnings) - } - - @Test - def whenCallingFold_thenNumberOfWordsShouldBeCalculated() = { - val expected = 6 - - val strings = Seq("bunch of words", "just me", "it") - val sumEarnings = strings.foldLeft(0)((acc, x) => acc + x.split(" ").size) - - assertEquals(expected, sumEarnings) - } - - @Test - def whenCallingOwnHigherOrderFunction_thenProperFunctionIsReturned() = { - def mathOperation(name: String): (Int, Int) => Int = (x: Int, y: Int) => { - name match { - case "addition" => x + y - case "multiplication" => x * y - case "division" => x/y - case "subtraction" => x - y - } - } - - def add: (Int, Int) => Int = mathOperation("addition") - def mul: (Int, Int) => Int = mathOperation("multiplication") - def div: (Int, Int) => Int = mathOperation("division") - def sub: (Int, Int) => Int = mathOperation("subtraction") - - assertEquals(15, add(10, 5)) - assertEquals(50, mul(10, 5)) - assertEquals(2, div(10, 5)) - assertEquals(5, sub(10, 5)) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala deleted file mode 100644 index 240c879d7f..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.scala - -import com.baeldung.scala.HigherOrderFunctions.mapReduce -import org.junit.Assert.assertEquals -import org.junit.Test - -class HigherOrderFunctionsUnitTest { - - @Test - def whenCalledWithSumAndSquareFunctions_thenCorrectValueReturned() = { - def square(x : Int) = x * x - - def sum(x : Int, y : Int) = x + y - - def sumSquares(a : Int, b : Int) = - mapReduce(sum, 0, square, a, b) - - assertEquals(385, sumSquares(1, 10)) - } - - @Test - def whenComputingSumOfSquaresWithAnonymousFunctions_thenCorrectValueReturned() = { - def sumSquares(a : Int, b : Int) = - mapReduce((x, y) => x + y, 0, x => x * x, a, b) - - assertEquals(385, sumSquares(1, 10)) - } - - @Test - def givenCurriedFunctions_whenInvoked_thenCorrectValueReturned() = { - // a curried function - def sum(f : Int => Int)(a : Int, - b : Int) : Int = - if (a > b) 0 else f(a) + sum(f)(a + 1, b) - - // another curried function - def mod(n : Int)(x : Int) = x % n - - // application of a curried function - assertEquals(1, mod(5)(6)) - - // partial application of curried function - // trailing underscore is required to make function type explicit - val sumMod5 = sum(mod(5)) _ - - assertEquals(10, sumMod5(6, 10)) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala deleted file mode 100644 index ac27389d70..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.scala - -import org.junit.Assert.assertFalse -import org.junit.Test - -class IntSetUnitTest { - - @Test - def givenSetof1To10_whenContains11Called_thenFalse() = { - - // Set up a set containing integers 1 to 10. - val set1To10 = - Range(1, 10) - .foldLeft(new EmptyIntSet() : IntSet) { - (x, y) => x incl y - } - - assertFalse(set1To10 contains 11) - } - -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/PatternMatchingUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/PatternMatchingUnitTest.scala deleted file mode 100644 index 21a2f0e871..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/PatternMatchingUnitTest.scala +++ /dev/null @@ -1,208 +0,0 @@ -package com.baeldung.scala - -import java.io.FileNotFoundException - -import org.junit.Assert.assertEquals -import org.junit.Test - -class PatternMatchingUnitTest { - @Test - def whenAMammalIsGivenToTheMatchExpression_ThenItsRecognizedAsMammal(): Unit = { - val result = new PatternMatching().caseClassesPatternMatching(Mammal("Lion", fromSea = false)) - assertEquals("I'm a Lion, a kind of mammal. Am I from the sea? false", result) - } - - @Test - def whenABirdIsGivenToTheMatchExpression_ThenItsRecognizedAsBird(): Unit = { - val result = new PatternMatching().caseClassesPatternMatching(Bird("Pigeon")) - assertEquals("I'm a Pigeon, a kind of bird", result) - } - - @Test - def whenAnUnkownAnimalIsGivenToTheMatchExpression_TheDefaultClauseIsUsed(): Unit = { - val result = new PatternMatching().caseClassesPatternMatching(Fish("Tuna")) - assertEquals("I'm an unknown animal", result) - } - - @Test - def whenTheConstantZeroIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().constantsPatternMatching(0) - assertEquals("I'm equal to zero", result) - } - - @Test - def whenFourAndAHalfIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().constantsPatternMatching(4.5d) - assertEquals("I'm a double", result) - } - - @Test - def whenTheBooleanFalseIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().constantsPatternMatching(false) - assertEquals("I'm the contrary of true", result) - } - - @Test - def whenAnUnkownConstantIsPassed_ThenTheDefaultPatternIsUsed(): Unit = { - val result = new PatternMatching().constantsPatternMatching(true) - assertEquals("I'm unknown and equal to true", result) - } - - @Test - def whenASingleElementListIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(List("String")) - assertEquals("I'm a list with one element: String", result) - } - - @Test - def whenAMultipleElementsListIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(List("Multiple", "Elements")) - assertEquals("I'm a list with one or multiple elements: List(Multiple, Elements)", result) - } - - @Test - def whenAVectorBeginningWithOneAndTwoIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(Vector(1, 2, 3)) - assertEquals("I'm a vector: Vector(1, 2, 3)", result) - } - - @Test - def whenANotMatchingVectorIsPassed_ThenItShouldntMatchAndEnterTheDefaultClause(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(Vector(2, 1)) - assertEquals("I'm an unrecognized sequence. My value: Vector(2, 1)", result) - } - - @Test - def whenAnEmptyListIsPassed_ThenItShouldntMatchAndEnterTheDefaultClause(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(List()) - assertEquals("I'm an unrecognized sequence. My value: List()", result) - } - - @Test - def whenATwoElementsTupleIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().tuplesPatternMatching(("First", "Second")) - assertEquals("I'm a tuple with two elements: First & Second", result) - } - - @Test - def whenAThreeElementsTupleIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().tuplesPatternMatching(("First", "Second", "Third")) - assertEquals("I'm a tuple with three elements: First & Second & Third", result) - } - - @Test - def whenAnoterKindOfTupleIsPassed_ThenItShouldntMatchAndReturnTheDefaultPattern(): Unit = { - val result = new PatternMatching().tuplesPatternMatching(("First")) - assertEquals("Unrecognized pattern. My value: First", result) - } - - @Test - def whenAStringConsistingOfNumericsOnlyIsPassed_ThenItShouldMatchTheNumericRegex(): Unit = { - val result = new PatternMatching().regexPatterns("123") - assertEquals("I'm a numeric with value 123", result) - } - - @Test - def whenAStringConsistignOfAlphabeticsOnlyIsPassed_ThenItShouldMatchTheAlphabeticRegex(): Unit = { - val result = new PatternMatching().regexPatterns("abc") - assertEquals("I'm an alphabetic with value abc", result) - } - - @Test - def whenAStringConsistignOfAlphanumericsOnlyIsPassed_ThenItShouldMatchTheAlphanumericRegex(): Unit = { - val result = new PatternMatching().regexPatterns("abc123") - assertEquals("I'm an alphanumeric with value abc123", result) - } - - @Test - def whenAnotherTypeOfStringIsPassed_ThenItShouldntMatchAndReturnTheDefaultPattern(): Unit = { - val result = new PatternMatching().regexPatterns("abc_123") - assertEquals("I contain other characters than alphanumerics. My value abc_123", result) - } - - @Test - def whenAFilledOptionIsPassed_ThenItShouldMatchTheSomeClause(): Unit = { - val result = new PatternMatching().optionsPatternMatching(Option.apply("something")) - assertEquals("I'm not an empty option. Value something", result) - } - - @Test - def whenAnEmptyOptionIsPassed_ThenItShouldMatchTheNoneClause(): Unit = { - val result = new PatternMatching().optionsPatternMatching(Option.empty) - assertEquals("I'm an empty option", result) - } - - @Test - def whenAListWithAcceptedSizeIsPassed_ThenThePositiveMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards(List(1, 2), 3) - assertEquals("List is of acceptable size", result) - } - - @Test - def whenAListWithAnUnacceptedSizeIsPassed_ThenTheNegativeMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards(List(1, 2, 3, 4), 3) - assertEquals("List has not an acceptable size", result) - } - - @Test - def whenAStringWithAcceptedSizeIsPassed_ThenThePositiveMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards("OK", 3) - assertEquals("String is of acceptable size", result) - } - - @Test - def whenAStringWithAnUnacceptedSizeIsPassed_ThenTheNegativeMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards("Not OK", 3) - assertEquals("String has not an acceptable size", result) - } - - @Test - def whenAnObjectWhichIsNotAListOrAStringIsPassed_thenTheDefaultClauseIsUsed(): Unit = { - val result = new PatternMatching().patternGuards(1, 1) - assertEquals("Input is neither a List or a String", result) - } - - @Test - def whenACardSuitIsPassed_ThenTheCorrespondingMatchCaseClauseIsUsed(): Unit = { - assertEquals("Card is spike", new PatternMatching().sealedClass(Spike())) - assertEquals("Card is club", new PatternMatching().sealedClass(Club())) - assertEquals("Card is heart", new PatternMatching().sealedClass(Heart())) - assertEquals("Card is diamond", new PatternMatching().sealedClass(Diamond())) - } - - @Test - def whenAnObjectWithExtractorIsPassed_ThenTheExtractedValueIsUsedInTheCaseClause(): Unit = { - val person = Person("John Smith") - val result = new PatternMatching().extractors(person) - assertEquals("My initials are J. S.", result) - } - - @Test - def whenAnObjectWithExtractorIsPassed_AndTheValueIsEmpty_ThenTheDefaultCaseClauseIsUsed(): Unit = { - val person = Person("") - val result = new PatternMatching().extractors(person) - assertEquals("Could not extract initials", result) - } - - @Test - def whenAListOfRandomElementsIsPassed_ThenOnlyTheIntegersBelowTenAreReturned(): Unit = { - val input = List(1, 2, "5", 11, true) - val result = new PatternMatching().closuresPatternMatching(input) - assertEquals(List(1, 2), result) - } - - @Test - def whenAnExceptionIsPassed_ThenTheCorrespondingMessageIsReturned(): Unit = { - val pm = new PatternMatching() - - val iae = new IllegalArgumentException() - val re = new RuntimeException() - val fnfe = new FileNotFoundException() - - assertEquals("It's an IllegalArgumentException", pm.catchBlocksPatternMatching(iae)) - assertEquals("It's a RuntimeException", pm.catchBlocksPatternMatching(re)) - assertEquals("It's an unknown kind of exception", pm.catchBlocksPatternMatching(fnfe)) - } -} - - diff --git a/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala deleted file mode 100644 index e4995201d8..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.scala - -import com.baeldung.scala.Utils.{average, fibonacci, power, randomLessThan} -import org.junit.Assert.{assertEquals, assertTrue} -import org.junit.Test - -class UtilsUnitTest { - - @Test - def whenAverageCalled_thenCorrectValueReturned(): Unit = { - assertEquals(15.0, average(10, 20), 1e-5) - } - - @Test - def whenRandomLessThanInvokedWithANumber_thenARandomLessThanItReturned: Unit = { - val d = 0.1 - assertTrue(randomLessThan(d) < d) - } - - @Test - def whenPowerInvokedWith2And3_then8Returned: Unit = { - assertEquals(8, power(2, 3)) - } - - @Test - def whenFibonacciCalled_thenCorrectValueReturned: Unit = { - assertEquals(1, fibonacci(0)) - assertEquals(1, fibonacci(1)) - assertEquals(fibonacci(6), - fibonacci(4) + fibonacci(5)) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/regex/RegexUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/regex/RegexUnitTest.scala deleted file mode 100644 index 27ed9e1172..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/regex/RegexUnitTest.scala +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.scala.regex - -import org.junit.Test -import org.junit.Assert.assertEquals - -class RegexUnitTest { - private val polishPostalCode = "([0-9]{2})\\-([0-9]{3})".r - private val timestamp = "([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{3})".r - private val timestampUnanchored = timestamp.unanchored - - @Test - def givenRegularExpression_whenCallingFindFirstIn_thenShouldFindCorrectMatches(): Unit = { - val postCode = polishPostalCode.findFirstIn("Warsaw 01-011, Jerusalem Avenue") - assertEquals(Some("01-011"), postCode) - } - - @Test - def givenRegularExpression_whenCallingFindFirstMatchIn_thenShouldFindCorrectMatches(): Unit = { - val postCodes = polishPostalCode.findFirstMatchIn("Warsaw 01-011, Jerusalem Avenue") - assertEquals(Some("011"), for (m <- postCodes) yield m.group(2)) - } - - @Test - def givenRegularExpression_whenCallingFindAllIn_thenShouldFindCorrectMatches(): Unit = { - val postCodes = polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue") - .toList - assertEquals(List("01-011", "30-059"), postCodes) - - polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue") - } - - @Test - def givenRegularExpression_whenCallingFindAlMatchlIn_thenShouldFindCorrectMatches(): Unit = { - val postCodes = polishPostalCode.findAllMatchIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue") - .toList - val postalDistricts = for (m <- postCodes) yield m.group(1) - assertEquals(List("01", "30"), postalDistricts) - } - - @Test - def givenRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = { - val description = "11:34:01.411" match { - case timestamp(hour, minutes, _, _) => s"It's $minutes minutes after $hour" - } - - assertEquals("It's 34 minutes after 11", description) - } - - @Test - def givenUnanchoredRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = { - val description = "Timestamp: 11:34:01.411 error appeared" match { - case timestampUnanchored(hour, minutes, _, _) => s"It's $minutes minutes after $hour" - } - - assertEquals("It's 34 minutes after 11", description) - } - - @Test - def givenRegularExpression_whenCallingReplaceAllIn_thenShouldReplaceText(): Unit = { - val minutes = timestamp.replaceAllIn("11:34:01.311", m => m.group(2)) - - assertEquals("34", minutes) - } - - @Test - def givenRegularExpression_whenCallingReplaceAllInWithMatcher_thenShouldReplaceText(): Unit = { - val secondsThatDayInTotal = timestamp.replaceAllIn("11:34:01.311", _ match { - case timestamp(hours, minutes, seconds, _) => s"$hours-$minutes" - }) - - assertEquals("11-34", secondsThatDayInTotal) - } -} diff --git a/couchbase/pom.xml b/couchbase/pom.xml index f4e98b32ba..34e2832e55 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 couchbase 0.1-SNAPSHOT diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index a011b6a121..e0f38199ec 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.pmd custom-pmd diff --git a/dagger/pom.xml b/dagger/pom.xml index 528a5383c6..e9410ceb63 100644 --- a/dagger/pom.xml +++ b/dagger/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 dagger dagger @@ -44,4 +46,4 @@ 2.16 - \ No newline at end of file + diff --git a/data-structures/README.md b/data-structures/README.md index e8fb374f6c..f9ca78679a 100644 --- a/data-structures/README.md +++ b/data-structures/README.md @@ -9,3 +9,4 @@ This module contains articles about data structures in Java - [Circular Linked List Java Implementation](https://www.baeldung.com/java-circular-linked-list) - [How to Print a Binary Tree Diagram](https://www.baeldung.com/java-print-binary-tree-diagram) - [Introduction to Big Queue](https://www.baeldung.com/java-big-queue) +- [Guide to AVL Trees in Java](https://www.baeldung.com/java-avl-trees) diff --git a/data-structures/pom.xml b/data-structures/pom.xml index 4468f3d21f..e2d2e23090 100644 --- a/data-structures/pom.xml +++ b/data-structures/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 data-structures 0.0.1-SNAPSHOT diff --git a/ddd-modules/README.md b/ddd-modules/README.md index 5616cce48b..ba6b8d5016 100644 --- a/ddd-modules/README.md +++ b/ddd-modules/README.md @@ -1 +1,3 @@ -## Relevant Articles +### Relevant Articles: + +- [DDD Bounded Contexts and Java Modules](https://www.baeldung.com/java-modules-ddd-bounded-contexts) diff --git a/ddd-modules/infrastructure/pom.xml b/ddd-modules/infrastructure/pom.xml index 72ec263745..c301eaa92a 100644 --- a/ddd-modules/infrastructure/pom.xml +++ b/ddd-modules/infrastructure/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.infrastructure infrastructure diff --git a/ddd-modules/mainapp/pom.xml b/ddd-modules/mainapp/pom.xml index ae1057f307..a048263d37 100644 --- a/ddd-modules/mainapp/pom.xml +++ b/ddd-modules/mainapp/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.mainapp mainapp diff --git a/ddd-modules/ordercontext/pom.xml b/ddd-modules/ordercontext/pom.xml index 6a921d2408..abd166fb69 100644 --- a/ddd-modules/ordercontext/pom.xml +++ b/ddd-modules/ordercontext/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.ordercontext ordercontext diff --git a/ddd-modules/pom.xml b/ddd-modules/pom.xml index 65bc204988..38e48ff27d 100644 --- a/ddd-modules/pom.xml +++ b/ddd-modules/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules dddmodules diff --git a/ddd-modules/sharedkernel/pom.xml b/ddd-modules/sharedkernel/pom.xml index 3b5d8bb71f..a61f03a494 100644 --- a/ddd-modules/sharedkernel/pom.xml +++ b/ddd-modules/sharedkernel/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.sharedkernel sharedkernel diff --git a/ddd-modules/shippingcontext/pom.xml b/ddd-modules/shippingcontext/pom.xml index 060f4fe5bf..2096923f90 100644 --- a/ddd-modules/shippingcontext/pom.xml +++ b/ddd-modules/shippingcontext/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.shippingcontext shippingcontext diff --git a/ddd/pom.xml b/ddd/pom.xml index f27f1d24a9..7f3c417b71 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.ddd ddd @@ -21,8 +23,8 @@ spring-boot-starter-data-mongodb - org.springframework.boot - spring-boot-starter-data-cassandra + org.springframework.boot + spring-boot-starter-data-cassandra org.junit.jupiter @@ -97,4 +99,4 @@ 2.0.6.RELEASE - \ No newline at end of file + diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index c143b86ff8..c8fa18cbd4 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.deeplearning4j deeplearning4j diff --git a/disruptor/pom.xml b/disruptor/pom.xml index 94be78fad6..31fc28986b 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 disruptor 0.1.0-SNAPSHOT diff --git a/dozer/pom.xml b/dozer/pom.xml index e307354603..0fdf7f6fba 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 dozer 1.0 diff --git a/drools/pom.xml b/drools/pom.xml index b4421ff2e3..e0a7b52938 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 drools drools diff --git a/dropwizard/pom.xml b/dropwizard/pom.xml index ddc9aa1949..c3e1a4e841 100644 --- a/dropwizard/pom.xml +++ b/dropwizard/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 dropwizard 0.0.1-SNAPSHOT @@ -48,8 +49,7 @@ - + com.baeldung.dropwizard.introduction.IntroductionApplication diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 9a7aceb9e5..cca1b3a3d1 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 dubbo dubbo diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 8c7e4c8c4c..5953195123 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.ethereum ethereum diff --git a/feign/pom.xml b/feign/pom.xml index 6dc8e7bafa..4b994be1f2 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.feign feign diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index 8f7d058db7..566eed95d8 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 flyway-cdi-extension 1.0-SNAPSHOT diff --git a/geotools/pom.xml b/geotools/pom.xml index 71489bdf94..46913daa69 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 geotools 0.0.1-SNAPSHOT diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml index 15f7f5c824..1e474b5dd0 100644 --- a/google-cloud/pom.xml +++ b/google-cloud/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 google-cloud 0.1-SNAPSHOT diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index 37e423b3af..6fdcae4f75 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 google-web-toolkit @@ -53,8 +54,7 @@ - + ${project.build.directory}/${project.build.finalName}/WEB-INF/classes @@ -76,8 +76,7 @@ com.baeldung.Google_web_toolkit Google_web_toolkit true - + ${maven.compiler.source} @@ -109,9 +108,8 @@ - + 1.8 1.8 diff --git a/gradle-6/README.md b/gradle-6/README.md new file mode 100644 index 0000000000..a1ea96ad83 --- /dev/null +++ b/gradle-6/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [What’s New in Gradle 6.0](https://www.baeldung.com/gradle-6-features) diff --git a/gradle/gradle-to-maven/README.md b/gradle/gradle-to-maven/README.md new file mode 100644 index 0000000000..9acbfb1647 --- /dev/null +++ b/gradle/gradle-to-maven/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Converting Gradle Build File to Maven POM](https://www.baeldung.com/gradle-build-to-maven-pom) diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml index 793a02458a..30bfbf555a 100644 --- a/graphql/graphql-java/pom.xml +++ b/graphql/graphql-java/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.graphql graphql-java diff --git a/grpc/pom.xml b/grpc/pom.xml index c7ae111da3..5e1c0bb28b 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 grpc 0.0.1-SNAPSHOT diff --git a/gson/README.md b/gson/README.md index df6ba0f516..4255e2ead9 100644 --- a/gson/README.md +++ b/gson/README.md @@ -13,4 +13,4 @@ This module contains articles about Gson - [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject) - [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) - [Serializing and Deserializing a List with Gson](https://www.baeldung.com/gson-list) - +- [Compare Two JSON Objects with Gson](https://www.baeldung.com/gson-compare-json-objects) diff --git a/gson/pom.xml b/gson/pom.xml index f2ed5509fa..0de9a6a533 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 gson 0.1-SNAPSHOT diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml index 9002ac2b91..c6019362c5 100644 --- a/guava-collections/pom.xml +++ b/guava-collections/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 guava-collections 0.1.0-SNAPSHOT diff --git a/guava/pom.xml b/guava/pom.xml index 3f07b77b0b..df6d57bd09 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 guava 0.1.0-SNAPSHOT diff --git a/guice/pom.xml b/guice/pom.xml index d119bbf78e..6bbad6dddc 100644 --- a/guice/pom.xml +++ b/guice/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.examples.guice guice diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml index 10234bb81f..287542be33 100644 --- a/hazelcast/pom.xml +++ b/hazelcast/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 hazelcast 0.0.1-SNAPSHOT @@ -32,7 +34,7 @@ - + 0.6 diff --git a/image-processing/README.md b/image-processing/README.md index adb35c2318..50129bb994 100644 --- a/image-processing/README.md +++ b/image-processing/README.md @@ -4,3 +4,5 @@ This module contains articles about image processing. ### Relevant Articles: - [Working with Images in Java](https://www.baeldung.com/java-images) +- [Intro to OpenCV with Java](https://www.baeldung.com/java-opencv) +- [Optical Character Recognition with Tesseract](https://www.baeldung.com/java-ocr-tesseract) diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml index a2d9443d67..f8d19b5750 100644 --- a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml +++ b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 app-auth-form-store-ldap app-auth-form-store-ldap @@ -12,10 +13,6 @@ java-ee-8-security-api 1.0-SNAPSHOT - - - 4.0.4 - @@ -52,4 +49,8 @@ + + 4.0.4 + + diff --git a/java-numbers-3/README.md b/java-numbers-3/README.md index 08e8dae8ef..835b8b0b54 100644 --- a/java-numbers-3/README.md +++ b/java-numbers-3/README.md @@ -2,3 +2,4 @@ - [Generating Random Numbers](https://www.baeldung.com/java-generating-random-numbers) - [Convert Double to Long in Java](https://www.baeldung.com/java-convert-double-long) +- [Check for null Before Calling Parse in Double.parseDouble](https://www.baeldung.com/java-check-null-parse-double) diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java index dfea878a75..744bdfc8f5 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java @@ -12,7 +12,9 @@ import javax.batch.runtime.StepExecution; import com.baeldung.batch.understanding.BatchTestHelper; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Disabled; +@Disabled("Should be fixed in BAEL-3812") class CustomCheckPointUnitTest { @Test public void givenChunk_whenCustomCheckPoint_thenCommitCountIsThree() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java index 7c5e8d0b78..88b981df92 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java @@ -13,7 +13,9 @@ import javax.batch.runtime.JobExecution; import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Disabled; +@Disabled("Should be fixed in BAEL-3812") class JobSequenceUnitTest { @Test public void givenTwoSteps_thenBatch_CompleteWithSuccess() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java index 57c794ba00..5871143fa3 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java @@ -14,7 +14,9 @@ import javax.batch.runtime.Metric; import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Disabled; +@Disabled("Should be fixed in BAEL-3812") class SimpleChunkUnitTest { @Test public void givenChunk_thenBatch_CompletesWithSucess() throws Exception { diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index 60fc1acf92..5eaf761921 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -7,6 +7,12 @@ 0.0.1-SNAPSHOT war Bookstore + + + jhipster-5 + com.baeldung.jhipster + 1.0.0-SNAPSHOT + diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTest.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTest.java index 670042d2df..764d6b3587 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTest.java @@ -37,7 +37,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @see WebConfigurer */ -public class WebConfigurerTest { +public class WebConfigurerUnitTest { private WebConfigurer webConfigurer; @@ -116,7 +116,7 @@ public class WebConfigurerTest { props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerUnitTestController()) .addFilters(webConfigurer.corsFilter()) .build(); @@ -146,7 +146,7 @@ public class WebConfigurerTest { props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerUnitTestController()) .addFilters(webConfigurer.corsFilter()) .build(); @@ -161,7 +161,7 @@ public class WebConfigurerTest { public void testCorsFilterDeactivated() throws Exception { props.getCors().setAllowedOrigins(null); - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerUnitTestController()) .addFilters(webConfigurer.corsFilter()) .build(); @@ -176,7 +176,7 @@ public class WebConfigurerTest { public void testCorsFilterDeactivated2() throws Exception { props.getCors().setAllowedOrigins(new ArrayList<>()); - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerUnitTestController()) .addFilters(webConfigurer.corsFilter()) .build(); diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTestController.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTestController.java similarity index 87% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTestController.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTestController.java index c19b28ea16..ee72e1c80e 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTestController.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTestController.java @@ -4,7 +4,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController -public class WebConfigurerTestController { +public class WebConfigurerUnitTestController { @GetMapping("/api/test-cors") public void testCorsOnApiPath() { diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntegrationTest.java index eaf5c07504..948bf43f87 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntegrationTest.java @@ -33,7 +33,7 @@ import static com.baeldung.jhipster5.repository.CustomAuditEventRepository.EVENT @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) @Transactional -public class CustomAuditEventRepositoryIntTest { +public class CustomAuditEventRepositoryIntegrationTest { @Autowired private PersistenceAuditEventRepository persistenceAuditEventRepository; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntegrationTest.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntegrationTest.java index f11252de2b..11757f6516 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntegrationTest.java @@ -28,7 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) @Transactional -public class DomainUserDetailsServiceIntTest { +public class DomainUserDetailsServiceIntegrationTest { private static final String USER_ONE_LOGIN = "test-user-one"; private static final String USER_ONE_EMAIL = "test-user-one@localhost"; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterUnitTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterUnitTest.java index b3de21819b..2be8e6809a 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterUnitTest.java @@ -20,7 +20,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -public class JWTFilterTest { +public class JWTFilterUnitTest { private TokenProvider tokenProvider; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderUnitTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderUnitTest.java index 11fcfddbf9..18da2eb875 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderUnitTest.java @@ -22,7 +22,7 @@ import io.jsonwebtoken.security.Keys; import static org.assertj.core.api.Assertions.assertThat; -public class TokenProviderTest { +public class TokenProviderUnitTest { private final long ONE_MINUTE = 60000; private Key key; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntegrationTest.java index 4bde3276f5..72592e1239 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntegrationTest.java @@ -31,7 +31,7 @@ import static org.mockito.Mockito.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class MailServiceIntTest { +public class MailServiceIntegrationTest { @Autowired private JHipsterProperties jHipsterProperties; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntegrationTest.java index 81034c2793..ca3608462d 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntegrationTest.java @@ -38,7 +38,7 @@ import static org.mockito.Mockito.when; @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) @Transactional -public class UserServiceIntTest { +public class UserServiceIntegrationTest { @Autowired private UserRepository userRepository; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java index 3d66fa5813..cd6a326c06 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java @@ -26,7 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class UserMapperTest { +public class UserMapperUnitTest { private static final String DEFAULT_LOGIN = "johndoe"; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntegrationTest.java index 6db284a87f..f591b7ecbf 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntegrationTest.java @@ -49,7 +49,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class AccountResourceIntTest { +public class AccountResourceIntegrationTest { @Autowired private UserRepository userRepository; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntegrationTest.java index c3b91ab390..05d8f9d503 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntegrationTest.java @@ -35,7 +35,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) @Transactional -public class AuditResourceIntTest { +public class AuditResourceIntegrationTest { private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL"; private static final String SAMPLE_TYPE = "SAMPLE_TYPE"; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntegrationTest.java index ef8f27ceea..4f5cb25cdb 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntegrationTest.java @@ -43,7 +43,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class BookResourceIntTest { +public class BookResourceIntegrationTest { private static final String DEFAULT_TITLE = "AAAAAAAAAA"; private static final String UPDATED_TITLE = "BBBBBBBBBB"; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntegrationTest.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntegrationTest.java index 62f7f3f17c..b045f52f87 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntegrationTest.java @@ -27,7 +27,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class LogsResourceIntTest { +public class LogsResourceIntegrationTest { private MockMvc restLogsMockMvc; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntegrationTest.java index 3886710438..7cfc0e19fc 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntegrationTest.java @@ -33,7 +33,7 @@ import static org.hamcrest.Matchers.not; */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class UserJWTControllerIntTest { +public class UserJWTControllerIntegrationTest { @Autowired private TokenProvider tokenProvider; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntegrationTest.java index d31df3b15c..c0abc042fb 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntegrationTest.java @@ -42,7 +42,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class UserResourceIntTest { +public class UserResourceIntegrationTest { private static final String DEFAULT_LOGIN = "johndoe"; private static final String UPDATED_LOGIN = "jhipster"; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntegrationTest.java index a94d54063b..e5ef08ee9c 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntegrationTest.java @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class ExceptionTranslatorIntTest { +public class ExceptionTranslatorIntegrationTest { @Autowired private ExceptionTranslatorTestController controller; diff --git a/json-2/README.md b/json-2/README.md index b0f49f0e48..c2b6b36a11 100644 --- a/json-2/README.md +++ b/json-2/README.md @@ -4,3 +4,4 @@ This module contains articles about JSON. ### Relevant Articles: - [Introduction to Jsoniter](https://www.baeldung.com/java-jsoniter) +- [Introduction to Moshi Json](https://www.baeldung.com/java-json-moshi) diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpLiveTest.kt similarity index 97% rename from kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpLiveTest.kt index b7993c5f43..69b6ae88c6 100644 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt +++ b/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpLiveTest.kt @@ -12,7 +12,11 @@ import org.junit.jupiter.api.Test import java.io.File import java.util.concurrent.CountDownLatch -internal class FuelHttpUnitTest { +/** + * These live tests make connections to the external systems: http://httpbin.org, https://jsonplaceholder.typicode.com + * Make sure these hosts are up and your internet connection is on before running the tests. + */ +internal class FuelHttpLiveTest { @Test fun whenMakingAsyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { diff --git a/lagom/build.sbt b/lagom/build.sbt index 06927e3301..19aeccbd07 100644 --- a/lagom/build.sbt +++ b/lagom/build.sbt @@ -1,4 +1,4 @@ -organization in ThisBuild := "org.baeldung" +organization in ThisBuild := "com.baeldung" // the Scala version that will be used for cross-compiled libraries scalaVersion in ThisBuild := "2.11.8" diff --git a/lagom/greeting-api/src/main/java/org/baeldung/lagom/helloworld/greeting/api/GreetingService.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java similarity index 93% rename from lagom/greeting-api/src/main/java/org/baeldung/lagom/helloworld/greeting/api/GreetingService.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java index 93567f0185..e212c45437 100644 --- a/lagom/greeting-api/src/main/java/org/baeldung/lagom/helloworld/greeting/api/GreetingService.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.api; +package com.baeldung.lagom.helloworld.greeting.api; import static com.lightbend.lagom.javadsl.api.Service.named; import static com.lightbend.lagom.javadsl.api.Service.restCall; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java similarity index 94% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java index be9e713ec9..30d3930b75 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java similarity index 85% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java index 91fc74039d..125cf4bf38 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java @@ -1,9 +1,9 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import java.util.Optional; -import org.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; -import org.baeldung.lagom.helloworld.greeting.impl.GreetingEvent.ReceivedGreetingEvent; +import com.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; +import com.baeldung.lagom.helloworld.greeting.impl.GreetingEvent.ReceivedGreetingEvent; import com.lightbend.lagom.javadsl.persistence.PersistentEntity; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java similarity index 90% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java index e454f6cd1b..8800177add 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.lightbend.lagom.serialization.Jsonable; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java similarity index 85% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java index c28687291e..0c79b0d468 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java @@ -1,12 +1,12 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import org.baeldung.lagom.helloworld.greeting.api.GreetingService; -import org.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; -import org.baeldung.lagom.helloworld.weather.api.WeatherStats; +import com.baeldung.lagom.helloworld.greeting.api.GreetingService; +import com.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.weather.api.WeatherStats; import com.google.inject.Inject; import com.lightbend.lagom.javadsl.api.ServiceCall; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java similarity index 72% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java index 4813e91a7c..ba5142a5e6 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java @@ -1,7 +1,7 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; -import org.baeldung.lagom.helloworld.greeting.api.GreetingService; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.greeting.api.GreetingService; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; import com.google.inject.AbstractModule; import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingState.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java similarity index 89% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingState.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java index 125795601e..023c0510ae 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingState.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; diff --git a/lagom/greeting-impl/bin/application.conf b/lagom/greeting-impl/bin/application.conf index 1e78ce4a79..3fd21ae72b 100644 --- a/lagom/greeting-impl/bin/application.conf +++ b/lagom/greeting-impl/bin/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/greeting-impl/bin/classes/application.conf b/lagom/greeting-impl/bin/classes/application.conf index 1e78ce4a79..3fd21ae72b 100644 --- a/lagom/greeting-impl/bin/classes/application.conf +++ b/lagom/greeting-impl/bin/classes/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/greeting-impl/src/main/resources/application.conf b/lagom/greeting-impl/src/main/resources/application.conf index 1e78ce4a79..3fd21ae72b 100644 --- a/lagom/greeting-impl/src/main/resources/application.conf +++ b/lagom/greeting-impl/src/main/resources/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherService.java b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java similarity index 93% rename from lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherService.java rename to lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java index 888109322b..a0749222eb 100644 --- a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherService.java +++ b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.weather.api; +package com.baeldung.lagom.helloworld.weather.api; import static com.lightbend.lagom.javadsl.api.Service.named; import static com.lightbend.lagom.javadsl.api.Service.*; diff --git a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherStats.java b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java similarity index 93% rename from lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherStats.java rename to lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java index 23530a297d..aa04c5ad86 100644 --- a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherStats.java +++ b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.weather.api; +package com.baeldung.lagom.helloworld.weather.api; import java.util.Arrays; import java.util.Collections; diff --git a/lagom/weather-impl/bin/application.conf b/lagom/weather-impl/bin/application.conf index cf6cec2115..53d2dff8f2 100644 --- a/lagom/weather-impl/bin/application.conf +++ b/lagom/weather-impl/bin/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file diff --git a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java similarity index 67% rename from lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java rename to lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java index d7f97f9105..38e4b4d28f 100644 --- a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java +++ b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java @@ -1,9 +1,9 @@ -package org.baeldung.lagom.helloworld.weather.impl; +package com.baeldung.lagom.helloworld.weather.impl; import java.util.concurrent.CompletableFuture; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; -import org.baeldung.lagom.helloworld.weather.api.WeatherStats; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.weather.api.WeatherStats; import com.lightbend.lagom.javadsl.api.ServiceCall; diff --git a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java similarity index 78% rename from lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java rename to lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java index ac2834ff5c..85257ffa47 100644 --- a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java +++ b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java @@ -1,6 +1,6 @@ -package org.baeldung.lagom.helloworld.weather.impl; +package com.baeldung.lagom.helloworld.weather.impl; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; import com.google.inject.AbstractModule; import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; diff --git a/lagom/weather-impl/src/main/resources/application.conf b/lagom/weather-impl/src/main/resources/application.conf index cf6cec2115..53d2dff8f2 100644 --- a/lagom/weather-impl/src/main/resources/application.conf +++ b/lagom/weather-impl/src/main/resources/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file diff --git a/libraries-3/README.md b/libraries-3/README.md index 404045e6b1..f3c3375098 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -12,3 +12,7 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Guide to the Cactoos Library](https://www.baeldung.com/java-cactoos) - [Parsing Command-Line Parameters with Airline](https://www.baeldung.com/java-airline) - [Introduction to cache2k](https://www.baeldung.com/java-cache2k) +- [Introduction to the jcabi-aspects AOP Annotations Library](https://www.baeldung.com/java-jcabi-aspects) +- [Introduction to Takes](https://www.baeldung.com/java-takes) +- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) + diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index 68b5f2aa21..5334bfba70 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 + parent-modules + 1.0.0-SNAPSHOT @@ -24,39 +23,6 @@ lombok ${lombok.version} - - org.springframework.boot - spring-boot-starter-web - - - - net.sourceforge.barbecue - barbecue - ${barbecue.version} - - - - net.sf.barcode4j - barcode4j - ${barcode4j.version} - - - - com.google.zxing - core - ${zxing.version} - - - com.google.zxing - javase - ${zxing.version} - - - - com.github.kenglxn.qrgen - javase - ${qrgen.version} - com.github.rvesse airline @@ -89,11 +55,38 @@ takes ${takes.version} + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + org.apache.velocity velocity-engine-core ${velocity-engine-core.version} + + com.uber.nullaway + nullaway + 0.3.0 + + + org.codehaus.plexus + plexus-compiler-javac-errorprone + 2.8 + + + + com.google.errorprone + error_prone_core + 2.1.3 + @@ -102,7 +95,7 @@ https://jitpack.io - + libraries-3 @@ -130,6 +123,45 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 3.5 + + javac-with-errorprone + true + 1.8 + 1.8 + true + + + com.uber.nullaway + nullaway + 0.3.0 + + + + + + -XepExcludedPaths:(.*)/test/.*|(.*)/jcabi/.* + -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway + + + + + org.codehaus.plexus + plexus-compiler-javac-errorprone + 2.8 + + + + com.google.errorprone + error_prone_core + 2.3.4 + + + @@ -183,10 +215,6 @@ 1.78 1.18.6 - 1.5-beta1 - 2.1 - 3.3.0 - 2.6.0 0.43 2.7.2 @@ -198,6 +226,8 @@ 1.9.2 1.19 + 4.4.13 + 4.5.12 2.2 1.6.0 diff --git a/libraries/src/main/java/com/baeldung/nullaway/NullAwayExample.java b/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java similarity index 93% rename from libraries/src/main/java/com/baeldung/nullaway/NullAwayExample.java rename to libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java index f3db1d2df9..1fab591cb0 100644 --- a/libraries/src/main/java/com/baeldung/nullaway/NullAwayExample.java +++ b/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java @@ -1,7 +1,5 @@ package com.baeldung.nullaway; -import com.baeldung.distinct.Person; - public class NullAwayExample { /* diff --git a/libraries-3/src/main/java/com/baeldung/nullaway/Person.java b/libraries-3/src/main/java/com/baeldung/nullaway/Person.java new file mode 100644 index 0000000000..fcd88036a1 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/nullaway/Person.java @@ -0,0 +1,65 @@ +package com.baeldung.nullaway; + +public class Person { + int age; + String name; + String email; + + public Person(int age, String name, String email) { + super(); + this.age = age; + this.name = name; + this.email = email; + } + + public int getAge() { + return age; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [age="); + builder.append(age); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.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; + Person other = (Person) obj; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + return true; + } + +} diff --git a/libraries-data-io/README.md b/libraries-data-io/README.md index 550f353c97..3e68334ec9 100644 --- a/libraries-data-io/README.md +++ b/libraries-data-io/README.md @@ -9,3 +9,4 @@ This module contains articles about IO data processing libraries. - [Introduction To OpenCSV](https://www.baeldung.com/opencsv) - [Interact with Google Sheets from Java](https://www.baeldung.com/google-sheets-java-client) - [Introduction To Docx4J](https://www.baeldung.com/docx4j) +- [Breaking YAML Strings Over Multiple Lines](https://www.baeldung.com/yaml-multi-line) diff --git a/libraries/pom.xml b/libraries/pom.xml index af300657b0..41bc2b9311 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -435,23 +435,6 @@ reflections ${reflections.version} - - com.uber.nullaway - nullaway - 0.3.0 - - - org.codehaus.plexus - plexus-compiler-javac-errorprone - 2.8 - - - - com.google.errorprone - error_prone_core - 2.1.3 - @@ -569,46 +552,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 3.5 - - javac-with-errorprone - true - 1.8 - 1.8 - true - - - com.uber.nullaway - nullaway - 0.3.0 - - - - - - -XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.* - -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway - - - - - org.codehaus.plexus - plexus-compiler-javac-errorprone - 2.8 - - - - com.google.errorprone - error_prone_core - 2.1.3 - - - - diff --git a/machine-learning/pom.xml b/machine-learning/pom.xml index 24162b7b9c..99b7e33579 100644 --- a/machine-learning/pom.xml +++ b/machine-learning/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 machine-learning 1.0-SNAPSHOT @@ -13,23 +15,6 @@ 1.0.0-SNAPSHOT - - UTF-8 - 1.7 - 1.7 - 1.3.50 - 0.9.1 - 3.1.0 - 3.0.2 - 3.0.2 - 3.8.0 - 2.22.1 - 2.5.2 - 2.8.2 - 3.7.1 - 3.0.0 - - org.jetbrains.kotlin @@ -158,4 +143,21 @@ + + UTF-8 + 1.7 + 1.7 + 1.3.50 + 0.9.1 + 3.1.0 + 3.0.2 + 3.0.2 + 3.8.0 + 2.22.1 + 2.5.2 + 2.8.2 + 3.7.1 + 3.0.0 + + diff --git a/maven-all/maven-custom-plugin/usage-example/pom.xml b/maven-all/maven-custom-plugin/usage-example/pom.xml index bd2b16475e..ef6f08a3fb 100644 --- a/maven-all/maven-custom-plugin/usage-example/pom.xml +++ b/maven-all/maven-custom-plugin/usage-example/pom.xml @@ -1,18 +1,14 @@ - + 4.0.0 com.baeldung example 0.0.1-SNAPSHOT pom - - 3.9 - 4.12 - - org.apache.commons @@ -47,4 +43,9 @@ + + 3.9 + 4.12 + + diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-archetype/src/main/resources/archetype-resources/pom.xml index 2a73687e2c..fc568349bc 100644 --- a/maven-archetype/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetype/src/main/resources/archetype-resources/pom.xml @@ -1,23 +1,13 @@ - + 4.0.0 ${groupId} ${artifactId} ${version} war - - UTF-8 - 1.8 - 1.8 - false - ${liberty-plugin-version} - 9080 - 9443 - 2.0 - 2.1 - - ${artifactId} @@ -80,4 +70,16 @@ + + UTF-8 + 1.8 + 1.8 + false + ${liberty-plugin-version} + 9080 + 9443 + 2.0 + 2.1 + + diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml index cfa59bdc39..cf6ea85cb5 100644 --- a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.userdaomodule userdaomodule @@ -14,11 +16,6 @@ 1.0 - - 1.0 - 1.0 - - com.baeldung.entitymodule @@ -37,4 +34,9 @@ + + 1.0 + 1.0 + + diff --git a/ninja/pom.xml b/ninja/pom.xml index afb1d509b8..9b80dc26c8 100644 --- a/ninja/pom.xml +++ b/ninja/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 ninja @@ -10,19 +12,34 @@ http://www.ninjaframework.org - - 6.5.0 - 9.4.18.v20190429 - 3.3.4 - 2.1.3 - 1.4.186 - 3.2 - 1.8 - 1.8 - 1.3.1 - 2.8.2 - 2.2 - + + + org.webjars + bootstrap + ${bootstrap.version} + + + org.webjars + jquery + ${jquery.version} + + + com.h2database + h2 + ${h2.version} + + + org.ninjaframework + ninja-standalone + ${ninja.version} + + + org.ninjaframework + ninja-test-utilities + ${ninja.version} + test + + @@ -131,10 +148,8 @@ - - + + ninja.standalone.NinjaJetty @@ -161,32 +176,19 @@ - - - org.webjars - bootstrap - ${bootstrap.version} - - - org.webjars - jquery - ${jquery.version} - - - com.h2database - h2 - ${h2.version} - - - org.ninjaframework - ninja-standalone - ${ninja.version} - - - org.ninjaframework - ninja-test-utilities - ${ninja.version} - test - - + + + 6.5.0 + 9.4.18.v20190429 + 3.3.4 + 2.1.3 + 1.4.186 + 3.2 + 1.8 + 1.8 + 1.3.1 + 2.8.2 + 2.2 + + \ No newline at end of file diff --git a/open-liberty/README.md b/open-liberty/README.md new file mode 100644 index 0000000000..6a51d2c486 --- /dev/null +++ b/open-liberty/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Open Liberty](https://www.baeldung.com/java-open-liberty) diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index e3d67eaaf2..52a753439c 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -31,7 +31,7 @@ spring-milestone Spring Milestone Repository - http://repo.spring.io/milestone + https://repo.spring.io/milestone diff --git a/pdf/pom.xml b/pdf/pom.xml index 88836c5ce9..d148aa1670 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -13,12 +13,6 @@ - - commons-codec - commons-codec - ${commons-codec.version} - - org.apache.pdfbox pdfbox-tools @@ -86,7 +80,6 @@ 3.15 1.8 3.15 - 1.14 diff --git a/persistence-modules/hibernate-annotations/README.md b/persistence-modules/hibernate-annotations/README.md new file mode 100644 index 0000000000..2813dbdda3 --- /dev/null +++ b/persistence-modules/hibernate-annotations/README.md @@ -0,0 +1,10 @@ +## Hibernate Annotations + +This module contains articles about Hibernate Annotations. + +### Relevant Articles: +- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) +- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) +- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) +- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) +- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) diff --git a/persistence-modules/hibernate5-2/pom.xml b/persistence-modules/hibernate-annotations/pom.xml similarity index 64% rename from persistence-modules/hibernate5-2/pom.xml rename to persistence-modules/hibernate-annotations/pom.xml index 15d42b3244..5367921f31 100644 --- a/persistence-modules/hibernate5-2/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - hibernate5-2 + hibernate-annotations 0.1-SNAPSHOT - hibernate5-2 + hibernate-annotations jar Hibernate tutorial illustrating the use of named parameters @@ -20,32 +20,6 @@ hibernate-core ${hibernate-core.version} - - org.springframework.boot - spring-boot-starter-web - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-thymeleaf - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-data-jpa - ${spring-boot.version} - - - com.zaxxer - HikariCP - - - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - com.h2database @@ -58,7 +32,32 @@ commons-lang3 ${commons.lang3.version} + + + org.hibernate + hibernate-testing + ${hibernate-core.version} + + + + org.hibernate + hibernate-spatial + ${hibernate-core.version} + + + org.opengeo + geodb + ${geodb.version} + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + 5.4.7.Final @@ -69,6 +68,7 @@ 5.4.7.Final 1.4.200 3.8.1 + 0.9 diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..afe2aeac89 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.joincolumn.Email; +import com.baeldung.hibernate.joincolumn.Office; +import com.baeldung.hibernate.joincolumn.OfficeAddress; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); + metadataSources.addAnnotatedClass(Email.class); + metadataSources.addAnnotatedClass(Office.class); + metadataSources.addAnnotatedClass(OfficeAddress.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java diff --git a/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/main/resources/logback.xml b/persistence-modules/hibernate-annotations/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate-annotations/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/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties rename to persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties diff --git a/persistence-modules/hibernate5-2/src/test/resources/log4j.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/test/resources/log4j.xml rename to persistence-modules/hibernate-annotations/src/test/resources/log4j.xml diff --git a/persistence-modules/hibernate5-2/src/test/resources/log4j2.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j2.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/test/resources/log4j2.xml rename to persistence-modules/hibernate-annotations/src/test/resources/log4j2.xml diff --git a/persistence-modules/hibernate5-2/src/test/resources/logback.xml b/persistence-modules/hibernate-annotations/src/test/resources/logback.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/test/resources/logback.xml rename to persistence-modules/hibernate-annotations/src/test/resources/logback.xml diff --git a/persistence-modules/hibernate-annotations/src/test/resources/profile.png b/persistence-modules/hibernate-annotations/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-annotations/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-enterprise/README.md b/persistence-modules/hibernate-enterprise/README.md new file mode 100644 index 0000000000..c48092e6a2 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/README.md @@ -0,0 +1,12 @@ +## Hibernate Enterprise + +This module contains articles about Hibernate. + +### Relevant articles: + +- [Introduction to Hibernate Spatial](http://www.baeldung.com/hibernate-spatial) +- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy) +- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) +- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) +- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) +- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml new file mode 100644 index 0000000000..060cb4c904 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + hibernate-enterprise + 0.0.1-SNAPSHOT + hibernate-enterprise + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + + + diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..ddeb1c42ea --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(PointEntity.class); + metadataSources.addAnnotatedClass(PolygonEntity.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java new file mode 100644 index 0000000000..736abde866 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -0,0 +1,43 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Point; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PointEntity { + + @Id + @GeneratedValue + private Long id; + + @Column(columnDefinition="BINARY(2048)") + private Point point; + + public PointEntity() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Point getPoint() { + return point; + } + + public void setPoint(Point point) { + this.point = point; + } + + @Override + public String toString() { + return "PointEntity{" + "id=" + id + ", point=" + point + '}'; + } +} diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java new file mode 100644 index 0000000000..69208c8cd4 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Polygon; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PolygonEntity { + + @Id + @GeneratedValue + private Long id; + + private Polygon polygon; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Polygon getPolygon() { + return polygon; + } + + public void setPolygon(Polygon polygon) { + this.polygon = polygon; + } + + @Override + public String toString() { + return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}'; + } +} diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + 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; + } + +} diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml b/persistence-modules/hibernate-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml diff --git a/persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml b/persistence-modules/hibernate-enterprise/src/main/resources/hibernate-logging.cfg.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/hibernate-logging.cfg.xml diff --git a/persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml b/persistence-modules/hibernate-enterprise/src/main/resources/hibernate.cfg.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/hibernate.cfg.xml diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql b/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/logback.xml b/persistence-modules/hibernate-enterprise/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/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/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java similarity index 100% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-multitenancy.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-multitenancy.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb1.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb1.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb2.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb2.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-schema-multitenancy.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-schema-multitenancy.properties diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties new file mode 100644 index 0000000000..1657c838e3 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate.properties diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/profile.png b/persistence-modules/hibernate-enterprise/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-enterprise/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-jpa/README.md b/persistence-modules/hibernate-jpa/README.md new file mode 100644 index 0000000000..fb1d46cf9b --- /dev/null +++ b/persistence-modules/hibernate-jpa/README.md @@ -0,0 +1,15 @@ +## Hibernate JPA + +This module contains articles about Hibernate JPA. + +### Relevant articles: + +- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters) +- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) +- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) +- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking) +- [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) +- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) +- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) +- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) +- [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) diff --git a/persistence-modules/hibernate-jpa/pom.xml b/persistence-modules/hibernate-jpa/pom.xml new file mode 100644 index 0000000000..67f40d5017 --- /dev/null +++ b/persistence-modules/hibernate-jpa/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + hibernate-jpa + 0.0.1-SNAPSHOT + hibernate-jpa + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-thymeleaf + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + com.zaxxer + HikariCP + + + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk-jmh.version} + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 1.21 + 2.1.7.RELEASE + + + diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..cf59fe4855 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; +import com.baeldung.hibernate.pessimisticlocking.Individual; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; +import com.baeldung.hibernate.pojo.Person; +import com.baeldung.hibernate.pojo.Post; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Person.class); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(Individual.class); + metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class); + metadataSources.addAnnotatedClass(PessimisticLockingStudent.class); + metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); + metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); + metadataSources.addAnnotatedClass(Post.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java similarity index 93% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java index c2f276472e..18fa2a41db 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java @@ -1,6 +1,5 @@ package com.baeldung.hibernate.onetoone; -import com.baeldung.hibernate.customtypes.LocalDateStringType; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; @@ -33,7 +32,6 @@ public class HibernateUtil { } Metadata metadata = metadataSources.getMetadataBuilder() - .applyBasicType(LocalDateStringType.INSTANCE) .build(); return metadata.getSessionFactoryBuilder() diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java new file mode 100644 index 0000000000..5fae7f6a97 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java @@ -0,0 +1,52 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "MOVIE") +public class Movie { + + @Id + private Long id; + + private String movieName; + + private Integer releaseYear; + + private String language; + + public String getMovieName() { + return movieName; + } + + public void setMovieName(String movieName) { + this.movieName = movieName; + } + + public Integer getReleaseYear() { + return releaseYear; + } + + public void setReleaseYear(Integer releaseYear) { + this.releaseYear = releaseYear; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java new file mode 100644 index 0000000000..335fe73f75 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.pojo; + +import java.io.Serializable; + +public class PersonName implements Serializable { + + private static final long serialVersionUID = 7883094644631050150L; + + private String name; + + private String surname; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } + +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java new file mode 100644 index 0000000000..25e51e35d0 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "posts") +public class Post { + + @Id + @GeneratedValue + private int id; + + private String title; + + private String body; + + public Post() { } + + public Post(String title, String body) { + this.title = title; + this.body = body; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + @Override + public String toString() { + return "Post{" + + "id=" + id + + ", title='" + title + '\'' + + ", body='" + body + '\'' + + '}'; + } +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + 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; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..4dfade1af3 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,19 @@ + + + + Hibernate EntityManager Demo + com.baeldung.hibernate.pojo.Movie + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql b/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/logback.xml b/persistence-modules/hibernate-jpa/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate-jpa/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/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-namedquery.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties rename to persistence-modules/hibernate-jpa/src/test/resources/hibernate-namedquery.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties rename to persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties diff --git a/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-jpa/src/test/resources/profile.png b/persistence-modules/hibernate-jpa/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-jpa/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 5bbdeecbea..5ba73f35f3 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -7,5 +7,9 @@ This module contains articles about Object-relational Mapping (ORM) with Hiberna - [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) - [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) - [Hibernate Validator Specific Constraints](https://www.baeldung.com/hibernate-validator-constraints) -- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) -- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) +- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) +- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) +- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) +- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) +- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) +- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode) diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index ac7952fa2b..4eabc5d298 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -51,15 +51,28 @@ ${moneta.version} pom + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + commons-io + commons-io + ${commons-io.version} + + - 5.3.10.Final + 5.4.12.Final 3.8.0 6.0.16.Final 3.0.1-b11 1.0.3 1.3 + 3.9 + 2.6 diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 7de13db8d3..fbd8bd487b 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,21 +1,48 @@ package com.baeldung.hibernate; -import org.hibernate.SessionFactory; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.service.ServiceRegistry; - import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.Properties; -public class HibernateUtil { +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; private HibernateUtil() { } + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(""); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + if(propertyFileName.equals("")) propertyFileName = null; + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + public static SessionFactory getSessionFactory(Strategy strategy) { return buildSessionFactory(strategy); } @@ -40,6 +67,35 @@ public class HibernateUtil { } } + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Employee.class); + metadataSources.addAnnotatedClass(Phone.class); + metadataSources.addAnnotatedClass(EntityDescription.class); + metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(Animal.class); + metadataSources.addAnnotatedClass(Bag.class); + metadataSources.addAnnotatedClass(Book.class); + metadataSources.addAnnotatedClass(Car.class); + metadataSources.addAnnotatedClass(MyEmployee.class); + metadataSources.addAnnotatedClass(MyProduct.class); + metadataSources.addAnnotatedClass(Pen.class); + metadataSources.addAnnotatedClass(Pet.class); + metadataSources.addAnnotatedClass(Vehicle.class); + + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + private static ServiceRegistry configureServiceRegistry() throws IOException { Properties properties = getProperties(); @@ -51,7 +107,7 @@ public class HibernateUtil { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() - .getResource("hibernate.properties"); + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java new file mode 100644 index 0000000000..e9732b2b67 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java @@ -0,0 +1,87 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.*; + +import javax.persistence.Entity; +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Where(clause = "deleted = false") +@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int")) +@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit") +public class Employee implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private long grossIncome; + + private int taxInPercents; + + private boolean deleted; + + public long getTaxJavaWay() { + return grossIncome * taxInPercents / 100; + } + + @Formula("grossIncome * taxInPercents / 100") + private long tax; + + @OneToMany + @JoinColumn(name = "employee_id") + @Where(clause = "deleted = false") + private Set phones = new HashSet<>(0); + + public Employee() { + } + + public Employee(long grossIncome, int taxInPercents) { + this.grossIncome = grossIncome; + this.taxInPercents = taxInPercents; + } + + public Integer getId() { + return id; + } + + public long getGrossIncome() { + return grossIncome; + } + + public int getTaxInPercents() { + return taxInPercents; + } + + public long getTax() { + return tax; + } + + public void setId(Integer id) { + this.id = id; + } + + public void setGrossIncome(long grossIncome) { + this.grossIncome = grossIncome; + } + + public void setTaxInPercents(int taxInPercents) { + this.taxInPercents = taxInPercents; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public Set getPhones() { + return phones; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java new file mode 100644 index 0000000000..131bb73a80 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java @@ -0,0 +1,55 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.Any; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class EntityDescription implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private String description; + + @Any( + metaDef = "EntityDescriptionMetaDef", + metaColumn = @Column(name = "entity_type") + ) + @JoinColumn(name = "entity_id") + private Serializable entity; + + public EntityDescription() { + } + + public EntityDescription(String description, Serializable entity) { + this.description = description; + this.entity = entity; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Serializable getEntity() { + return entity; + } + + public void setEntity(Serializable entity) { + this.entity = entity; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java new file mode 100644 index 0000000000..607269a267 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +public class Result { + private String employeeName; + + private String departmentName; + + public Result(String employeeName, String departmentName) { + this.employeeName = employeeName; + this.departmentName = departmentName; + } + + public Result() { + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public String getDepartmentName() { + return departmentName; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java new file mode 100644 index 0000000000..f3fe095cae --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java @@ -0,0 +1,195 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.*; +import java.io.Serializable; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.*; +import java.util.Calendar; + +@Entity +public class TemporalValues implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @Basic + private java.sql.Date sqlDate; + + @Basic + private java.sql.Time sqlTime; + + @Basic + private java.sql.Timestamp sqlTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Date utilDate; + + @Basic + @Temporal(TemporalType.TIME) + private java.util.Date utilTime; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Date utilTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Calendar calendarDate; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Calendar calendarTimestamp; + + @Basic + private java.time.LocalDate localDate; + + @Basic + private java.time.LocalTime localTime; + + @Basic + private java.time.OffsetTime offsetTime; + + @Basic + private java.time.Instant instant; + + @Basic + private java.time.LocalDateTime localDateTime; + + @Basic + private java.time.OffsetDateTime offsetDateTime; + + @Basic + private java.time.ZonedDateTime zonedDateTime; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(Date sqlDate) { + this.sqlDate = sqlDate; + } + + public Time getSqlTime() { + return sqlTime; + } + + public void setSqlTime(Time sqlTime) { + this.sqlTime = sqlTime; + } + + public Timestamp getSqlTimestamp() { + return sqlTimestamp; + } + + public void setSqlTimestamp(Timestamp sqlTimestamp) { + this.sqlTimestamp = sqlTimestamp; + } + + public java.util.Date getUtilDate() { + return utilDate; + } + + public void setUtilDate(java.util.Date utilDate) { + this.utilDate = utilDate; + } + + public java.util.Date getUtilTime() { + return utilTime; + } + + public void setUtilTime(java.util.Date utilTime) { + this.utilTime = utilTime; + } + + public java.util.Date getUtilTimestamp() { + return utilTimestamp; + } + + public void setUtilTimestamp(java.util.Date utilTimestamp) { + this.utilTimestamp = utilTimestamp; + } + + public Calendar getCalendarDate() { + return calendarDate; + } + + public void setCalendarDate(Calendar calendarDate) { + this.calendarDate = calendarDate; + } + + public Calendar getCalendarTimestamp() { + return calendarTimestamp; + } + + public void setCalendarTimestamp(Calendar calendarTimestamp) { + this.calendarTimestamp = calendarTimestamp; + } + + public LocalDate getLocalDate() { + return localDate; + } + + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } + + public LocalTime getLocalTime() { + return localTime; + } + + public void setLocalTime(LocalTime localTime) { + this.localTime = localTime; + } + + public OffsetTime getOffsetTime() { + return offsetTime; + } + + public void setOffsetTime(OffsetTime offsetTime) { + this.offsetTime = offsetTime; + } + + public Instant getInstant() { + return instant; + } + + public void setInstant(Instant instant) { + this.instant = instant; + } + + public LocalDateTime getLocalDateTime() { + return localDateTime; + } + + public void setLocalDateTime(LocalDateTime localDateTime) { + this.localDateTime = localDateTime; + } + + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } + + public void setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } + + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + + public void setZonedDateTime(ZonedDateTime zonedDateTime) { + this.zonedDateTime = zonedDateTime; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java new file mode 100644 index 0000000000..17ffe9b7e1 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.pojo.generator; + +import java.io.Serializable; +import java.util.Properties; +import java.util.stream.Stream; + +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.id.Configurable; +import org.hibernate.id.IdentifierGenerator; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.type.Type; + +public class MyGenerator implements IdentifierGenerator, Configurable { + + private String prefix; + + @Override + public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException { + + String query = String.format("select %s from %s", + session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(), + obj.getClass().getSimpleName()); + + Stream ids = session.createQuery(query).stream(); + + Long max = ids.map(o -> o.replace(prefix + "-", "")) + .mapToLong(Long::parseLong) + .max() + .orElse(0L); + + return prefix + "-" + (max + 1); + } + + @Override + public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException { + prefix = properties.getProperty("prefix"); + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java new file mode 100644 index 0000000000..6fe7f915fc --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.JOINED) +public class Animal { + + @Id + private long animalId; + + private String species; + + public Animal() {} + + public Animal(long animalId, String species) { + this.animalId = animalId; + this.species = species; + } + + public long getAnimalId() { + return animalId; + } + + public void setAnimalId(long animalId) { + this.animalId = animalId; + } + + public String getSpecies() { + return species; + } + + public void setSpecies(String species) { + this.species = species; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java new file mode 100644 index 0000000000..fa6e1b4bef --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.hibernate.annotations.Polymorphism; +import org.hibernate.annotations.PolymorphismType; + +@Entity +@Polymorphism(type = PolymorphismType.EXPLICIT) +public class Bag implements Item { + + @Id + private long bagId; + + private String type; + + public Bag(long bagId, String type) { + this.bagId = bagId; + this.type = type; + } + + public long getBagId() { + return bagId; + } + + public void setBagId(long bagId) { + this.bagId = bagId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java new file mode 100644 index 0000000000..36ca8dd77c --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("1") +public class Book extends MyProduct { + private String author; + + public Book() { + } + + public Book(long productId, String name, String author) { + super(productId, name); + this.author = author; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java new file mode 100644 index 0000000000..49d1f7749a --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class Car extends Vehicle { + private String engine; + + public Car() { + } + + public Car(long vehicleId, String manufacturer, String engine) { + super(vehicleId, manufacturer); + this.engine = engine; + } + + public String getEngine() { + return engine; + } + + public void setEngine(String engine) { + this.engine = engine; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java new file mode 100644 index 0000000000..9656030736 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java @@ -0,0 +1,5 @@ +package com.baeldung.hibernate.pojo.inheritance; + +public interface Item { + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java new file mode 100644 index 0000000000..9a6bce16cf --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java @@ -0,0 +1,22 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class MyEmployee extends Person { + private String company; + + public MyEmployee(long personId, String name, String company) { + super(personId, name); + this.company = company; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java new file mode 100644 index 0000000000..13f04d8904 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +import org.hibernate.annotations.DiscriminatorFormula; + +@Entity +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "product_type", discriminatorType = DiscriminatorType.INTEGER) +// @DiscriminatorFormula("case when author is not null then 1 else 2 end") +public class MyProduct { + @Id + private long productId; + + private String name; + + public MyProduct() { + } + + public MyProduct(long productId, String name) { + super(); + this.productId = productId; + this.name = name; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java new file mode 100644 index 0000000000..32b77e52af --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("2") +public class Pen extends MyProduct { + private String color; + + public Pen() { + } + + public Pen(long productId, String name, String color) { + super(productId, name); + this.color = color; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java new file mode 100644 index 0000000000..99084b88af --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public class Person { + + @Id + private long personId; + + private String name; + + public Person() { + } + + public Person(long personId, String name) { + this.personId = personId; + this.name = name; + } + + public long getPersonId() { + return personId; + } + + public void setPersonId(long personId) { + this.personId = personId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java new file mode 100644 index 0000000000..870b3cd684 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.PrimaryKeyJoinColumn; + +@Entity +@PrimaryKeyJoinColumn(name = "petId") +public class Pet extends Animal { + private String name; + + public Pet() { + } + + public Pet(long animalId, String species, String name) { + super(animalId, species); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java new file mode 100644 index 0000000000..b2a920573e --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) +public class Vehicle { + @Id + private long vehicleId; + + private String manufacturer; + + public Vehicle() { + } + + public Vehicle(long vehicleId, String manufacturer) { + this.vehicleId = vehicleId; + this.manufacturer = manufacturer; + } + + public long getVehicleId() { + return vehicleId; + } + + public void setVehicleId(long vehicleId) { + this.vehicleId = vehicleId; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java new file mode 100644 index 0000000000..992cda7c1d --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java @@ -0,0 +1,9 @@ +@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int", + metaValues = { + @MetaValue(value = "Employee", targetEntity = Employee.class), + @MetaValue(value = "Phone", targetEntity = Phone.class) + }) +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.AnyMetaDef; +import org.hibernate.annotations.MetaValue; \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties b/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping/src/test/resources/profile.png b/persistence-modules/hibernate-mapping/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-mapping/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-queries/README.md b/persistence-modules/hibernate-queries/README.md new file mode 100644 index 0000000000..61d94e32de --- /dev/null +++ b/persistence-modules/hibernate-queries/README.md @@ -0,0 +1,10 @@ +## Hibernate Queries + +This module contains articles about use of Queries in Hibernate. + +### Relevant articles: + +- [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 diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml new file mode 100644 index 0000000000..a439ded9df --- /dev/null +++ b/persistence-modules/hibernate-queries/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + hibernate-queries + 0.0.1-SNAPSHOT + hibernate-queries + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk-jmh.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + 1.21 + + + diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..58724e690c --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.customtypes.LocalDateStringType; +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java new file mode 100644 index 0000000000..56be9e693f --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.type.LocalDateType; +import org.hibernate.type.descriptor.WrapperOptions; +import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; +import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; +import org.hibernate.type.descriptor.java.MutabilityPlan; + +import java.time.LocalDate; + +public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { + + public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); + + public LocalDateStringJavaDescriptor() { + super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE); + } + + @Override + public String toString(LocalDate value) { + return LocalDateType.FORMATTER.format(value); + } + + @Override + public LocalDate fromString(String string) { + return LocalDate.from(LocalDateType.FORMATTER.parse(string)); + } + + @Override + public X unwrap(LocalDate value, Class type, WrapperOptions options) { + + if (value == null) + return null; + + if (String.class.isAssignableFrom(type)) + return (X) LocalDateType.FORMATTER.format(value); + + throw unknownUnwrap(type); + } + + @Override + public LocalDate wrap(X value, WrapperOptions options) { + if (value == null) + return null; + + if(String.class.isInstance(value)) + return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value)); + + throw unknownWrap(value.getClass()); + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java new file mode 100644 index 0000000000..c8d37073e8 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.dialect.Dialect; +import org.hibernate.type.AbstractSingleColumnStandardBasicType; +import org.hibernate.type.DiscriminatorType; +import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor; +import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; + +import java.time.LocalDate; + +public class LocalDateStringType extends AbstractSingleColumnStandardBasicType implements DiscriminatorType { + + public static final LocalDateStringType INSTANCE = new LocalDateStringType(); + + public LocalDateStringType() { + super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); + } + + @Override + public String getName() { + return "LocalDateString"; + } + + @Override + public LocalDate stringToObject(String xml) throws Exception { + return fromString(xml); + } + + @Override + public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception { + return '\'' + toString(value) + '\''; + } + +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + 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; + } + +} diff --git a/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/resources/init_database.sql b/persistence-modules/hibernate-queries/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/resources/logback.xml b/persistence-modules/hibernate-queries/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate-queries/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/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java diff --git a/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties new file mode 100644 index 0000000000..457f965347 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql' +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/profile.png b/persistence-modules/hibernate-queries/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-queries/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate5-2/README.md b/persistence-modules/hibernate5-2/README.md deleted file mode 100644 index 330708f6d3..0000000000 --- a/persistence-modules/hibernate5-2/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Hibernate 5 - -This module contains articles about Hibernate 5. - -### Relevant Articles: -- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) -- [FetchMode in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-fetchmode) -- [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) -- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode) -- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) -- [[<-- Prev]](/hibernate5) diff --git a/persistence-modules/hibernate5-mapping/README.md b/persistence-modules/hibernate5-mapping/README.md new file mode 100644 index 0000000000..f18b0b63de --- /dev/null +++ b/persistence-modules/hibernate5-mapping/README.md @@ -0,0 +1,11 @@ +## Hibernate 5 + +This module contains articles about Hibernate 5. + +### Relevant articles: + +- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) +- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) +- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) +- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) +- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) \ No newline at end of file diff --git a/persistence-modules/hibernate5-mapping/pom.xml b/persistence-modules/hibernate5-mapping/pom.xml new file mode 100644 index 0000000000..59e0547671 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + hibernate5-mapping + 0.0.1-SNAPSHOT + hibernate5-mapping + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + + + diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..28e1af49ed --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,96 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Employee.class); + metadataSources.addAnnotatedClass(Phone.class); + metadataSources.addAnnotatedClass(EntityDescription.class); + metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(Animal.class); + metadataSources.addAnnotatedClass(Bag.class); + metadataSources.addAnnotatedClass(Book.class); + metadataSources.addAnnotatedClass(Car.class); + metadataSources.addAnnotatedClass(MyEmployee.class); + metadataSources.addAnnotatedClass(MyProduct.class); + metadataSources.addAnnotatedClass(Pen.class); + metadataSources.addAnnotatedClass(Pet.class); + metadataSources.addAnnotatedClass(Vehicle.class); + + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-mapping/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5-mapping/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-mapping/src/main/resources/logback.xml b/persistence-modules/hibernate5-mapping/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/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/hibernate5/README.md b/persistence-modules/hibernate5/README.md index d1bfe897f6..b7a254d836 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -1,41 +1,15 @@ ## Hibernate 5 -This module contains articles about Hibernate 5. +This module contains articles about Hibernate 5. Let's not add more articles here, we should not be creating a -2 out of it. Please add to other existing hibernate-* modules, or create a new one. ### Relevant articles: -- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) - [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers) -- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) -- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) -- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy) -- [Introduction to Hibernate Spatial](http://www.baeldung.com/hibernate-spatial) - [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor) -- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters) -- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) -- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) -- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) -- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) -- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking) - [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle) -- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) -- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) - [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy) - [Proxy in Hibernate load() Method](https://www.baeldung.com/hibernate-proxy-load-method) -- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) -- [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) -- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) - [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api) -- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel) - [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager) -- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) -- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) -- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) -- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) -- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) -- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) -- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) -- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) -- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) -- [[Next -->]](/hibernate5-2) \ No newline at end of file +- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) \ No newline at end of file diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index ffeff5ee4a..7f04abc09f 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -77,7 +77,7 @@ - 5.3.7.Final + 5.4.12.Final 6.0.6 2.2.3 3.8.0 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 137fc4f0bd..11a59c9cf0 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -12,25 +12,13 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; -import com.baeldung.hibernate.customtypes.LocalDateStringType; -import com.baeldung.hibernate.customtypes.OfficeEmployee; import com.baeldung.hibernate.entities.DeptEmployee; -import com.baeldung.hibernate.joincolumn.Email; -import com.baeldung.hibernate.joincolumn.Office; -import com.baeldung.hibernate.joincolumn.OfficeAddress; -import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; -import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; -import com.baeldung.hibernate.pessimisticlocking.Individual; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; import com.baeldung.hibernate.pojo.Course; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; import com.baeldung.hibernate.pojo.OrderEntry; import com.baeldung.hibernate.pojo.OrderEntryIdClass; import com.baeldung.hibernate.pojo.OrderEntryPK; -import com.baeldung.hibernate.pojo.Person; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.PointEntity; import com.baeldung.hibernate.pojo.PolygonEntity; @@ -88,7 +76,6 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(MyEmployee.class); metadataSources.addAnnotatedClass(MyProduct.class); metadataSources.addAnnotatedClass(Pen.class); - metadataSources.addAnnotatedClass(Person.class); metadataSources.addAnnotatedClass(Animal.class); metadataSources.addAnnotatedClass(Pet.class); metadataSources.addAnnotatedClass(Vehicle.class); @@ -96,26 +83,11 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Bag.class); metadataSources.addAnnotatedClass(PointEntity.class); metadataSources.addAnnotatedClass(PolygonEntity.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class); - metadataSources.addAnnotatedClass(Individual.class); - metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class); - metadataSources.addAnnotatedClass(PessimisticLockingStudent.class); - metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); - metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); - metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); - metadataSources.addAnnotatedClass(OfficeEmployee.class); metadataSources.addAnnotatedClass(Post.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); - metadataSources.addAnnotatedClass(Email.class); - metadataSources.addAnnotatedClass(Office.class); - metadataSources.addAnnotatedClass(OfficeAddress.class); Metadata metadata = metadataSources.getMetadataBuilder() - .applyBasicType(LocalDateStringType.INSTANCE) .build(); return metadata.getSessionFactoryBuilder() diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java index 736abde866..7a88a8bedc 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -1,12 +1,13 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Point; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import org.locationtech.jts.geom.Point; + @Entity public class PointEntity { diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java index 69208c8cd4..3144a88a16 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Polygon; - import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import org.locationtech.jts.geom.Polygon; + @Entity public class PolygonEntity { diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index 41d0ad63f8..a8539e644f 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -9,3 +9,4 @@ This module contains articles about MongoDB in Java. - [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson) - [Geospatial Support in MongoDB](https://www.baeldung.com/mongodb-geospatial-support) - [Introduction to Morphia – Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia) +- [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 15b62d5d77..f1b7c407bd 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -21,9 +21,12 @@ flyway hbase hibernate5 - hibernate5-2 hibernate-mapping hibernate-ogm + hibernate-annotations + hibernate-jpa + hibernate-queries + hibernate-enterprise influxdb java-cassandra java-cockroachdb diff --git a/persistence-modules/spring-boot-persistence-h2/pom.xml b/persistence-modules/spring-boot-persistence-h2/pom.xml index 5b5e255211..777bc6cb2d 100644 --- a/persistence-modules/spring-boot-persistence-h2/pom.xml +++ b/persistence-modules/spring-boot-persistence-h2/pom.xml @@ -29,12 +29,30 @@ com.h2database h2 + + org.projectlombok + lombok + ${lombok.version} + compile + + + org.hibernate + hibernate-core + ${hibernate.version} + + + com.vladmihalcea + db-util + ${db-util.version} + com.baeldung.h2db.demo.server.SpringBootApp 2.0.4.RELEASE + 5.3.11.Final + 1.0.4 diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/LazyLoadNoTransSpringBootApplication.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/LazyLoadNoTransSpringBootApplication.java new file mode 100644 index 0000000000..a52d9fc2f9 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/LazyLoadNoTransSpringBootApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.h2db.lazy_load_no_trans; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@SpringBootApplication +@EnableTransactionManagement +public class LazyLoadNoTransSpringBootApplication { + public static void main(String[] args) { + SpringApplication.run(LazyLoadNoTransSpringBootApplication.class, args); + } +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java new file mode 100644 index 0000000000..c087427b65 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java @@ -0,0 +1,67 @@ +package com.baeldung.h2db.lazy_load_no_trans.config; + +import net.ttddyy.dsproxy.listener.DataSourceQueryCountListener; +import net.ttddyy.dsproxy.listener.logging.CommonsQueryLoggingListener; +import net.ttddyy.dsproxy.listener.logging.DefaultQueryLogEntryCreator; +import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel; +import net.ttddyy.dsproxy.listener.logging.SLF4JQueryLoggingListener; +import net.ttddyy.dsproxy.support.ProxyDataSource; +import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.stereotype.Component; +import org.springframework.util.ReflectionUtils; + +import javax.sql.DataSource; +import java.lang.reflect.Method; + +@Component +public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor { + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) { + if (bean instanceof DataSource && !(bean instanceof ProxyDataSource)) { + // Instead of directly returning a less specific datasource bean + // (e.g.: HikariDataSource -> DataSource), return a proxy object. + // See following links for why: + // https://stackoverflow.com/questions/44237787/how-to-use-user-defined-database-proxy-in-datajpatest + // https://gitter.im/spring-projects/spring-boot?at=5983602d2723db8d5e70a904 + // http://blog.arnoldgalovics.com/2017/06/26/configuring-a-datasource-proxy-in-spring-boot/ + final ProxyFactory factory = new ProxyFactory(bean); + factory.setProxyTargetClass(true); + factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean)); + return factory.getProxy(); + } + return bean; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) { + return bean; + } + + private static class ProxyDataSourceInterceptor implements MethodInterceptor { + private final DataSource dataSource; + + public ProxyDataSourceInterceptor(final DataSource dataSource) { + this.dataSource = ProxyDataSourceBuilder.create(dataSource) + .name("MyDS") + .multiline() + .logQueryBySlf4j(SLF4JLogLevel.INFO) + .listener(new DataSourceQueryCountListener()) + .build(); + } + + @Override + public Object invoke(final MethodInvocation invocation) throws Throwable { + final Method proxyMethod = ReflectionUtils.findMethod(this.dataSource.getClass(), + invocation.getMethod().getName()); + if (proxyMethod != null) { + return proxyMethod.invoke(this.dataSource, invocation.getArguments()); + } + return invocation.proceed(); + } + } +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java new file mode 100644 index 0000000000..9d69e7eb58 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java @@ -0,0 +1,26 @@ +package com.baeldung.h2db.lazy_load_no_trans.entity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.annotations.Immutable; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Immutable +public class Document { + + @Id + private Long id; + + private String title; + + private Long userId; +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java new file mode 100644 index 0000000000..ae9cb9e4e8 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java @@ -0,0 +1,37 @@ +package com.baeldung.h2db.lazy_load_no_trans.entity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.annotations.Fetch; +import org.hibernate.annotations.FetchMode; +import org.hibernate.annotations.Immutable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Immutable +public class User { + + @Id + @GeneratedValue + private Long id; + + private String name; + + private String comment; + + @OneToMany(mappedBy = "userId") + @Fetch(FetchMode.SUBSELECT) + private List docs = new ArrayList<>(); +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/repository/UserRepository.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/repository/UserRepository.java new file mode 100644 index 0000000000..bafe484163 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/repository/UserRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.h2db.lazy_load_no_trans.repository; + +import com.baeldung.h2db.lazy_load_no_trans.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends JpaRepository { +} \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/service/ServiceLayer.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/service/ServiceLayer.java new file mode 100644 index 0000000000..ff3783fd9d --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/service/ServiceLayer.java @@ -0,0 +1,34 @@ +package com.baeldung.h2db.lazy_load_no_trans.service; + +import com.baeldung.h2db.lazy_load_no_trans.entity.User; +import com.baeldung.h2db.lazy_load_no_trans.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collection; + +@Service +public class ServiceLayer { + + @Autowired + private UserRepository userRepository; + + @Transactional(readOnly = true) + public long countAllDocsTransactional() { + return countAllDocs(); + } + + public long countAllDocsNonTransactional() { + return countAllDocs(); + } + + private long countAllDocs() { + return userRepository.findAll() + .stream() + .map(User::getDocs) + .mapToLong(Collection::size) + .sum(); + } + +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties new file mode 100644 index 0000000000..b5fb841685 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties @@ -0,0 +1,13 @@ +spring.datasource.url=jdbc:h2:mem:mydb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create-drop +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console + +logging.level.org.hibernate.SQL=INFO +logging.level.org.hibernate.type=TRACE +spring.jpa.properties.hibernate.validator.apply_to_ddl=false +spring.jpa.properties.hibernate.enable_lazy_load_no_trans=false +spring.jpa.open-in-view=false \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties new file mode 100644 index 0000000000..04579e1dae --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties @@ -0,0 +1,13 @@ +spring.datasource.url=jdbc:h2:mem:mydb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create-drop +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console + +logging.level.org.hibernate.SQL=INFO +logging.level.org.hibernate.type=TRACE +spring.jpa.properties.hibernate.validator.apply_to_ddl=false +spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true +spring.jpa.open-in-view=false \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql index 2d7b446005..b8835e70cb 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql @@ -10,4 +10,17 @@ CREATE TABLE billionaires ( INSERT INTO billionaires (first_name, last_name, career) VALUES ('Aliko', 'Dangote', 'Billionaire Industrialist'), ('Bill', 'Gates', 'Billionaire Tech Entrepreneur'), -('Folrunsho', 'Alakija', 'Billionaire Oil Magnate'); \ No newline at end of file +('Folrunsho', 'Alakija', 'Billionaire Oil Magnate'); + +insert into USER values (101, 'user1', 'comment1'); +insert into USER values (102, 'user2', 'comment2'); +insert into USER values (103, 'user3', 'comment3'); +insert into USER values (104, 'user4', 'comment4'); +insert into USER values (105, 'user5', 'comment5'); + +insert into DOCUMENT values (1, 'doc1', 101); +insert into DOCUMENT values (2, 'doc2', 101); +insert into DOCUMENT values (3, 'doc3', 101); +insert into DOCUMENT values (4, 'doc4', 101); +insert into DOCUMENT values (5, 'doc5', 102); +insert into DOCUMENT values (6, 'doc6', 102); \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOffIntegrationTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOffIntegrationTest.java new file mode 100644 index 0000000000..cb5063d8a4 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOffIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.lazy_load_no_trans; + +import com.baeldung.h2db.lazy_load_no_trans.LazyLoadNoTransSpringBootApplication; +import com.baeldung.h2db.lazy_load_no_trans.service.ServiceLayer; +import com.vladmihalcea.sql.SQLStatementCountValidator; +import org.hibernate.LazyInitializationException; +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.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = LazyLoadNoTransSpringBootApplication.class) +@ActiveProfiles("lazy-load-no-trans-off") +public class LazyLoadNoTransPropertyOffIntegrationTest { + + @Autowired + private ServiceLayer serviceLayer; + + private static final long EXPECTED_DOCS_COLLECTION_SIZE = 6; + + @Test(expected = LazyInitializationException.class) + public void whenCallNonTransactionalMethodWithPropertyOff_thenThrowException() { + serviceLayer.countAllDocsNonTransactional(); + } + + @Test + public void whenCallTransactionalMethodWithPropertyOff_thenTestPass() { + SQLStatementCountValidator.reset(); + + long docsCount = serviceLayer.countAllDocsTransactional(); + + assertEquals(EXPECTED_DOCS_COLLECTION_SIZE, docsCount); + + SQLStatementCountValidator.assertSelectCount(2); + } +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOnIntegrationTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOnIntegrationTest.java new file mode 100644 index 0000000000..5968fde7b7 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOnIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.lazy_load_no_trans; + +import com.baeldung.h2db.lazy_load_no_trans.LazyLoadNoTransSpringBootApplication; +import com.baeldung.h2db.lazy_load_no_trans.service.ServiceLayer; +import com.vladmihalcea.sql.SQLStatementCountValidator; +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.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = LazyLoadNoTransSpringBootApplication.class) +@ActiveProfiles("lazy-load-no-trans-on") +public class LazyLoadNoTransPropertyOnIntegrationTest { + + @Autowired + private ServiceLayer serviceLayer; + + private static final long EXPECTED_DOCS_COLLECTION_SIZE = 6; + private static final long EXPECTED_USERS_COUNT = 5; + + @Test + public void whenCallNonTransactionalMethodWithPropertyOn_thenGetNplusOne() { + SQLStatementCountValidator.reset(); + + long docsCount = serviceLayer.countAllDocsNonTransactional(); + + assertEquals(EXPECTED_DOCS_COLLECTION_SIZE, docsCount); + + SQLStatementCountValidator.assertSelectCount(EXPECTED_USERS_COUNT + 1); + } + + @Test + public void whenCallTransactionalMethodWithPropertyOn_thenTestPass() { + SQLStatementCountValidator.reset(); + + long docsCount = serviceLayer.countAllDocsTransactional(); + + assertEquals(EXPECTED_DOCS_COLLECTION_SIZE, docsCount); + + SQLStatementCountValidator.assertSelectCount(2); + } +} diff --git a/persistence-modules/spring-data-jpa-4/README.md b/persistence-modules/spring-data-jpa-4/README.md index 42e4619a59..3884435f75 100644 --- a/persistence-modules/spring-data-jpa-4/README.md +++ b/persistence-modules/spring-data-jpa-4/README.md @@ -5,6 +5,7 @@ - [Programmatic Transaction Management in Spring](https://www.baeldung.com/spring-programmatic-transaction-management) - [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events) - [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) +- [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index 9bbc571aee..4e87c24614 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -16,8 +16,7 @@ public class MovieDatabaseNeo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { - org.neo4j.ogm.config.Configuration config = new Builder().uri(URL).build(); - return config; + return new Builder().uri(URL).build(); } @Bean diff --git a/persistence-modules/spring-data-redis/README.md b/persistence-modules/spring-data-redis/README.md index e4a528ae91..175634376b 100644 --- a/persistence-modules/spring-data-redis/README.md +++ b/persistence-modules/spring-data-redis/README.md @@ -4,6 +4,7 @@ - [Introduction to Spring Data Redis](https://www.baeldung.com/spring-data-redis-tutorial) - [PubSub Messaging with Spring Data Redis](https://www.baeldung.com/spring-data-redis-pub-sub) - [An Introduction to Spring Data Redis Reactive](https://www.baeldung.com/spring-data-redis-reactive) +- [Delete Everything in Redis](https://www.baeldung.com/redis-delete-data) ### Build the Project with Tests Running ``` diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index c3c8fa7b9f..6d7526a13b 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -9,6 +9,7 @@ This module contains articles about Hibernate 5 with Spring. - [JPA Criteria Queries](https://www.baeldung.com/hibernate-criteria-queries) - [Introduction to Hibernate Search](https://www.baeldung.com/hibernate-search) - [@DynamicUpdate with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-dynamicupdate) -- [Hibernate Second-Level Cache](https://www.baeldung.com/hibernate-second-level-cache) -- [Deleting Objects with Hibernate](https://www.baeldung.com/delete-with-hibernate) -- [Spring, Hibernate and a JNDI Datasource](https://www.baeldung.com/spring-persistence-jpa-jndi-datasource) +- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) +- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) +- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) +- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) \ No newline at end of file diff --git a/play-framework/async-http/README.md b/play-framework/async-http/README.md new file mode 100644 index 0000000000..c42b86ad4e --- /dev/null +++ b/play-framework/async-http/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Asynchronous HTTP Programming with Play Framework](https://www.baeldung.com/java-play-asynchronous-http-programming) diff --git a/pom.xml b/pom.xml index a295439951..15331d8c95 100644 --- a/pom.xml +++ b/pom.xml @@ -69,6 +69,12 @@ ${hamcrest-all.version} test + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + test + org.mockito mockito-core @@ -394,7 +400,6 @@ core-java-modules core-kotlin-modules - core-scala couchbase custom-pmd @@ -907,7 +912,6 @@ core-java-modules core-kotlin-modules - core-scala couchbase custom-pmd @@ -1330,7 +1334,8 @@ 4.12 2.2 1.3 - 2.21.0 + 3.3.0 + 1.10.5 1.7.30 diff --git a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java index b7ed031ec7..9d04541f8d 100644 --- a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java +++ b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java @@ -52,14 +52,13 @@ public class ConsumerFooServiceIntegrationTest { .map(Arrays::stream) .orElse(Stream.empty()); }) - .map(IThrowableProxy::getMessage) + .map(IThrowableProxy::getClassName) .collect(Collectors.toList()); assertThat(allLoggedEntries).anyMatch(entry -> entry.contains("The following error happened on processFoo method!")) .anyMatch(entry -> entry.contains("| onSubscribe")) .anyMatch(entry -> entry.contains("| cancel()")); - assertThat(allSuppressedEntries).anyMatch(entry -> entry.contains("Assembly trace from producer")) - .anyMatch(entry -> entry.contains("Error has been observed by the following operator(s)")); + assertThat(allSuppressedEntries) + .anyMatch(entry -> entry.contains("reactor.core.publisher.FluxOnAssembly$OnAssemblyException")); } - } diff --git a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java index af9bdfbc9b..e61ea9e155 100644 --- a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java +++ b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java @@ -7,6 +7,11 @@ import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; import com.baeldung.debugging.consumer.service.FooService; +/** + * In order to run this live test, start the following classes: + * - com.baeldung.debugging.server.ServerDebuggingApplication + * - com.baeldung.debugging.consumer.ConsumerDebuggingApplication + */ public class ConsumerFooServiceLiveTest { FooService service = new FooService(); diff --git a/spring-5/README.md b/spring-5/README.md index 857b199562..d50f9c7544 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -16,3 +16,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Assert Statements](https://www.baeldung.com/spring-assert) - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) - [Difference between \ vs \](https://www.baeldung.com/spring-contextannotation-contextcomponentscan) +- [Finding the Spring Version](https://www.baeldung.com/spring-find-version) diff --git a/spring-amqp/README.md b/spring-amqp/README.md index 6b09aec10a..7d202f49f8 100644 --- a/spring-amqp/README.md +++ b/spring-amqp/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring with the AMQP messaging system - [Messaging With Spring AMQP](https://www.baeldung.com/spring-amqp) - [RabbitMQ Message Dispatching with Spring AMQP](https://www.baeldung.com/rabbitmq-spring-amqp) - [Error Handling with Spring AMQP](https://www.baeldung.com/spring-amqp-error-handling) +- [Exponential Backoff With Spring AMQP](https://www.baeldung.com/spring-amqp-exponential-backoff) diff --git a/spring-batch/README.md b/spring-batch/README.md index 99ac9826bc..d637de269c 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -9,3 +9,4 @@ This module contains articles about Spring Batch - [How to Trigger and Stop a Scheduled Spring Batch Job](https://www.baeldung.com/spring-batch-start-stop-job) - [Configuring Skip Logic in Spring Batch](https://www.baeldung.com/spring-batch-skip-logic) - [Testing a Spring Batch Job](https://www.baeldung.com/spring-batch-testing-job) +- [Configuring Retry Logic in Spring Batch](https://www.baeldung.com/spring-batch-retry-logic) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index c8d153d4bb..228e7ce481 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -20,6 +20,7 @@ spring-boot-annotations spring-boot-artifacts spring-boot-autoconfiguration + spring-boot-basic-customization spring-boot-bootstrap spring-boot-client spring-boot-config-jpa-error diff --git a/spring-boot-modules/spring-boot-basic-customization/README.md b/spring-boot-modules/spring-boot-basic-customization/README.md new file mode 100644 index 0000000000..a3d9f1b1fc --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/README.md @@ -0,0 +1,13 @@ +## Spring Boot Basic Customization + +This module contains articles about Spring Boot customization + +### Relevant Articles: + + - [How to Change the Default Port in Spring Boot](https://www.baeldung.com/spring-boot-change-port) + - [Using Custom Banners in Spring Boot](https://www.baeldung.com/spring-boot-custom-banners) + - [Create a Custom FailureAnalyzer with Spring Boot](https://www.baeldung.com/spring-boot-failure-analyzer) + - [Spring Boot: Customize Whitelabel Error Page](https://www.baeldung.com/spring-boot-custom-error-page) + - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) + - [How to Define a Spring Boot Filter?](https://www.baeldung.com/spring-boot-add-filter) + - [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) diff --git a/spring-boot-modules/spring-boot-basic-customization/pom.xml b/spring-boot-modules/spring-boot-basic-customization/pom.xml new file mode 100644 index 0000000000..7c2c89def4 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + spring-boot-basic-customization + spring-boot-basic-customization + jar + Module For Spring Boot Basic Customization + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + com.baeldung.changeport.CustomApplication + + diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java similarity index 93% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java index aa794182de..42da61fe14 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java @@ -1,10 +1,8 @@ package com.baeldung.bootcustomfilters; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - import com.baeldung.bootcustomfilters.filters.RequestResponseLoggingFilter; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Configuration; @Configuration public class FilterConfig { diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java similarity index 99% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java index 97165f2cf3..50d5f4ea71 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java @@ -1,16 +1,15 @@ package com.baeldung.bootcustomfilters.controller; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - +import com.baeldung.bootcustomfilters.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.baeldung.bootcustomfilters.model.User; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; /** * Rest controller for User diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java similarity index 86% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java index e42ea7d2dd..3924354932 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java @@ -1,21 +1,15 @@ package com.baeldung.bootcustomfilters.filters; -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + /** * A servlet filter to log request and response * The logging implementation is pretty native and for demonstration only diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java similarity index 85% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java index d92b723e73..604829c3d3 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java @@ -1,20 +1,14 @@ package com.baeldung.bootcustomfilters.filters; -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + /** * A filter to create transaction before and commit it once request completes * The current implemenatation is just for demo diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/model/User.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/model/User.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/model/User.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/model/User.java diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/changeport/CustomApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/CustomApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/changeport/CustomApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/CustomApplication.java diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java similarity index 73% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java index 5dd55ef077..9f6c209deb 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java @@ -2,10 +2,8 @@ package com.baeldung.errorhandling; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; -@SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.errorhandling") +@SpringBootApplication(scanBasePackages = "com.baeldung.errorhandling") public class ErrorHandlingApplication { public static void main(String [] args) { diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java index 7bd5c36786..d08fa05c6e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java @@ -1,10 +1,10 @@ package com.baeldung.failureanalyzer; -import javax.annotation.security.RolesAllowed; - import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import javax.annotation.security.RolesAllowed; + @SpringBootApplication public class FailureAnalyzerApplication { @RolesAllowed("*") diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyDAO.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyDAO.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyDAO.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyDAO.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyService.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyService.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyService.java index 72334ca8fa..f31b67615f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyService.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyService.java @@ -1,9 +1,9 @@ package com.baeldung.failureanalyzer; -import javax.annotation.Resource; - import org.springframework.stereotype.Service; +import javax.annotation.Resource; + @Service public class MyService { diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/FaviconApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/FaviconApplication.java new file mode 100644 index 0000000000..f94549b988 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/FaviconApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.favicon; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FaviconApplication { + + public static void main(String[] args) { + SpringApplication.run(FaviconApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/config/FaviconConfiguration.java similarity index 96% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/config/FaviconConfiguration.java index 9a1f47b5cb..d1809199d6 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/config/FaviconConfiguration.java @@ -1,8 +1,4 @@ -package com.baeldung.springbootmvc.config; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +package com.baeldung.favicon.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -14,8 +10,13 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + @Configuration public class FaviconConfiguration { + @Bean public SimpleUrlHandlerMapping myFaviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); @@ -33,7 +34,7 @@ public class FaviconConfiguration { return requestHandler; } - // @Controller + // @Controller static class FaviconController { @RequestMapping(value = "favicon.ico", method = RequestMethod.GET) diff --git a/spring-boot-modules/spring-boot/src/main/resources/META-INF/spring.factories b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/META-INF/spring.factories rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/META-INF/spring.factories diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application-errorhandling.properties b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application-errorhandling.properties new file mode 100644 index 0000000000..0a6d68763c --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application-errorhandling.properties @@ -0,0 +1,10 @@ +#server +server.port=9000 +spring.mvc.servlet.path=/ +server.servlet.context-path=/ +server.error.whitelabel.enabled=false + +#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration + +#for Spring Boot 2.0+ +#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties new file mode 100644 index 0000000000..4d4a6ec7bd --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties @@ -0,0 +1,7 @@ +#spring.banner.charset=UTF-8 +#spring.banner.location=classpath:banner.txt +#spring.banner.image.location=classpath:banner.gif +#spring.banner.image.width= //TODO +#spring.banner.image.height= //TODO +#spring.banner.image.margin= //TODO +#spring.banner.image.invert= //TODO diff --git a/spring-boot-modules/spring-boot/src/main/resources/banner.txt b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/banner.txt similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/banner.txt rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/banner.txt diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/com/baeldung/images/favicon.ico similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/com/baeldung/images/favicon.ico diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/favicon.ico b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/favicon.ico similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/resources/favicon.ico rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/favicon.ico diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/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/spring-boot-modules/spring-boot-mvc/src/main/resources/static/favicon.ico b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/static/favicon.ico similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/resources/static/favicon.ico rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/static/favicon.ico diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-404.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-404.html new file mode 100644 index 0000000000..555cf52de4 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-404.html @@ -0,0 +1,7 @@ + + + +

Sorry, we couldn't find the page you were looking for.

+

Go Home

+ + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-500.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-500.html new file mode 100644 index 0000000000..fc64c7e180 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-500.html @@ -0,0 +1,9 @@ + + + +

Sorry, something went wrong!

+ +

We're fixing it.

+

Go Home

+ + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error.html new file mode 100644 index 0000000000..4e953059e2 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error.html @@ -0,0 +1,8 @@ + + + +

Something went wrong!

+

Our Engineers are on it.

+

Go Home

+ + diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error/404.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error/404.html new file mode 100644 index 0000000000..df83ce219b --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error/404.html @@ -0,0 +1,8 @@ + + + RESOURCE NOT FOUND + + +

404 RESOURCE NOT FOUND

+ + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/index.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/index.html new file mode 100644 index 0000000000..95c68c8600 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/index.html @@ -0,0 +1,6 @@ + + +

Welcome Home

+

Success! It is working as we expected.

+ + diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java rename to spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java index b3555f55da..2d9fb56217 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java @@ -1,18 +1,16 @@ package com.baeldung.failureanalyzer; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collection; -import java.util.stream.Collectors; - +import ch.qos.logback.classic.spi.ILoggingEvent; +import com.baeldung.failureanalyzer.utils.ListAppender; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.SpringApplication; -import com.baeldung.failureanalyzer.utils.ListAppender; +import java.util.Collection; +import java.util.stream.Collectors; -import ch.qos.logback.classic.spi.ILoggingEvent; +import static org.assertj.core.api.Assertions.assertThat; public class FailureAnalyzerAppIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java rename to spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java index a298f49ff5..091cd687f1 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java @@ -1,11 +1,11 @@ package com.baeldung.failureanalyzer.utils; -import java.util.ArrayList; -import java.util.List; - import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.util.ArrayList; +import java.util.List; + public class ListAppender extends AppenderBase { static private List events = new ArrayList<>(); diff --git a/spring-boot-modules/spring-boot/src/test/resources/logback-test.xml b/spring-boot-modules/spring-boot-basic-customization/src/test/resources/logback-test.xml similarity index 51% rename from spring-boot-modules/spring-boot/src/test/resources/logback-test.xml rename to spring-boot-modules/spring-boot-basic-customization/src/test/resources/logback-test.xml index 9e0f4e221f..6919a457cb 100644 --- a/spring-boot-modules/spring-boot/src/test/resources/logback-test.xml +++ b/spring-boot-modules/spring-boot-basic-customization/src/test/resources/logback-test.xml @@ -1,15 +1,15 @@ + resource="org/springframework/boot/logging/logback/base.xml" /> + class="com.baeldung.failureanalyzer.utils.ListAppender"> + name="org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter"> - \ No newline at end of file + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-bootstrap/README.md b/spring-boot-modules/spring-boot-bootstrap/README.md index 5fb8fd4a84..146cd04551 100644 --- a/spring-boot-modules/spring-boot-bootstrap/README.md +++ b/spring-boot-modules/spring-boot-bootstrap/README.md @@ -10,3 +10,4 @@ This module contains articles about bootstrapping Spring Boot applications. - [Deploy a Spring Boot Application to OpenShift](https://www.baeldung.com/spring-boot-deploy-openshift) - [Deploy a Spring Boot Application to AWS Beanstalk](https://www.baeldung.com/spring-boot-deploy-aws-beanstalk) - [Guide to @SpringBootConfiguration in Spring Boot](https://www.baeldung.com/springbootconfiguration-annotation) +- [Implement Health Checks in OpenShift](https://www.baeldung.com/openshift-health-checks) diff --git a/spring-boot-modules/spring-boot-libraries/README.md b/spring-boot-modules/spring-boot-libraries/README.md index f0bc3c9e89..c02fb69e5d 100644 --- a/spring-boot-modules/spring-boot-libraries/README.md +++ b/spring-boot-modules/spring-boot-libraries/README.md @@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to ShedLock with Spring](https://www.baeldung.com/shedlock-spring) - [A Guide to the Problem Spring Web Library](https://www.baeldung.com/problem-spring-web) +- [Generating Barcodes and QR Codes in Java](https://www.baeldung.com/java-generating-barcodes-qr-codes) diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index ba1164dd59..e9d955edc0 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -53,8 +53,41 @@ ${shedlock.version}
+ + + net.sourceforge.barbecue + barbecue + ${barbecue.version} + + + net.sf.barcode4j + barcode4j + ${barcode4j.version} + + + com.github.kenglxn.qrgen + javase + ${qrgen.version} + + + com.google.zxing + core + ${zxing.version} + + + com.google.zxing + javase + ${zxing.version} + + + + jitpack.io + https://jitpack.io + + + spring-boot-libraries @@ -153,6 +186,10 @@ 2.3.2 0.23.0 2.1.0 + 1.5-beta1 + 2.1 + 2.6.0 + 3.3.0
diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/BarcodesController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/BarcodesController.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/BarcodesController.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/BarcodesController.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/SpringBootApp.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/SpringBootApp.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/SpringBootApp.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/SpringBootApp.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java diff --git a/spring-boot-modules/spring-boot-mvc-2/README.md b/spring-boot-modules/spring-boot-mvc-2/README.md index d7341cca35..c42730f9cc 100644 --- a/spring-boot-modules/spring-boot-mvc-2/README.md +++ b/spring-boot-modules/spring-boot-mvc-2/README.md @@ -6,6 +6,7 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Functional Controllers in Spring MVC](https://www.baeldung.com/spring-mvc-functional-controllers) - [Specify an Array of Strings as Body Parameters in Swagger](https://www.baeldung.com/swagger-body-array-of-strings) +- [Swagger @ApiParam vs @ApiModelProperty](https://www.baeldung.com/swagger-apiparam-vs-apimodelproperty) - [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) - [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index 2e67c42ede..41b98063a6 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -4,7 +4,6 @@ This module contains articles about Spring Web MVC in Spring Boot projects. ### Relevant Articles: -- [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) - [Custom Validation MessageSource in Spring Boot](https://www.baeldung.com/spring-custom-validation-message-source) - [Display RSS Feed with Spring MVC](https://www.baeldung.com/spring-mvc-rss-feed) - [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) diff --git a/spring-boot-modules/spring-boot-properties/README.md b/spring-boot-modules/spring-boot-properties/README.md index daf7c55ab3..f861a01d10 100644 --- a/spring-boot-modules/spring-boot-properties/README.md +++ b/spring-boot-modules/spring-boot-properties/README.md @@ -12,3 +12,5 @@ This module contains articles about Properties in Spring Boot. - [Spring YAML Configuration](https://www.baeldung.com/spring-yaml) - [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults) - [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class) +- [Add Build Properties to a Spring Boot Application](https://www.baeldung.com/spring-boot-build-properties) +- [IntelliJ – Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties) diff --git a/spring-boot-modules/spring-boot-runtime/README.md b/spring-boot-modules/spring-boot-runtime/README.md index a544faf830..62727ecc76 100644 --- a/spring-boot-modules/spring-boot-runtime/README.md +++ b/spring-boot-modules/spring-boot-runtime/README.md @@ -8,7 +8,6 @@ This module contains articles about administering a Spring Boot runtime - [Logging HTTP Requests with Spring Boot Actuator HTTP Tracing](https://www.baeldung.com/spring-boot-actuator-http) - [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) - [Spring Boot Embedded Tomcat Logs](https://www.baeldung.com/spring-boot-embedded-tomcat-logs) - - [How to Change the Default Port in Spring Boot](https://www.baeldung.com/spring-boot-change-port) - [Project Configuration with Spring](https://www.baeldung.com/project-configuration-with-spring) - [CORS with Spring](https://www.baeldung.com/spring-cors) - [Spring – Log Incoming Requests](https://www.baeldung.com/spring-http-logging) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index fd8a9e71ae..c99a9c2b24 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 spring-boot-springdoc 0.0.1-SNAPSHOT @@ -16,11 +17,6 @@ ../../parent-boot-2 - - 1.8 - 1.2.32 - - org.springframework.boot @@ -63,6 +59,11 @@ + + 1.8 + 1.2.32 + + integration diff --git a/spring-boot-modules/spring-boot-testing/README.md b/spring-boot-modules/spring-boot-testing/README.md index 0b2533e6bc..882e2be766 100644 --- a/spring-boot-modules/spring-boot-testing/README.md +++ b/spring-boot-modules/spring-boot-testing/README.md @@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test) - [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level) - [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) +- [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties) diff --git a/spring-boot-modules/spring-boot/README.MD b/spring-boot-modules/spring-boot/README.MD index 217d9e90b2..b15ab7dbe5 100644 --- a/spring-boot-modules/spring-boot/README.MD +++ b/spring-boot-modules/spring-boot/README.MD @@ -11,9 +11,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) -- [Using Custom Banners in Spring Boot](https://www.baeldung.com/spring-boot-custom-banners) - [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) -- [Create a Custom FailureAnalyzer with Spring Boot](https://www.baeldung.com/spring-boot-failure-analyzer) - [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) - [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) - [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) @@ -22,11 +20,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) - [An Introduction to Kong](https://www.baeldung.com/kong) -- [Spring Boot: Customize Whitelabel Error Page](https://www.baeldung.com/spring-boot-custom-error-page) - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) - [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) -- [How to Define a Spring Boot Filter?](https://www.baeldung.com/spring-boot-add-filter) -- [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) - [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) - [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) - [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) diff --git a/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties b/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties index 6ffcfbaf52..270e86d443 100644 --- a/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties +++ b/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties @@ -1,10 +1,4 @@ #server server.port=9000 server.servlet-path=/ -server.context-path=/ -#server.error.whitelabel.enabled=false - -#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration - -#for Spring Boot 2.0+ -#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration \ No newline at end of file +server.context-path=/ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/application.properties b/spring-boot-modules/spring-boot/src/main/resources/application.properties index 7de79da574..44649fc1c0 100644 --- a/spring-boot-modules/spring-boot/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot/src/main/resources/application.properties @@ -33,12 +33,4 @@ logging.level.org.springframework=INFO servlet.name=dispatcherExample servlet.mapping=/dispatcherExampleURL -#spring.banner.charset=UTF-8 -#spring.banner.location=classpath:banner.txt -#spring.banner.image.location=classpath:banner.gif -#spring.banner.image.width= //TODO -#spring.banner.image.height= //TODO -#spring.banner.image.margin= //TODO -#spring.banner.image.invert= //TODO - contactInfoType=email \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/error-404.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error-404.html deleted file mode 100644 index cf68032596..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/error-404.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - -
-
-

Sorry, we couldn't find the page you were looking for.

-

Go Home

-
- - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/error-500.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error-500.html deleted file mode 100644 index 5ddf458229..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/error-500.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - -
-
-

Sorry, something went wrong!

- -

We're fixing it.

-

Go Home

-
- - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/README.md b/spring-cloud/spring-cloud-gateway/README.md index d3323947e8..9c8e0d443a 100644 --- a/spring-cloud/spring-cloud-gateway/README.md +++ b/spring-cloud/spring-cloud-gateway/README.md @@ -5,3 +5,4 @@ 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) diff --git a/spring-cloud/spring-cloud-zuul/README.md b/spring-cloud/spring-cloud-zuul/README.md index b8e1773930..acd56a213c 100644 --- a/spring-cloud/spring-cloud-zuul/README.md +++ b/spring-cloud/spring-cloud-zuul/README.md @@ -5,3 +5,4 @@ This module contains articles about Spring with Netflix Zuul ### Relevant Articles: - [Rate Limiting in Spring Cloud Netflix Zuul](https://www.baeldung.com/spring-cloud-zuul-rate-limit) - [Spring REST with a Zuul Proxy](https://www.baeldung.com/spring-rest-with-zuul-proxy) +- [Modifying the Response Body in a Zuul Filter](https://www.baeldung.com/zuul-filter-modifying-response-body) diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml index c13aeb890e..8643309645 100644 --- a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml @@ -1,7 +1,8 @@ - + spring-cloud-zuul com.baeldung.spring.cloud @@ -10,10 +11,6 @@ 4.0.0 spring-zuul-post-filter - - Hoxton.SR1 - - org.springframework.cloud @@ -21,5 +18,8 @@ + + Hoxton.SR1 + \ No newline at end of file diff --git a/spring-core-3/README.md b/spring-core-3/README.md index ae2d33c196..b2c4f694a8 100644 --- a/spring-core-3/README.md +++ b/spring-core-3/README.md @@ -8,4 +8,6 @@ This module contains articles about core Spring functionality - [Guide to the Spring BeanFactory](https://www.baeldung.com/spring-beanfactory) - [How to use the Spring FactoryBean?](https://www.baeldung.com/spring-factorybean) - [Spring – Injecting Collections](https://www.baeldung.com/spring-injecting-collections) +- [Design Patterns in the Spring Framework](https://www.baeldung.com/spring-framework-design-patterns) +- [Injecting a Value in a Static Field in Spring](https://www.baeldung.com/spring-inject-static-field) - More articles: [[<-- prev]](/spring-core-2) diff --git a/spring-ejb/ejb-beans/README.md b/spring-ejb/ejb-beans/README.md new file mode 100644 index 0000000000..f1af5a3a87 --- /dev/null +++ b/spring-ejb/ejb-beans/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring Bean vs. EJB – A Feature Comparison](https://www.baeldung.com/spring-bean-vs-ejb) diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml index eecf8c1d23..c9edfc21f8 100644 --- a/spring-ejb/ejb-beans/pom.xml +++ b/spring-ejb/ejb-beans/pom.xml @@ -121,6 +121,8 @@ 5.2.3.RELEASE 5.10.2 5.13.1 + 2.21.0 + 1.8.5 diff --git a/spring-mvc-java-2/README.md b/spring-mvc-java-2/README.md new file mode 100644 index 0000000000..b5d5df3cd4 --- /dev/null +++ b/spring-mvc-java-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Cache Headers in Spring MVC](https://www.baeldung.com/spring-mvc-cache-headers) diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 0adf127aaa..685e7686b1 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -17,6 +17,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) - [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable) - [Debugging the Spring MVC 404 “No mapping found for HTTP request” Error](https://www.baeldung.com/spring-mvc-404-error) +- [Getting Started with CRaSH](https://www.baeldung.com/jvm-crash-shell) ## Spring MVC with XML Configuration Example Project diff --git a/spring-reactive-kotlin/pom.xml b/spring-reactive-kotlin/pom.xml index 3a693837df..cbb143f6ec 100644 --- a/spring-reactive-kotlin/pom.xml +++ b/spring-reactive-kotlin/pom.xml @@ -5,6 +5,7 @@ spring-reactive-kotlin spring-reactive-kotlin Demo project for Spring Boot + jar @@ -23,6 +24,18 @@ org.springframework.boot spring-boot-starter-webflux
+ + org.springframework.boot.experimental + spring-boot-starter-data-r2dbc + + + org.springframework.boot + spring-boot-starter-actuator + + + io.r2dbc + r2dbc-h2 + com.fasterxml.jackson.module jackson-module-kotlin @@ -38,21 +51,95 @@ reactor-test test + + + org.springframework.boot.experimental + spring-boot-test-autoconfigure-r2dbc + test + + + io.projectreactor + reactor-test + test + +
+ + + + org.springframework.boot.experimental + spring-boot-bom-r2dbc + 0.1.0.M3 + pom + import + + + + + src/main/kotlin + src/test/kotlin kotlin-maven-plugin + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + org.jetbrains.kotlin ${kotlin.version} -Xjsr305=strict + 1.8 + + spring + jpa + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-maven-noarg + ${kotlin.version} + + + + 1.8 + 1.3.70 + 2.2.5.RELEASE + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + +
diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt new file mode 100644 index 0000000000..c70057b5de --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt @@ -0,0 +1,11 @@ +package com.baeldung.bootmicroservice + +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class HealthTrackerApplication + +fun main(args: Array) { + runApplication(*args) +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt new file mode 100644 index 0000000000..b14682cc5c --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt @@ -0,0 +1,28 @@ +package com.baeldung.bootmicroservice.config; + +import org.springframework.context.annotation.Configuration +import org.springframework.data.r2dbc.core.DatabaseClient + +@Configuration +class DBConfiguration(db: DatabaseClient) { + init { + val initDb = db.execute { + """ CREATE TABLE IF NOT EXISTS profile ( + id SERIAL PRIMARY KEY, + first_name VARCHAR(20) NOT NULL, + last_name VARCHAR(20) NOT NULL, + birth_date DATE NOT NULL + ); + CREATE TABLE IF NOT EXISTS health_record( + id SERIAL PRIMARY KEY, + profile_id LONG NOT NULL, + temperature DECIMAL NOT NULL, + blood_pressure DECIMAL NOT NULL, + heart_rate DECIMAL, + date DATE NOT NULL + ); + """ + } + initDb.then().subscribe() + } +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt new file mode 100644 index 0000000000..620f187b7b --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt @@ -0,0 +1,44 @@ +package com.baeldung.bootmicroservice.controller + +import com.baeldung.bootmicroservice.model.AverageHealthStatus +import com.baeldung.bootmicroservice.model.HealthRecord +import com.baeldung.bootmicroservice.repository.HealthRecordRepository +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.RestController +import reactor.core.publisher.Mono + +@RestController +class HealthRecordController(val repository: HealthRecordRepository) { + + @PostMapping("/health/{profileId}/record") + fun storeHealthRecord(@PathVariable("profileId") profileId: Long, @RequestBody record: HealthRecord): Mono = + repository.save(HealthRecord(null + , profileId + , record.temperature + , record.bloodPressure + , record.heartRate + , record.date)) + + @GetMapping("/health/{profileId}/avg") + fun fetchHealthRecordAverage(@PathVariable("profileId") profileId: Long): Mono = + repository.findByProfileId(profileId) + .reduce( + AverageHealthStatus(0, 0.0, 0.0, 0.0) + , { s, r -> + AverageHealthStatus(s.cnt + 1 + , s.temperature + r.temperature + , s.bloodPressure + r.bloodPressure + , s.heartRate + r.heartRate + ) + } + ).map { s -> + AverageHealthStatus(s.cnt + , if (s.cnt != 0) s.temperature / s.cnt else 0.0 + , if (s.cnt != 0) s.bloodPressure / s.cnt else 0.0 + , if (s.cnt != 0) s.heartRate / s.cnt else 0.0) + } + +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt new file mode 100644 index 0000000000..1dc3bcdc50 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt @@ -0,0 +1,15 @@ +package com.baeldung.bootmicroservice.controller + +import com.baeldung.bootmicroservice.model.Profile +import com.baeldung.bootmicroservice.repository.ProfileRepository +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RestController +import reactor.core.publisher.Mono + +@RestController +class ProfileController(val repository: ProfileRepository) { + + @PostMapping("/profile") + fun save(@RequestBody profile: Profile): Mono = repository.save(profile) +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt new file mode 100644 index 0000000000..3141146b9c --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt @@ -0,0 +1,3 @@ +package com.baeldung.bootmicroservice.model; + +class AverageHealthStatus(var cnt: Int, var temperature: Double, var bloodPressure: Double, var heartRate: Double) diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt new file mode 100644 index 0000000000..71c534027f --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt @@ -0,0 +1,8 @@ +package com.baeldung.bootmicroservice.model + +import org.springframework.data.annotation.Id +import org.springframework.data.relational.core.mapping.Table +import java.time.LocalDate + +@Table +data class HealthRecord(@Id var id: Long?, var profileId: Long?, var temperature: Double, var bloodPressure: Double, var heartRate: Double, var date: LocalDate) \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt new file mode 100644 index 0000000000..cbb7e675ea --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt @@ -0,0 +1,8 @@ +package com.baeldung.bootmicroservice.model + +import org.springframework.data.annotation.Id +import org.springframework.data.relational.core.mapping.Table +import java.time.LocalDateTime + +@Table +data class Profile(@Id var id:Long?, var firstName : String, var lastName : String, var birthDate: LocalDateTime) \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt new file mode 100644 index 0000000000..8cc91f06e4 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt @@ -0,0 +1,13 @@ +package com.baeldung.bootmicroservice.repository + +import com.baeldung.bootmicroservice.model.HealthRecord +import org.springframework.data.r2dbc.repository.Query +import org.springframework.data.repository.reactive.ReactiveCrudRepository +import org.springframework.stereotype.Repository +import reactor.core.publisher.Flux + +@Repository +interface HealthRecordRepository: ReactiveCrudRepository { + @Query("select p.* from health_record p where p.profile_id = :profileId ") + fun findByProfileId(profileId: Long): Flux +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt new file mode 100644 index 0000000000..eee8c5fcbe --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt @@ -0,0 +1,8 @@ +package com.baeldung.bootmicroservice.repository + +import com.baeldung.bootmicroservice.model.Profile +import org.springframework.data.repository.reactive.ReactiveCrudRepository +import org.springframework.stereotype.Repository + +@Repository +interface ProfileRepository: ReactiveCrudRepository \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/resources/application.yml b/spring-reactive-kotlin/src/main/resources/application.yml new file mode 100644 index 0000000000..d75683f905 --- /dev/null +++ b/spring-reactive-kotlin/src/main/resources/application.yml @@ -0,0 +1 @@ +management.endpoints.web.exposure.include: health,metrics \ No newline at end of file diff --git a/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt b/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt new file mode 100644 index 0000000000..51481af3d7 --- /dev/null +++ b/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt @@ -0,0 +1,51 @@ +package com.baeldung.bootmicroservice.controller; + +import com.baeldung.bootmicroservice.model.Profile +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.http.MediaType +import org.springframework.test.web.reactive.server.WebTestClient +import java.time.LocalDateTime + +@SpringBootTest +class ProfileControllerTest { + @Autowired + lateinit var controller: ProfileController + + @Autowired + lateinit var mapper: ObjectMapper ; + + lateinit var client: WebTestClient + lateinit var profile: String + + @BeforeEach + fun setup() { + client = WebTestClient.bindToController(controller).build() + profile = mapper.writeValueAsString(Profile(null, "kotlin", "reactive", LocalDateTime.now())) + } + + @Test + fun whenRequestProfile_thenStatusShouldBeOk() { + client.post() + .uri("/profile") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(profile) + .exchange() + .expectStatus().isOk + } + + @Test + fun whenRequestProfile_thenIdShouldBeNotNull() { + client.post() + .uri("/profile") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(profile) + .exchange() + .expectBody() + .jsonPath("$.id") + .isNotEmpty + } +} diff --git a/spring-rest-http/README.md b/spring-rest-http/README.md index 54b31e80c4..35793cb281 100644 --- a/spring-rest-http/README.md +++ b/spring-rest-http/README.md @@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Returning Custom Status Codes from Spring Controllers](https://www.baeldung.com/spring-mvc-controller-custom-http-status-code) - [Spring RequestMapping](https://www.baeldung.com/spring-requestmapping) - [Guide to DeferredResult in Spring](https://www.baeldung.com/spring-deferred-result) +- [Using JSON Patch in Spring REST APIs](https://www.baeldung.com/spring-rest-json-patch) diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java similarity index 92% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java index 9a361e92c9..3e4d1ffa00 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java similarity index 95% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java index a39994ae67..bef8af3725 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java similarity index 89% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java index 5e8220d064..75ce02ea04 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.springframework.boot.web.client.RestTemplateCustomizer; import org.springframework.web.client.RestTemplate; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java similarity index 97% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java index a9d400b199..dbef16b592 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; @@ -6,7 +6,7 @@ import java.net.URI; import java.util.Collection; import java.util.Map; -import org.baeldung.resttemplate.web.dto.Foo; +import com.baeldung.resttemplate.web.dto.Foo; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java similarity index 95% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java index ee404db4f8..854ca1a1c1 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java similarity index 82% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java index 966d5bcaa1..7866a4abcd 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -11,7 +11,7 @@ import org.springframework.web.client.RestTemplate; @Configuration @EnableAutoConfiguration -@ComponentScan("org.baeldung.resttemplate.configuration") +@ComponentScan("com.baeldung.resttemplate.configuration") public class SpringConfig { @Bean @@ -26,8 +26,4 @@ public class SpringConfig { return new RestTemplateBuilder(customRestTemplateCustomizer()); } - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } } diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java index 226134787f..8a1773483a 100644 --- a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java @@ -7,7 +7,7 @@ import com.baeldung.resttemplate.lists.dto.Employee; import java.util.ArrayList; import java.util.List; -@Service +@Service("EmployeeListService") public class EmployeeService { public List getAllEmployees() diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/controller/PersonAPI.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java similarity index 88% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/controller/PersonAPI.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java index b1b56ec2f3..b3131cc00c 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/controller/PersonAPI.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java @@ -1,9 +1,9 @@ -package org.baeldung.resttemplate.web.controller; +package com.baeldung.resttemplate.web.controller; import javax.servlet.http.HttpServletResponse; -import org.baeldung.resttemplate.web.dto.Person; -import org.baeldung.resttemplate.web.service.PersonService; +import com.baeldung.resttemplate.web.service.PersonService; +import com.baeldung.resttemplate.web.dto.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java similarity index 93% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java index ed0a42c429..ede91dab1a 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.web.dto; +package com.baeldung.resttemplate.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Person.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java similarity index 91% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Person.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java index 4b7679638f..11e56fc6e2 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Person.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.web.dto; +package com.baeldung.resttemplate.web.dto; public class Person { private Integer id; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java similarity index 55% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java index 3e606e9314..8eb217978c 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.web.exception; +package com.baeldung.resttemplate.web.exception; public class NotFoundException extends RuntimeException { } diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java similarity index 92% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java index 214de38746..02260438c7 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java @@ -1,8 +1,8 @@ -package org.baeldung.resttemplate.web.handler; +package com.baeldung.resttemplate.web.handler; import java.io.IOException; -import org.baeldung.resttemplate.web.exception.NotFoundException; +import com.baeldung.resttemplate.web.exception.NotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Component; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java similarity index 87% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java index cf5279697f..7f8902e2fc 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.web.model; +package com.baeldung.resttemplate.web.model; public class Bar { private String id; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java similarity index 93% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java index a9b84a77b4..bb1ad8cbfa 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java @@ -1,6 +1,5 @@ -package org.baeldung.resttemplate.web.model; +package com.baeldung.resttemplate.web.model; -import java.util.Date; import java.util.Objects; public class Employee { diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java similarity index 80% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java index 54a66ea591..485143b0a1 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java @@ -1,7 +1,7 @@ -package org.baeldung.resttemplate.web.service; +package com.baeldung.resttemplate.web.service; -import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; -import org.baeldung.resttemplate.web.model.Bar; +import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.model.Bar; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Service; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java similarity index 89% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java index c6562fbc94..18dff3db1b 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java @@ -1,6 +1,6 @@ -package org.baeldung.resttemplate.web.service; +package com.baeldung.resttemplate.web.service; -import org.baeldung.resttemplate.web.model.Employee; +import com.baeldung.resttemplate.web.model.Employee; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java similarity index 58% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonService.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java index c5ad39e101..e91d2adc5c 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java @@ -1,6 +1,6 @@ -package org.baeldung.resttemplate.web.service; +package com.baeldung.resttemplate.web.service; -import org.baeldung.resttemplate.web.dto.Person; +import com.baeldung.resttemplate.web.dto.Person; public interface PersonService { diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonServiceImpl.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java similarity index 77% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonServiceImpl.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java index 658e0fade0..d7a1bfc2db 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonServiceImpl.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java @@ -1,6 +1,6 @@ -package org.baeldung.resttemplate.web.service; +package com.baeldung.resttemplate.web.service; -import org.baeldung.resttemplate.web.dto.Person; +import com.baeldung.resttemplate.web.dto.Person; import org.springframework.stereotype.Component; @Component diff --git a/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java index 11ea5b70c9..5c385edb07 100644 --- a/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java +++ b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java @@ -20,7 +20,7 @@ import com.baeldung.sampleapp.web.dto.Foo; import com.baeldung.sampleapp.web.exception.ResourceNotFoundException; @Controller -@RequestMapping(value = "/foos") +@RequestMapping(value = "/foo") public class MyFooController { private final Map myfoos; diff --git a/spring-resttemplate/src/main/java/com/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/SpringContextTest.java rename to spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java b/spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java similarity index 71% rename from spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java rename to spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java index 7c4bbb4e5e..c626d1021d 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java +++ b/spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; @@ -8,12 +8,7 @@ import org.springframework.web.client.RestTemplate; @Configuration @EnableAutoConfiguration -@ComponentScan("org.baeldung") +@ComponentScan("com.baeldung") public class SpringTestConfig { - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } - } diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java b/spring-resttemplate/src/test/java/com/baeldung/client/Consts.java similarity index 68% rename from spring-resttemplate/src/test/java/org/baeldung/client/Consts.java rename to spring-resttemplate/src/test/java/com/baeldung/client/Consts.java index b40561d9c3..b392c4d199 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java +++ b/spring-resttemplate/src/test/java/com/baeldung/client/Consts.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package com.baeldung.client; public interface Consts { int APPLICATION_PORT = 8082; diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java similarity index 98% rename from spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java index 967c4a6188..9f4b3c9b35 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java @@ -1,10 +1,10 @@ -package org.baeldung.client; +package com.baeldung.client; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; -import org.baeldung.resttemplate.web.dto.Foo; +import com.baeldung.resttemplate.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.web.client.TestRestTemplate; diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java similarity index 99% rename from spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java index 21639818db..eb5d01d06f 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import org.assertj.core.api.Assertions; import org.junit.Assert; diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java similarity index 98% rename from spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java index 54e416d008..0dab124316 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java @@ -1,7 +1,7 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import static org.apache.commons.codec.binary.Base64.encodeBase64; -import static org.baeldung.client.Consts.APPLICATION_PORT; +import static com.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; @@ -14,8 +14,8 @@ import java.net.URI; import java.util.Arrays; import java.util.Set; -import org.baeldung.resttemplate.web.dto.Foo; -import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpEntity; diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/postjson/PersonAPILiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java similarity index 95% rename from spring-resttemplate/src/test/java/org/baeldung/resttemplate/postjson/PersonAPILiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java index 1347cb0c7a..f1861ede92 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/postjson/PersonAPILiveTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.resttemplate.postjson; +package com.baeldung.resttemplate.postjson; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.URI; -import org.baeldung.resttemplate.RestTemplateConfigurationApplication; -import org.baeldung.resttemplate.web.dto.Person; +import com.baeldung.resttemplate.RestTemplateConfigurationApplication; +import com.baeldung.resttemplate.web.dto.Person; import org.json.JSONException; import org.json.JSONObject; import org.junit.BeforeClass; diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java similarity index 90% rename from spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java index 60069cea71..688b6e9d56 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.web.handler; +package com.baeldung.web.handler; -import org.baeldung.resttemplate.web.exception.NotFoundException; -import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; -import org.baeldung.resttemplate.web.model.Bar; +import com.baeldung.resttemplate.web.exception.NotFoundException; +import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.model.Bar; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java similarity index 88% rename from spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java index f93ba71666..ee01cb6a50 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; @@ -6,9 +6,9 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat import java.net.URI; -import org.baeldung.SpringTestConfig; -import org.baeldung.resttemplate.web.model.Employee; -import org.baeldung.resttemplate.web.service.EmployeeService; +import com.baeldung.SpringTestConfig; +import com.baeldung.resttemplate.web.model.Employee; +import com.baeldung.resttemplate.web.service.EmployeeService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -16,6 +16,7 @@ import org.junit.runner.RunWith; 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.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -28,7 +29,7 @@ import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class) -@ContextConfiguration(classes = SpringTestConfig.class) +@SpringBootTest(classes = SpringTestConfig.class) public class EmployeeServiceMockRestServiceServerUnitTest { private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceMockRestServiceServerUnitTest.class); diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java similarity index 84% rename from spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java index f4b391573a..6eb040414b 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java @@ -1,15 +1,13 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; -import org.baeldung.resttemplate.web.model.Employee; -import org.baeldung.resttemplate.web.service.EmployeeService; +import com.baeldung.resttemplate.web.model.Employee; +import com.baeldung.resttemplate.web.service.EmployeeService; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; import org.mockito.runners.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e52d249f0b..0000000000 --- a/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.resttemplate.RestTemplateConfigurationApplication; -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 = RestTemplateConfigurationApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-mvc-boot-1/pom.xml b/spring-security-modules/spring-security-mvc-boot-1/pom.xml index 7dfee200d4..7ad18376ec 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/pom.xml +++ b/spring-security-modules/spring-security-mvc-boot-1/pom.xml @@ -222,10 +222,10 @@ - org.baeldung.custom.Application + com.baeldung.roles.custom.Application - + 1.1.2 1.6.1 diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/AppConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/AppConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java index 8719e39a20..ab2cc71fec 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/AppConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.relationships; import java.util.Properties; @@ -19,7 +19,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @SpringBootApplication @PropertySource({"classpath:persistence-h2.properties", "classpath:application-defaults.properties"}) -@EnableJpaRepositories(basePackages = { "com.baeldung.data.repositories" }) +@EnableJpaRepositories(basePackages = {"com.baeldung.relationships.repositories"}) @EnableWebMvc @Import(SpringSecurityConfig.class) public class AppConfig extends WebMvcConfigurerAdapter { @@ -41,7 +41,7 @@ public class AppConfig extends WebMvcConfigurerAdapter { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.models" }); + em.setPackagesToScan(new String[] { "com.baeldung.relationships.models" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/SpringSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java similarity index 94% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/SpringSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java index ee13678a24..88814038a8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/SpringSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.relationships; import javax.annotation.PostConstruct; import javax.sql.DataSource; @@ -18,8 +18,8 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.security.AuthenticationSuccessHandlerImpl; -import com.baeldung.security.CustomUserDetailsService; +import com.baeldung.relationships.security.AuthenticationSuccessHandlerImpl; +import com.baeldung.relationships.security.CustomUserDetailsService; @Configuration @EnableWebSecurity diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/AppUser.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/AppUser.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java index e48233f90a..2efd24e879 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/AppUser.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.relationships.models; import java.util.Date; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/Tweet.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/Tweet.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java index 54a96deaf3..d8496f89be 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/Tweet.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.relationships.models; import java.util.HashSet; import java.util.Set; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/TweetRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java similarity index 84% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/TweetRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java index 7d6446ed0d..4e4b16a151 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/TweetRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java @@ -1,11 +1,11 @@ -package com.baeldung.data.repositories; +package com.baeldung.relationships.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; -import com.baeldung.models.Tweet; +import com.baeldung.relationships.models.Tweet; public interface TweetRepository extends PagingAndSortingRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/UserRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/UserRepository.java similarity index 76% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/UserRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/UserRepository.java index 5240c683e0..883ea332f8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/UserRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/UserRepository.java @@ -1,18 +1,15 @@ -package com.baeldung.data.repositories; +package com.baeldung.relationships.repositories; import java.util.Date; import java.util.List; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; -import com.baeldung.models.AppUser; +import com.baeldung.relationships.models.AppUser; public interface UserRepository extends CrudRepository { AppUser findByUsername(String username); diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AppUserPrincipal.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AppUserPrincipal.java similarity index 93% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AppUserPrincipal.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AppUserPrincipal.java index 195f9f7bf6..1ae7d95e41 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AppUserPrincipal.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AppUserPrincipal.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.relationships.security; import java.util.Collection; import java.util.Collections; @@ -8,7 +8,7 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; -import com.baeldung.models.AppUser; +import com.baeldung.relationships.models.AppUser; public class AppUserPrincipal implements UserDetails { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java similarity index 88% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java index 3fc2bc6559..1b85294467 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.relationships.security; import java.io.IOException; import java.util.Date; @@ -12,7 +12,7 @@ import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; -import com.baeldung.data.repositories.UserRepository; +import com.baeldung.relationships.repositories.UserRepository; @Component public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/CustomUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java similarity index 87% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/CustomUserDetailsService.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java index 016f4f7fa9..10c266bb74 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/CustomUserDetailsService.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.relationships.security; import javax.annotation.PostConstruct; @@ -9,8 +9,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.data.repositories.UserRepository; -import com.baeldung.models.AppUser; +import com.baeldung.relationships.repositories.UserRepository; +import com.baeldung.relationships.models.AppUser; @Service public class CustomUserDetailsService implements UserDetailsService { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/util/DummyContentUtil.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/util/DummyContentUtil.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/util/DummyContentUtil.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/util/DummyContentUtil.java index f1640264d2..b8e5192b48 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/util/DummyContentUtil.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/util/DummyContentUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.util; +package com.baeldung.relationships.util; import java.util.ArrayList; import java.util.Collection; @@ -10,8 +10,8 @@ import java.util.stream.IntStream; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import com.baeldung.models.AppUser; -import com.baeldung.models.Tweet; +import com.baeldung.relationships.models.AppUser; +import com.baeldung.relationships.models.Tweet; public class DummyContentUtil { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/Application.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/Application.java similarity index 88% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/Application.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/Application.java index e051e5a853..e7ace1f962 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/Application.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.custom; +package com.baeldung.roles.custom; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; @SpringBootApplication -@ComponentScan("org.baeldung.custom") +@ComponentScan("com.baeldung.roles.custom") @PropertySource("classpath:application-defaults.properties") public class Application extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MethodSecurityConfig.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MethodSecurityConfig.java index 6a005153dc..57ab8b120f 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MethodSecurityConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.custom.config; +package com.baeldung.roles.custom.config; -import org.baeldung.custom.security.CustomMethodSecurityExpressionHandler; -import org.baeldung.custom.security.CustomPermissionEvaluator; +import com.baeldung.roles.custom.security.CustomMethodSecurityExpressionHandler; +import com.baeldung.roles.custom.security.CustomPermissionEvaluator; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MvcConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MvcConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MvcConfig.java index 58d11ea9ae..c99d1e38a5 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.config; +package com.baeldung.roles.custom.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/SecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java index 06357650dc..6bf04120ab 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.config; +package com.baeldung.roles.custom.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/SetupData.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/SetupData.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java index f0fcce3908..ab57e7436c 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/SetupData.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java @@ -1,16 +1,16 @@ -package org.baeldung.custom.persistence; +package com.baeldung.roles.custom.persistence; import java.util.Arrays; import java.util.HashSet; import javax.annotation.PostConstruct; -import org.baeldung.custom.persistence.dao.OrganizationRepository; -import org.baeldung.custom.persistence.dao.PrivilegeRepository; -import org.baeldung.custom.persistence.dao.UserRepository; -import org.baeldung.custom.persistence.model.Organization; -import org.baeldung.custom.persistence.model.Privilege; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.dao.OrganizationRepository; +import com.baeldung.roles.custom.persistence.dao.PrivilegeRepository; +import com.baeldung.roles.custom.persistence.dao.UserRepository; +import com.baeldung.roles.custom.persistence.model.Organization; +import com.baeldung.roles.custom.persistence.model.Privilege; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/OrganizationRepository.java similarity index 63% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/OrganizationRepository.java index 1319a7b9f8..2f585f3527 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/OrganizationRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.custom.persistence.dao; +package com.baeldung.roles.custom.persistence.dao; -import org.baeldung.custom.persistence.model.Organization; +import com.baeldung.roles.custom.persistence.model.Organization; import org.springframework.data.jpa.repository.JpaRepository; public interface OrganizationRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/PrivilegeRepository.java similarity index 62% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/PrivilegeRepository.java index c232bb986c..c83e0f505e 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/PrivilegeRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.custom.persistence.dao; +package com.baeldung.roles.custom.persistence.dao; -import org.baeldung.custom.persistence.model.Privilege; +import com.baeldung.roles.custom.persistence.model.Privilege; import org.springframework.data.jpa.repository.JpaRepository; public interface PrivilegeRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/UserRepository.java similarity index 74% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/UserRepository.java index 68dd1d756c..884a998219 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.custom.persistence.dao; +package com.baeldung.roles.custom.persistence.dao; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Foo.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Foo.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java index f139382eea..3dbf48f7ce 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Foo.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.persistence.model; +package com.baeldung.roles.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Organization.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Organization.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java index 1fdb88e320..0d0220b6b2 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Organization.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.persistence.model; +package com.baeldung.roles.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Privilege.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Privilege.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java index ed3edd5085..60e0506641 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Privilege.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.persistence.model; +package com.baeldung.roles.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/User.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/User.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java index c14ef034b4..219f40a3df 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/User.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.persistence.model; +package com.baeldung.roles.custom.persistence.model; import java.util.Set; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionHandler.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionHandler.java index 646f5a387f..76e94a9dd4 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import org.aopalliance.intercept.MethodInvocation; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionRoot.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionRoot.java index b2f2be8cf5..dd9f6a5786 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionRoot.java @@ -1,6 +1,6 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.security.access.expression.SecurityExpressionRoot; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.core.Authentication; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomPermissionEvaluator.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomPermissionEvaluator.java index f436b4488b..d69e405b28 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomPermissionEvaluator.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import java.io.Serializable; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MySecurityExpressionRoot.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MySecurityExpressionRoot.java index 03d18cb755..8448ad9075 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MySecurityExpressionRoot.java @@ -1,11 +1,11 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Set; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserDetailsService.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserDetailsService.java index b9b40fbcb9..c6514d6c05 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserDetailsService.java @@ -1,7 +1,7 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; -import org.baeldung.custom.persistence.dao.UserRepository; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.dao.UserRepository; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserPrincipal.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserPrincipal.java index 7d57227316..41741c64f4 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserPrincipal.java @@ -1,11 +1,11 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.baeldung.custom.persistence.model.Privilege; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.Privilege; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/web/MainController.java similarity index 87% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/web/MainController.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/web/MainController.java index 74de45d1a8..beb12f7749 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/web/MainController.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/web/MainController.java @@ -1,9 +1,9 @@ -package org.baeldung.custom.web; +package com.baeldung.roles.custom.web; -import org.baeldung.custom.persistence.dao.OrganizationRepository; -import org.baeldung.custom.persistence.model.Foo; -import org.baeldung.custom.persistence.model.Organization; -import org.baeldung.custom.security.MyUserPrincipal; +import com.baeldung.roles.custom.persistence.dao.OrganizationRepository; +import com.baeldung.roles.custom.persistence.model.Foo; +import com.baeldung.roles.custom.persistence.model.Organization; +import com.baeldung.roles.custom.security.MyUserPrincipal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/IpApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/IpApplication.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/IpApplication.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/IpApplication.java index d77414c54e..b9a86fee3e 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/IpApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/IpApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.ip; +package com.baeldung.roles.ip; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; @SpringBootApplication -@ComponentScan("org.baeldung.ip") +@ComponentScan("com.baeldung.ip") @PropertySource("classpath:application-defaults.properties") public class IpApplication extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java index 078dd81259..adcadb65e8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java @@ -1,4 +1,4 @@ -package org.baeldung.ip.config; +package com.baeldung.roles.ip.config; import java.util.ArrayList; import java.util.HashSet; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java index 3a8032a734..46ba62afb3 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ip.config; +package com.baeldung.roles.ip.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityXmlConfig.java similarity index 78% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityXmlConfig.java index 1d22ca4c67..4b2cf43f6a 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityXmlConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ip.config; +package com.baeldung.roles.ip.config; //@Configuration diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java similarity index 94% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/web/MainController.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java index 940194c421..438b668c5f 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/web/MainController.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java @@ -1,11 +1,11 @@ -package org.baeldung.ip.web; +package com.baeldung.roles.ip.web; import java.util.List; import javax.servlet.Filter; import javax.servlet.http.HttpServletRequest; -import org.baeldung.custom.persistence.model.Foo; +import com.baeldung.roles.custom.persistence.model.Foo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.web.FilterChainProxy; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/CustomAuthenticationProvider.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/CustomAuthenticationProvider.java index d7195ac358..5168e64b4a 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/CustomAuthenticationProvider.java @@ -1,7 +1,7 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; -import org.baeldung.rolesauthorities.model.User; -import org.baeldung.rolesauthorities.persistence.UserRepository; +import com.baeldung.roles.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.persistence.UserRepository; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java index b0dc0b7537..23104e5292 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; import java.io.IOException; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyUserDetailsService.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyUserDetailsService.java index f38b867a75..18230ba794 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyUserDetailsService.java @@ -1,13 +1,13 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; -import org.baeldung.rolesauthorities.model.Role; -import org.baeldung.rolesauthorities.model.User; -import org.baeldung.rolesauthorities.persistence.UserRepository; +import com.baeldung.roles.rolesauthorities.model.Role; +import com.baeldung.roles.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.persistence.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/RolesAuthoritiesApplication.java similarity index 87% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/RolesAuthoritiesApplication.java index 3c4e6f7b5a..d3e54b4303 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/RolesAuthoritiesApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -8,7 +8,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration -@ComponentScan("org.baeldung.rolesauthorities") +@ComponentScan("com.baeldung.rolesauthorities") public class RolesAuthoritiesApplication extends SpringBootServletInitializer { public static void main(String[] args) { System.setProperty("spring.profiles.default", "rolesauthorities"); diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/MvcConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/MvcConfig.java index c42958457e..61394b6178 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/MvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities.config; +package com.baeldung.roles.rolesauthorities.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java index 7624dd7d39..cb8476fcc7 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.rolesauthorities.config; +package com.baeldung.roles.rolesauthorities.config; -import org.baeldung.rolesauthorities.CustomAuthenticationProvider; -import org.baeldung.rolesauthorities.persistence.UserRepository; +import com.baeldung.roles.rolesauthorities.CustomAuthenticationProvider; +import com.baeldung.roles.rolesauthorities.persistence.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -18,7 +18,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; @Configuration -@ComponentScan(basePackages = { "org.baeldung.rolesauthorities" }) +@ComponentScan(basePackages = {"com.baeldung.rolesauthorities"}) @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @@ -76,7 +76,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public DaoAuthenticationProvider authProvider() { - final CustomAuthenticationProvider authProvider + final CustomAuthenticationProvider authProvider = new CustomAuthenticationProvider(userRepository, userDetailsService); authProvider.setPasswordEncoder(encoder()); return authProvider; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java index ab2cd08610..507beaffa8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities.model; +package com.baeldung.roles.rolesauthorities.model; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Role.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Role.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java index ac33e32fcf..a284d92090 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Role.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities.model; +package com.baeldung.roles.rolesauthorities.model; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/User.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/User.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java index dc1096541d..ebf0c9b310 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/User.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities.model; +package com.baeldung.roles.rolesauthorities.model; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/IUserService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/IUserService.java new file mode 100644 index 0000000000..be9cb911d7 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/IUserService.java @@ -0,0 +1,9 @@ +package com.baeldung.roles.rolesauthorities.persistence; + +import com.baeldung.roles.rolesauthorities.model.User; + +public interface IUserService { + + User findUserByEmail(String email); + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/PrivilegeRepository.java similarity index 65% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/PrivilegeRepository.java index 05d5f2b870..f8ba7def49 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/PrivilegeRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; -import org.baeldung.rolesauthorities.model.Privilege; +import com.baeldung.roles.rolesauthorities.model.Privilege; import org.springframework.data.jpa.repository.JpaRepository; public interface PrivilegeRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/RoleRepository.java similarity index 63% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/RoleRepository.java index 25e3b3a1f6..e5833712fe 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/RoleRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; -import org.baeldung.rolesauthorities.model.Role; +import com.baeldung.roles.rolesauthorities.model.Role; import org.springframework.data.jpa.repository.JpaRepository; public interface RoleRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/SetupDataLoader.java similarity index 93% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/SetupDataLoader.java index 46dad4f06d..140fc56e53 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/SetupDataLoader.java @@ -1,13 +1,13 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; -import org.baeldung.rolesauthorities.model.Privilege; -import org.baeldung.rolesauthorities.model.Role; -import org.baeldung.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.model.Privilege; +import com.baeldung.roles.rolesauthorities.model.Role; +import com.baeldung.roles.rolesauthorities.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserRepository.java similarity index 64% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserRepository.java index bca2953153..6801eec01d 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; -import org.baeldung.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java similarity index 77% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java index 3b16c78898..17770e5cd0 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java @@ -1,8 +1,8 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; import javax.transaction.Transactional; -import org.baeldung.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/MinuteBasedVoter.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/MinuteBasedVoter.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java index 2beda1e557..6970441a4e 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/MinuteBasedVoter.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java @@ -1,4 +1,4 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import java.time.LocalDateTime; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterApplication.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java index d2078e6115..d3e0652ae9 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -7,7 +7,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration -@ComponentScan(basePackages = { "org.baeldung.voter" }) +@ComponentScan(basePackages = {"com.baeldung.voter"}) public class VoterApplication { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java similarity index 71% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterMvcConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java index 8f41153f06..f11a4ae06c 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterMvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java @@ -1,10 +1,8 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by ambrusadrianz on 30/09/2016. diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/WebSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java index 84ed070e8e..8a0f438b49 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -15,7 +15,6 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.access.expression.WebExpressionVoter; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import java.util.Arrays; import java.util.List; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/XmlSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/XmlSecurityConfig.java similarity index 60% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/XmlSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/XmlSecurityConfig.java index 8041585f42..0ef2ef51c7 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/XmlSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/XmlSecurityConfig.java @@ -1,7 +1,4 @@ -package org.baeldung.voter; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +package com.baeldung.roles.voter; /** * Created by ambrusadrianz on 09/10/2016. diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java deleted file mode 100644 index 2c508cbd20..0000000000 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.rolesauthorities.persistence; - -import org.baeldung.rolesauthorities.model.User; - -public interface IUserService { - - User findUserByEmail(String email); - -} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml index 0b334a3694..9f510280a1 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml @@ -22,12 +22,12 @@ - + - + diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java index b2def82c51..54120650d9 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java @@ -1,12 +1,11 @@ package com.baeldung.relationships; -import com.baeldung.AppConfig; -import com.baeldung.data.repositories.TweetRepository; -import com.baeldung.data.repositories.UserRepository; -import com.baeldung.models.AppUser; -import com.baeldung.models.Tweet; -import com.baeldung.security.AppUserPrincipal; -import com.baeldung.util.DummyContentUtil; +import com.baeldung.relationships.repositories.TweetRepository; +import com.baeldung.relationships.repositories.UserRepository; +import com.baeldung.relationships.models.AppUser; +import com.baeldung.relationships.models.Tweet; +import com.baeldung.relationships.security.AppUserPrincipal; +import com.baeldung.relationships.util.DummyContentUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/SpringContextTest.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/SpringContextTest.java index 2041249b71..7b23b878c8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung.roles; -import org.baeldung.custom.Application; +import com.baeldung.roles.custom.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/ApplicationLiveTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java similarity index 94% rename from spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/ApplicationLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java index e199411e58..5a040b8dea 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/ApplicationLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java @@ -1,9 +1,9 @@ -package org.baeldung.web; +package com.baeldung.roles.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.baeldung.custom.persistence.model.Foo; +import com.baeldung.roles.custom.persistence.model.Foo; import io.restassured.RestAssured; import io.restassured.authentication.FormAuthConfig; @@ -13,7 +13,7 @@ import io.restassured.specification.RequestSpecification; import org.junit.Test; import org.springframework.http.MediaType; -// In order to execute these tests, org.baeldung.custom.Application needs to be running. +// In order to execute these tests, com.baeldung.custom.Application needs to be running. public class ApplicationLiveTest { @Test diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java index a69b52c0dd..df7645150f 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.roles.web; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -7,8 +7,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.http.HttpHeaders; -import org.baeldung.custom.Application; -import org.baeldung.custom.persistence.model.Foo; +import com.baeldung.roles.custom.Application; +import com.baeldung.roles.custom.persistence.model.Foo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -59,7 +59,7 @@ public class CustomUserDetailsServiceIntegrationTest { @WithAnonymousUser public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception { this.mvc.perform(get("/foos/1").with(csrf())) - .andExpect(status().isFound()); + .andExpect(status().isFound()); } @Test diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/IpLiveTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/IpLiveTest.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/IpLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/IpLiveTest.java index 761f5450f7..2d0e2e5402 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/IpLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/IpLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.roles.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -8,7 +8,7 @@ import io.restassured.response.Response; import org.junit.Test; -// In order to execute these tests, org.baeldung.ip.IpApplication needs to be running. +// In order to execute these tests, com.baeldung.ip.IpApplication needs to be running. public class IpLiveTest { @Test diff --git a/spring-security-modules/spring-security-mvc-boot-2/pom.xml b/spring-security-modules/spring-security-mvc-boot-2/pom.xml index 565528e070..668eb04cd9 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/pom.xml +++ b/spring-security-modules/spring-security-mvc-boot-2/pom.xml @@ -222,16 +222,15 @@ - org.baeldung.custom.Application - - + + + com.baeldung.multiplelogin.MultipleLoginApplication - + - + 1.1.2 1.6.1 diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java index 6936cdc560..d71885d73c 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.h2; +package com.baeldung.jdbcauthentication.h2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java index 8b8696f0b2..50dc5b6958 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.h2.config; +package com.baeldung.jdbcauthentication.h2.config; import javax.sql.DataSource; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/web/UserController.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/web/UserController.java index 0955061614..03271677a4 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/web/UserController.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.h2.web; +package com.baeldung.jdbcauthentication.h2.web; import java.security.Principal; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java index 52934e0096..1f4c54e512 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.mysql; +package com.baeldung.jdbcauthentication.mysql; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java index 157c0be748..a0584818cd 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.mysql.config; +package com.baeldung.jdbcauthentication.mysql.config; import javax.sql.DataSource; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java similarity index 88% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java index f1060b5f78..ed15f8bfe6 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.mysql.web; +package com.baeldung.jdbcauthentication.mysql.web; import java.security.Principal; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java index 2c4d1a5255..4b074ef51d 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.postgre; +package com.baeldung.jdbcauthentication.postgre; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java similarity index 93% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java index ba79635852..85dc9d364c 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.postgre.config; +package com.baeldung.jdbcauthentication.postgre.config; import javax.sql.DataSource; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java similarity index 88% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java index c8fd3812b1..da85a46562 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.postgre.web; +package com.baeldung.jdbcauthentication.postgre.web; import java.security.Principal; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/CustomAuthenticationProvider.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/CustomAuthenticationProvider.java index 1a89c362cd..97a8d8ac2a 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/CustomAuthenticationProvider.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import java.util.Collections; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthController.java similarity index 85% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthController.java index b63169bb00..0079c84c6c 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthController.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java index 1f641298c3..e1a437e9a9 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java index 3819e981a2..aa2ffc9046 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java index 847dab073e..4ed36f770f 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleentrypoints; +package com.baeldung.multipleentrypoints; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java similarity index 99% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java index dc89c83cde..b6155fc100 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleentrypoints; +package com.baeldung.multipleentrypoints; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/PagesController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/PagesController.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/PagesController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/PagesController.java index b3462d4061..ba5028aea7 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/PagesController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/PagesController.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleentrypoints; +package com.baeldung.multipleentrypoints; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginApplication.java similarity index 85% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginApplication.java index 90bb5e4260..abba2ba339 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,7 +7,6 @@ import org.springframework.context.annotation.PropertySource; @SpringBootApplication @PropertySource("classpath:application-defaults.properties") -@ComponentScan("org.baeldung.multiplelogin") public class MultipleLoginApplication { public static void main(String[] args) { SpringApplication.run(MultipleLoginApplication.class, args); diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginMvcConfig.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginMvcConfig.java index 204b186411..86b3314c7c 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginMvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -6,14 +6,12 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import org.springframework.context.annotation.ComponentScan; @EnableWebMvc @Configuration -@ComponentScan("org.baeldung.controller") public class MultipleLoginMvcConfig implements WebMvcConfigurer { public MultipleLoginMvcConfig() { diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginSecurityConfig.java similarity index 99% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginSecurityConfig.java index 9962bf41a9..3d12951f39 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/UsersController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/UsersController.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/UsersController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/UsersController.java index 61d7da127c..03be0fd6b2 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/UsersController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/UsersController.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/HttpsEnabledApplication.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/HttpsEnabledApplication.java index 17c249067c..f6a550ae54 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/HttpsEnabledApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.ssl; +package com.baeldung.ssl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/SecurityConfig.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/SecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/SecurityConfig.java index 92f92d8fc7..4bddf0592a 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/SecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ssl; +package com.baeldung.ssl; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/WelcomeController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/WelcomeController.java similarity index 74% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/WelcomeController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/WelcomeController.java index 72ad8abb85..2bd8c8cfde 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/WelcomeController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/WelcomeController.java @@ -1,8 +1,7 @@ -package org.baeldung.ssl; +package com.baeldung.ssl; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; @Controller public class WelcomeController { diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/SpringContextTest.java similarity index 76% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/SpringContextTest.java index 659dad9155..5bd2a0ce27 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/SpringContextTest.java @@ -1,6 +1,5 @@ -package org.baeldung.jdbcauthentication.h2; +package com.baeldung.jdbcauthentication.h2; -import org.baeldung.jdbcauthentication.h2.H2JdbcAuthenticationApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java index 638e9d7919..12b5ca5867 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.h2.web; +package com.baeldung.jdbcauthentication.h2.web; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java index 261063cbb6..79bc84ea69 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.mysql.web; +package com.baeldung.jdbcauthentication.mysql.web; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java index 82bf6df8db..e6426a843e 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.postgre.web; +package com.baeldung.jdbcauthentication.postgre.web; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/HttpsApplicationIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/HttpsApplicationIntegrationTest.java index fe7883ec94..63d47e6a46 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/HttpsApplicationIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web; +package com.baeldung.web; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; -import org.baeldung.ssl.HttpsEnabledApplication; +import com.baeldung.ssl.HttpsEnabledApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java index 9ef09f1f67..c5ef469fe8 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web; +package com.baeldung.web; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; -import org.baeldung.multipleauthproviders.MultipleAuthProvidersApplication; +import com.baeldung.multipleauthproviders.MultipleAuthProvidersApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleEntryPointsIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleEntryPointsIntegrationTest.java index 422be2ac88..352b4af244 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleEntryPointsIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import org.junit.Before; import org.junit.Test; @@ -15,7 +15,7 @@ import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -import org.baeldung.multipleentrypoints.MultipleEntryPointsApplication; +import com.baeldung.multipleentrypoints.MultipleEntryPointsApplication; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 19f49ea59d..73c186cae3 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -2,6 +2,8 @@ package org.baeldung.security; import java.io.IOException; import java.util.Collection; +import java.util.HashMap; +import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -47,26 +49,21 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu } protected String determineTargetUrl(final Authentication authentication) { - boolean isUser = false; - boolean isAdmin = false; + + Map roleTargetUrlMap = new HashMap<>(); + roleTargetUrlMap.put("ROLE_USER", "/homepage.html"); + roleTargetUrlMap.put("ROLE_ADMIN", "/console.html"); + final Collection authorities = authentication.getAuthorities(); for (final GrantedAuthority grantedAuthority : authorities) { - if (grantedAuthority.getAuthority().equals("ROLE_USER")) { - isUser = true; - break; - } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { - isAdmin = true; - break; + + String authorityName = grantedAuthority.getAuthority(); + if(roleTargetUrlMap.containsKey(authorityName)) { + return roleTargetUrlMap.get(authorityName); } } - if (isUser) { - return "/homepage.html"; - } else if (isAdmin) { - return "/console.html"; - } else { - throw new IllegalStateException(); - } + throw new IllegalStateException(); } /** @@ -83,12 +80,4 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } - public void setRedirectStrategy(final RedirectStrategy redirectStrategy) { - this.redirectStrategy = redirectStrategy; - } - - protected RedirectStrategy getRedirectStrategy() { - return redirectStrategy; - } - } diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MyUserDetailsService.java new file mode 100644 index 0000000000..43eb39e927 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MyUserDetailsService.java @@ -0,0 +1,32 @@ +package org.baeldung.spring; + +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.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.*; + +@Service +public class MyUserDetailsService implements UserDetailsService { + + private Map roles = new HashMap<>(); + + @PostConstruct + public void init() { + roles.put("admin", new User("admin", "{noop}admin1", getAuthority("ROLE_ADMIN"))); + roles.put("user", new User("user", "{noop}user1", getAuthority("ROLE_USER"))); + } + + @Override + public UserDetails loadUserByUsername(String username) { + return roles.get(username); + } + + private List getAuthority(String role) { + return Collections.singletonList(new SimpleGrantedAuthority(role)); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java index ebe23950a7..fe00e6943b 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,11 +1,9 @@ package org.baeldung.spring; import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; -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.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @@ -15,7 +13,7 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand //@ImportResource({ "classpath:webSecurityConfig.xml" }) @EnableWebSecurity public class SecSecurityConfig extends WebSecurityConfigurerAdapter { - + public SecSecurityConfig() { super(); } @@ -26,43 +24,34 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { return super.authenticationManagerBean(); } - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("user1").password("{noop}user1Pass").roles("USER") - .and() - .withUser("admin1").password("{noop}admin1Pass").roles("ADMIN"); - // @formatter:on - } - @Override protected void configure(final HttpSecurity http) throws Exception { // @formatter:off - http.authorizeRequests() - .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*").permitAll() - .anyRequest().authenticated() - + http + .authorizeRequests() + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + .and() .formLogin() - .loginPage("/login.html") - .loginProcessingUrl("/login") - .successHandler(myAuthenticationSuccessHandler()) - .failureUrl("/login.html?error=true") - + .loginPage("/login.html") + .loginProcessingUrl("/login") + .successHandler(myAuthenticationSuccessHandler()) + .failureUrl("/login.html?error=true") + .and() - .logout().deleteCookies("JSESSIONID") - + .logout().deleteCookies("JSESSIONID") + .and() - .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) - + .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) + .and() - .csrf().disable() + .csrf().disable() ; // @formatter:on } - + @Bean public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){ return new MySimpleUrlAuthenticationSuccessHandler(); diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 579d2327e8..42a414afdc 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-session 1.0.0-SNAPSHOT spring-session diff --git a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-jdbc/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java rename to spring-session/spring-session-jdbc/src/test/java/com/baeldung/SpringContextTest.java index b69855ba38..8f6c2f2889 100644 --- a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-session/spring-session-jdbc/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/SpringContextTest.java similarity index 96% rename from spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java rename to spring-session/spring-session-mongodb/src/test/java/com/baeldung/SpringContextTest.java index cc935b8cfb..babcdb2ccf 100644 --- a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; import org.junit.Test; diff --git a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-session/spring-session-redis/src/test/java/com/baeldung/SpringContextLiveTest.java similarity index 96% rename from spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextLiveTest.java rename to spring-session/spring-session-redis/src/test/java/com/baeldung/SpringContextLiveTest.java index 3a4f14e9e6..2e33255e01 100644 --- a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextLiveTest.java +++ b/spring-session/spring-session-redis/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java b/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java rename to spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java index ff22398ca4..8dc2455e63 100644 --- a/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-social-login/src/main/java/org/baeldung/config/Application.java b/spring-social-login/src/main/java/com/baeldung/config/Application.java similarity index 80% rename from spring-social-login/src/main/java/org/baeldung/config/Application.java rename to spring-social-login/src/main/java/com/baeldung/config/Application.java index cf6251a51e..5d083d2d47 100644 --- a/spring-social-login/src/main/java/org/baeldung/config/Application.java +++ b/spring-social-login/src/main/java/com/baeldung/config/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,8 +7,8 @@ import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication -@EnableJpaRepositories("org.baeldung.persistence.dao") -@EntityScan("org.baeldung.persistence.model") +@EnableJpaRepositories("com.baeldung.persistence.dao") +@EntityScan("com.baeldung.persistence.model") public class Application extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java similarity index 92% rename from spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java rename to spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java index 8e439653a9..3d3081fef9 100644 --- a/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.config; +package com.baeldung.config; -import org.baeldung.security.FacebookSignInAdapter; -import org.baeldung.security.FacebookConnectionSignup; +import com.baeldung.security.FacebookSignInAdapter; +import com.baeldung.security.FacebookConnectionSignup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -18,7 +18,7 @@ import org.springframework.social.connect.web.ProviderSignInController; @Configuration @EnableWebSecurity -@ComponentScan(basePackages = { "org.baeldung.security" }) +@ComponentScan(basePackages = { "com.baeldung.security" }) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired diff --git a/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java b/spring-social-login/src/main/java/com/baeldung/config/WebConfig.java similarity index 98% rename from spring-social-login/src/main/java/org/baeldung/config/WebConfig.java rename to spring-social-login/src/main/java/com/baeldung/config/WebConfig.java index 8cfcd6cb41..d178cc28a6 100644 --- a/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-social-login/src/main/java/com/baeldung/config/WebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-social-login/src/main/java/com/baeldung/persistence/dao/UserRepository.java similarity index 69% rename from spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java rename to spring-social-login/src/main/java/com/baeldung/persistence/dao/UserRepository.java index 679dd6c363..aeb443dd06 100644 --- a/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ b/spring-social-login/src/main/java/com/baeldung/persistence/dao/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.dao; +package com.baeldung.persistence.dao; -import org.baeldung.persistence.model.User; +import com.baeldung.persistence.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java b/spring-social-login/src/main/java/com/baeldung/persistence/model/User.java similarity index 96% rename from spring-social-login/src/main/java/org/baeldung/persistence/model/User.java rename to spring-social-login/src/main/java/com/baeldung/persistence/model/User.java index a4cffc27d0..ce1774ca2c 100644 --- a/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-social-login/src/main/java/com/baeldung/persistence/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package com.baeldung.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java b/spring-social-login/src/main/java/com/baeldung/security/FacebookConnectionSignup.java similarity index 85% rename from spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java rename to spring-social-login/src/main/java/com/baeldung/security/FacebookConnectionSignup.java index 6a9e30d7d8..e0a9fdc2e7 100644 --- a/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java +++ b/spring-social-login/src/main/java/com/baeldung/security/FacebookConnectionSignup.java @@ -1,9 +1,9 @@ -package org.baeldung.security; +package com.baeldung.security; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.User; +import com.baeldung.persistence.dao.UserRepository; +import com.baeldung.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.social.connect.Connection; import org.springframework.social.connect.ConnectionSignUp; diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java b/spring-social-login/src/main/java/com/baeldung/security/FacebookSignInAdapter.java similarity index 96% rename from spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java rename to spring-social-login/src/main/java/com/baeldung/security/FacebookSignInAdapter.java index b861609a01..3050941ffa 100644 --- a/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java +++ b/spring-social-login/src/main/java/com/baeldung/security/FacebookSignInAdapter.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.util.Arrays; diff --git a/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-social-login/src/main/java/com/baeldung/security/MyUserDetailsService.java similarity index 89% rename from spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java rename to spring-social-login/src/main/java/com/baeldung/security/MyUserDetailsService.java index 5d0d5d793a..126f02e74a 100644 --- a/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-social-login/src/main/java/com/baeldung/security/MyUserDetailsService.java @@ -1,9 +1,9 @@ -package org.baeldung.security; +package com.baeldung.security; import java.util.Arrays; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.User; +import com.baeldung.persistence.dao.UserRepository; +import com.baeldung.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; diff --git a/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java b/spring-social-login/src/test/java/com/baeldung/SpringContextTest.java similarity index 88% rename from spring-social-login/src/test/java/org/baeldung/SpringContextTest.java rename to spring-social-login/src/test/java/com/baeldung/SpringContextTest.java index cfd8759c52..1d9711b5a4 100644 --- a/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-social-login/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.config.Application; +import com.baeldung.config.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-spel/src/test/java/org/baeldung/SpringContextTest.java b/spring-spel/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-spel/src/test/java/org/baeldung/SpringContextTest.java rename to spring-spel/src/test/java/com/baeldung/SpringContextTest.java index e25c1bf8e4..338b8b1e68 100644 --- a/spring-spel/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-spel/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java b/spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java similarity index 97% rename from spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java rename to spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java index 1e847c0d65..407cd8ebb0 100644 --- a/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 98% rename from spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 316642ab6f..d6c54f8099 100644 --- a/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import javax.servlet.http.HttpServletRequest; diff --git a/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java b/spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java similarity index 83% rename from spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java rename to spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java index c379d20047..97e7cf96fc 100644 --- a/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java +++ b/spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -8,7 +8,7 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration -@ComponentScan(basePackages = { "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) +@ComponentScan(basePackages = { "com.baeldung.persistence.service", "com.baeldung.persistence.dao" }) @Import({ MvcConfig.class, SecSecurityConfig.class }) @PropertySource("classpath:application.properties") public class AppConfig { diff --git a/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java similarity index 96% rename from spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java rename to spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java index 7bd03617be..f23fe14fb8 100644 --- a/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import java.util.Locale; @@ -25,7 +25,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration -@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) +@ComponentScan(basePackages = { "com.baeldung.web.controller", "com.baeldung.persistence.service", "com.baeldung.persistence.dao" }) @EnableWebMvc public class MvcConfig implements WebMvcConfigurer { @Autowired diff --git a/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 90% rename from spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java index 4da114c78b..3e630b8729 100644 --- a/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; diff --git a/spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java similarity index 96% rename from spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java rename to spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java index 44645a1471..dd58c7c2b6 100644 --- a/spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java +++ b/spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import java.io.IOException; import java.text.DateFormat; diff --git a/spring-static-resources/src/main/resources/webSecurityConfig.xml b/spring-static-resources/src/main/resources/webSecurityConfig.xml index ea64ad5aea..2278cb6138 100644 --- a/spring-static-resources/src/main/resources/webSecurityConfig.xml +++ b/spring-static-resources/src/main/resources/webSecurityConfig.xml @@ -23,7 +23,7 @@ - + diff --git a/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java index 0dcbba3221..153b290de7 100644 --- a/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ package com.baeldung; -import org.baeldung.spring.SecSecurityConfig; +import com.baeldung.spring.SecSecurityConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index dee9415679..39d8902956 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -15,6 +15,7 @@ spring-swagger-codegen-api-client + spring-openapi-generator-api-client spring-swagger-codegen-app diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator-ignore b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator/VERSION b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator/VERSION new file mode 100644 index 0000000000..ec87108d82 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.2.3 \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/.travis.yml b/spring-swagger-codegen/spring-openapi-generator-api-client/.travis.yml new file mode 100644 index 0000000000..e3bdf2af1b --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/README.md b/spring-swagger-codegen/spring-openapi-generator-api-client/README.md new file mode 100644 index 0000000000..01fd596268 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/README.md @@ -0,0 +1,174 @@ +# spring-openapi-generator-api-client + +Swagger Petstore + +- API version: 1.0.3 + +- Build date: 2020-03-15T06:14:01.568992-05:00[America/Chicago] + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: + +1. Java 1.8+ +2. Maven/Gradle + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + com.baeldung + spring-openapi-generator-api-client + 0.0.1-SNAPSHOT + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "com.baeldung:spring-openapi-generator-api-client:0.0.1-SNAPSHOT" +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +- `target/spring-openapi-generator-api-client-0.0.1-SNAPSHOT.jar` +- `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import com.baeldung.petstore.client.invoker.*; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.model.*; +import com.baeldung.petstore.client.api.PetApi; + +public class PetApiExample { + + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [Category](docs/Category.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### petstore_auth + + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: https://petstore.swagger.io/oauth/authorize +- **Scopes**: + - read:pets: read your pets + - write:pets: modify pets in your account + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +apiteam@swagger.io + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/build.gradle b/spring-swagger-codegen/spring-openapi-generator-api-client/build.gradle new file mode 100644 index 0000000000..d86deb75b8 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/build.gradle @@ -0,0 +1,120 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'com.baeldung' +version = '0.0.1-SNAPSHOT' + +buildscript { + repositories { + maven { url "https://repo1.maven.org/maven2" } + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + install { + repositories.mavenInstaller { + pom.artifactId = 'spring-openapi-generator-api-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.22" + jackson_version = "2.10.1" + jackson_databind_version = "2.10.1" + jackson_databind_nullable_version = "0.2.1" + spring_web_version = "4.3.9.RELEASE" + jodatime_version = "2.9.9" + junit_version = "4.13" + jackson_threeten_version = "2.9.10" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.google.code.findbugs:jsr305:3.0.2" + compile "org.springframework:spring-web:$spring_web_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threeten_version" + testCompile "junit:junit:$junit_version" +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/build.sbt b/spring-swagger-codegen/spring-openapi-generator-api-client/build.sbt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Category.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Category.md new file mode 100644 index 0000000000..848fb61818 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Category.md @@ -0,0 +1,13 @@ + + +# Category + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/ModelApiResponse.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/ModelApiResponse.md new file mode 100644 index 0000000000..14fb7f1ed2 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/ModelApiResponse.md @@ -0,0 +1,14 @@ + + +# ModelApiResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Order.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Order.md new file mode 100644 index 0000000000..409fc4cc96 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Order.md @@ -0,0 +1,27 @@ + + +# Order + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum + +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Pet.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Pet.md new file mode 100644 index 0000000000..37ac007b79 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Pet.md @@ -0,0 +1,27 @@ + + +# Pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum + +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/PetApi.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/PetApi.md new file mode 100644 index 0000000000..56e81ea3aa --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/PetApi.md @@ -0,0 +1,581 @@ +# PetApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +## addPet + +> addPet(body) + +Add a new pet to the store + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +## deletePet + +> deletePet(petId, apiKey) + +Deletes a pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | Pet id to delete + String apiKey = "apiKey_example"; // String | + try { + apiInstance.deletePet(petId, apiKey); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## findPetsByStatus + +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List status = Arrays.asList("available"); // List | Status values that need to be considered for filter + try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + + +## findPetsByTags + +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List tags = Arrays.asList(); // List | Tags to filter by + try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + + +## getPetById + +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to return + try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## updatePet + +> updatePet(body) + +Update an existing pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.updatePet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + + +## updatePetWithForm + +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet that needs to be updated + String name = "name_example"; // String | Updated name of the pet + String status = "status_example"; // String | Updated status of the pet + try { + apiInstance.updatePetWithForm(petId, name, status); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +## uploadFile + +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + File file = new File("/path/to/file"); // File | file to upload + try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/StoreApi.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/StoreApi.md new file mode 100644 index 0000000000..7a70c0bdbc --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/StoreApi.md @@ -0,0 +1,276 @@ +# StoreApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +## deleteOrder + +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of the order that needs to be deleted + try { + apiInstance.deleteOrder(orderId); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## getInventory + +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + StoreApi apiInstance = new StoreApi(defaultClient); + try { + Map result = apiInstance.getInventory(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Map<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## getOrderById + +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of pet that needs to be fetched + try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## placeOrder + +> Order placeOrder(body) + +Place an order for a pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Order body = new Order(); // Order | order placed for purchasing the pet + try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Tag.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Tag.md new file mode 100644 index 0000000000..f24eba7d22 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Tag.md @@ -0,0 +1,13 @@ + + +# Tag + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/User.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/User.md new file mode 100644 index 0000000000..c4ea94b7fc --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/User.md @@ -0,0 +1,19 @@ + + +# User + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/UserApi.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/UserApi.md new file mode 100644 index 0000000000..ff3815e352 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/UserApi.md @@ -0,0 +1,525 @@ +# UserApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +## createUser + +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + User body = new User(); // User | Created user object + try { + apiInstance.createUser(body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithArrayInput + +> createUsersWithArrayInput(body) + +Creates list of users with given input array + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List body = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithArrayInput(body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithListInput + +> createUsersWithListInput(body) + +Creates list of users with given input array + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List body = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithListInput(body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## deleteUser + +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be deleted + try { + apiInstance.deleteUser(username); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## getUserByName + +> User getUserByName(username) + +Get user by user name + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. + try { + User result = apiInstance.getUserByName(username); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## loginUser + +> String loginUser(username, password) + +Logs user into the system + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The user name for login + String password = "password_example"; // String | The password for login in clear text + try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
| +| **400** | Invalid username/password supplied | - | + + +## logoutUser + +> logoutUser() + +Logs out current logged in user session + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + try { + apiInstance.logoutUser(); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## updateUser + +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | name that need to be updated + User body = new User(); // User | Updated user object + try { + apiInstance.updateUser(username, body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be updated | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/git_push.sh b/spring-swagger-codegen/spring-openapi-generator-api-client/git_push.sh new file mode 100644 index 0000000000..ced3be2b0c --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradle.properties b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle.properties new file mode 100644 index 0000000000..05644f0754 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.jar b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..cc4fdc293d Binary files /dev/null and b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.jar differ diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.properties b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..94920145f3 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew new file mode 100644 index 0000000000..2fe81a7d95 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed 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 +# +# https://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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +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 +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew.bat b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew.bat new file mode 100644 index 0000000000..9618d8d960 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml new file mode 100644 index 0000000000..cc70a9f654 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml @@ -0,0 +1,274 @@ + + 4.0.0 + com.baeldung + spring-openapi-generator-api-client + jar + spring-openapi-generator-api-client + 0.0.1-SNAPSHOT + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + + org.springframework + spring-web + ${spring-web-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${jackson-threetenbp-version} + + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.5.22 + 4.3.9.RELEASE + 2.10.1 + 2.10.1 + 0.2.1 + 2.9.10 + 1.0.0 + 4.13 + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/settings.gradle b/spring-swagger-codegen/spring-openapi-generator-api-client/settings.gradle new file mode 100644 index 0000000000..06a087cb49 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "spring-openapi-generator-api-client" \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/AndroidManifest.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..cd581f9f78 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java new file mode 100644 index 0000000000..b7256c81fb --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java @@ -0,0 +1,477 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.model.ModelApiResponse; +import com.baeldung.petstore.client.model.Pet; + +import java.io.File; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.api.PetApi") +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(new ApiClient()); + } + + @Autowired + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + *

405 - Invalid input + * @param body Pet object that needs to be added to the store (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void addPet(Pet body) throws RestClientException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + *

405 - Invalid input + * @param body Pet object that needs to be added to the store (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity addPetWithHttpInfo(Pet body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling addPet"); + } + + String path = apiClient.expandPath("/pet", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json", "application/xml" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Deletes a pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deletePet(Long petId, String apiKey) throws RestClientException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deletePetWithHttpInfo(Long petId, String apiKey) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling deletePet"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = apiClient.expandPath("/pet/{petId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + if (apiKey != null) + headerParams.add("api_key", apiClient.parameterToString(apiKey)); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

200 - successful operation + *

400 - Invalid status value + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public List findPetsByStatus(List status) throws RestClientException { + return findPetsByStatusWithHttpInfo(status).getBody(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

200 - successful operation + *

400 - Invalid status value + * @param status Status values that need to be considered for filter (required) + * @return ResponseEntity<List<Pet>> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> findPetsByStatusWithHttpInfo(List status) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + + String path = apiClient.expandPath("/pet/findByStatus", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "status", status)); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

200 - successful operation + *

400 - Invalid tag value + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + @Deprecated + public List findPetsByTags(List tags) throws RestClientException { + return findPetsByTagsWithHttpInfo(tags).getBody(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

200 - successful operation + *

400 - Invalid tag value + * @param tags Tags to filter by (required) + * @return ResponseEntity<List<Pet>> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + @Deprecated + public ResponseEntity> findPetsByTagsWithHttpInfo(List tags) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + + String path = apiClient.expandPath("/pet/findByTags", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "tags", tags)); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Find pet by ID + * Returns a single pet + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId ID of pet to return (required) + * @return Pet + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Pet getPetById(Long petId) throws RestClientException { + return getPetByIdWithHttpInfo(petId).getBody(); + } + + /** + * Find pet by ID + * Returns a single pet + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId ID of pet to return (required) + * @return ResponseEntity<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getPetByIdWithHttpInfo(Long petId) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling getPetById"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = apiClient.expandPath("/pet/{petId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Update an existing pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + *

405 - Validation exception + * @param body Pet object that needs to be added to the store (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updatePet(Pet body) throws RestClientException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + *

405 - Validation exception + * @param body Pet object that needs to be added to the store (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updatePetWithHttpInfo(Pet body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updatePet"); + } + + String path = apiClient.expandPath("/pet", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json", "application/xml" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Updates a pet in the store with form data + * + *

405 - Invalid input + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + *

405 - Invalid input + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = apiClient.expandPath("/pet/{petId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + if (name != null) + formParams.add("name", name); + if (status != null) + formParams.add("status", status); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * uploads an image + * + *

200 - successful operation + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { + return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); + } + + /** + * uploads an image + * + *

200 - successful operation + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ResponseEntity<ModelApiResponse> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling uploadFile"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = apiClient.expandPath("/pet/{petId}/uploadImage", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + if (additionalMetadata != null) + formParams.add("additionalMetadata", additionalMetadata); + if (file != null) + formParams.add("file", new FileSystemResource(file)); + + final String[] accepts = { + "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "multipart/form-data" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/StoreApi.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/StoreApi.java new file mode 100644 index 0000000000..792617bc28 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/StoreApi.java @@ -0,0 +1,240 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.model.Order; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.api.StoreApi") +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(new ApiClient()); + } + + @Autowired + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of the order that needs to be deleted (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteOrder(Long orderId) throws RestClientException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of the order that needs to be deleted (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteOrderWithHttpInfo(Long orderId) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("orderId", orderId); + String path = apiClient.expandPath("/store/order/{orderId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

200 - successful operation + * @return Map<String, Integer> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Map getInventory() throws RestClientException { + return getInventoryWithHttpInfo().getBody(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

200 - successful operation + * @return ResponseEntity<Map<String, Integer>> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> getInventoryWithHttpInfo() throws RestClientException { + Object postBody = null; + + String path = apiClient.expandPath("/store/inventory", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key" }; + + ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Order getOrderById(Long orderId) throws RestClientException { + return getOrderByIdWithHttpInfo(orderId).getBody(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of pet that needs to be fetched (required) + * @return ResponseEntity<Order> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getOrderByIdWithHttpInfo(Long orderId) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("orderId", orderId); + String path = apiClient.expandPath("/store/order/{orderId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Place an order for a pet + * + *

200 - successful operation + *

400 - Invalid Order + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Order placeOrder(Order body) throws RestClientException { + return placeOrderWithHttpInfo(body).getBody(); + } + + /** + * Place an order for a pet + * + *

200 - successful operation + *

400 - Invalid Order + * @param body order placed for purchasing the pet (required) + * @return ResponseEntity<Order> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity placeOrderWithHttpInfo(Order body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling placeOrder"); + } + + String path = apiClient.expandPath("/store/order", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java new file mode 100644 index 0000000000..c7cb0b803d --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java @@ -0,0 +1,441 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.model.User; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.api.UserApi") +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(new ApiClient()); + } + + @Autowired + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + *

0 - successful operation + * @param body Created user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUser(User body) throws RestClientException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + *

0 - successful operation + * @param body Created user object (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createUserWithHttpInfo(User body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUser"); + } + + String path = apiClient.expandPath("/user", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUsersWithArrayInput(List body) throws RestClientException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createUsersWithArrayInputWithHttpInfo(List body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + String path = apiClient.expandPath("/user/createWithArray", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUsersWithListInput(List body) throws RestClientException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createUsersWithListInputWithHttpInfo(List body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + String path = apiClient.expandPath("/user/createWithList", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Delete user + * This can only be done by the logged in user. + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be deleted (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteUser(String username) throws RestClientException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be deleted (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteUserWithHttpInfo(String username) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling deleteUser"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = apiClient.expandPath("/user/{username}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Get user by user name + * + *

200 - successful operation + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public User getUserByName(String username) throws RestClientException { + return getUserByNameWithHttpInfo(username).getBody(); + } + + /** + * Get user by user name + * + *

200 - successful operation + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ResponseEntity<User> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserByNameWithHttpInfo(String username) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling getUserByName"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = apiClient.expandPath("/user/{username}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Logs user into the system + * + *

200 - successful operation + *

400 - Invalid username/password supplied + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String loginUser(String username, String password) throws RestClientException { + return loginUserWithHttpInfo(username, password).getBody(); + } + + /** + * Logs user into the system + * + *

200 - successful operation + *

400 - Invalid username/password supplied + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity loginUserWithHttpInfo(String username, String password) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'password' when calling loginUser"); + } + + String path = apiClient.expandPath("/user/login", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Logs out current logged in user session + * + *

0 - successful operation + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void logoutUser() throws RestClientException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + *

0 - successful operation + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity logoutUserWithHttpInfo() throws RestClientException { + Object postBody = null; + + String path = apiClient.expandPath("/user/logout", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Updated user + * This can only be done by the logged in user. + *

400 - Invalid user supplied + *

404 - User not found + * @param username name that need to be updated (required) + * @param body Updated user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updateUser(String username, User body) throws RestClientException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + *

400 - Invalid user supplied + *

404 - User not found + * @param username name that need to be updated (required) + * @param body Updated user object (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateUserWithHttpInfo(String username, User body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = apiClient.expandPath("/user/{username}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java new file mode 100644 index 0000000000..5a10828c47 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java @@ -0,0 +1,750 @@ +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; + +import com.baeldung.petstore.client.invoker.auth.ApiKeyAuth; +import com.baeldung.petstore.client.invoker.auth.Authentication; +import com.baeldung.petstore.client.invoker.auth.HttpBasicAuth; +import com.baeldung.petstore.client.invoker.auth.HttpBearerAuth; +import com.baeldung.petstore.client.invoker.auth.OAuth; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TimeZone; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openapitools.jackson.nullable.JsonNullableModule; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpRequest; +import org.springframework.http.InvalidMediaTypeException; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.RequestEntity.BodyBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; +import org.threeten.bp.*; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.invoker.ApiClient") +public class ApiClient { + public enum CollectionFormat { + CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null); + + private final String separator; + private CollectionFormat(String separator) { + this.separator = separator; + } + + private String collectionToString(Collection collection) { + return StringUtils.collectionToDelimitedString(collection, separator); + } + } + + private boolean debugging = false; + + private HttpHeaders defaultHeaders = new HttpHeaders(); + private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + + private String basePath = "https://petstore.swagger.io/v2"; + + private RestTemplate restTemplate; + + private Map authentications; + + private DateFormat dateFormat; + + public ApiClient() { + this.restTemplate = buildRestTemplate(); + init(); + } + + @Autowired + public ApiClient(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + init(); + } + + protected void init() { + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new RFC3339DateFormat(); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-SDK"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get the current base path + * @return String the base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set the base path, which should include the host + * @param basePath the base path + * @return ApiClient this client + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * @return Map the currently configured authentication types + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set token for HTTP bearer authentication. + * @param bearerToken the token + */ + public void setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * @param username the username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * @param password the password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * @param apiKey the API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix the API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken the access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent the user agent string + * @return ApiClient this client + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param name The header's name + * @param value The header's value + * @return ApiClient this client + */ + public ApiClient addDefaultHeader(String name, String value) { + if (defaultHeaders.containsKey(name)) { + defaultHeaders.remove(name); + } + defaultHeaders.add(name, value); + return this; + } + + /** + * Add a default cookie. + * + * @param name The cookie's name + * @param value The cookie's value + * @return ApiClient this client + */ + public ApiClient addDefaultCookie(String name, String value) { + if (defaultCookies.containsKey(name)) { + defaultCookies.remove(name); + } + defaultCookies.add(name, value); + return this; + } + + public void setDebugging(boolean debugging) { + List currentInterceptors = this.restTemplate.getInterceptors(); + if(debugging) { + if (currentInterceptors == null) { + currentInterceptors = new ArrayList(); + } + ClientHttpRequestInterceptor interceptor = new ApiClientHttpRequestInterceptor(); + currentInterceptors.add(interceptor); + this.restTemplate.setInterceptors(currentInterceptors); + } else { + if (currentInterceptors != null && !currentInterceptors.isEmpty()) { + Iterator iter = currentInterceptors.iterator(); + while (iter.hasNext()) { + ClientHttpRequestInterceptor interceptor = iter.next(); + if (interceptor instanceof ApiClientHttpRequestInterceptor) { + iter.remove(); + } + } + this.restTemplate.setInterceptors(currentInterceptors); + } + } + this.debugging = debugging; + } + + /** + * Check that whether debugging is enabled for this API client. + * @return boolean true if this client is enabled for debugging, false otherwise + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Get the date format used to parse/format date parameters. + * @return DateFormat format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + for(HttpMessageConverter converter:restTemplate.getMessageConverters()){ + if(converter instanceof AbstractJackson2HttpMessageConverter){ + ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper(); + mapper.setDateFormat(dateFormat); + } + } + return this; + } + + /** + * Parse the given string into Date object. + * @param str the string to parse + * @return the Date parsed from the string + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + * @param date the date to format + * @return the formatted date as string + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * @param param the object to convert + * @return String the parameter represented as a String + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate( (Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection) param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param values The values of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(CollectionFormat collectionFormat, Collection values) { + // create the value based on the collection format + if (CollectionFormat.MULTI.equals(collectionFormat)) { + // not valid for path params + return parameterToString(values); + } + + // collectionFormat is assumed to be "csv" by default + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + return collectionFormat.collectionToString(values); + } + + /** + * Converts a parameter to a {@link MultiValueMap} for use in REST requests + * @param collectionFormat The format to convert to + * @param name The name of the parameter + * @param value The parameter's value + * @return a Map containing the String value(s) of the input parameter + */ + public MultiValueMap parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) { + final MultiValueMap params = new LinkedMultiValueMap(); + + if (name == null || name.isEmpty() || value == null) { + return params; + } + + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(name, parameterToString(value)); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + if (collectionFormat.equals(CollectionFormat.MULTI)) { + for (Object item : valueCollection) { + params.add(name, parameterToString(item)); + } + return params; + } + + List values = new ArrayList(); + for(Object o : valueCollection) { + values.add(parameterToString(o)); + } + params.add(name, collectionFormat.collectionToString(values)); + + return params; + } + + /** + * Check if the given {@code String} is a JSON MIME. + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(String mediaType) { + // "* / *" is default to JSON + if ("*/*".equals(mediaType)) { + return true; + } + + try { + return isJsonMime(MediaType.parseMediaType(mediaType)); + } catch (InvalidMediaTypeException e) { + } + return false; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(MediaType mediaType) { + return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return List The list of MediaTypes to use for the Accept header + */ + public List selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + MediaType mediaType = MediaType.parseMediaType(accept); + if (isJsonMime(mediaType)) { + return Collections.singletonList(mediaType); + } + } + return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts)); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return MediaType The Content-Type header to use. If the given array is empty, JSON will be used. + */ + public MediaType selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return MediaType.APPLICATION_JSON; + } + for (String contentType : contentTypes) { + MediaType mediaType = MediaType.parseMediaType(contentType); + if (isJsonMime(mediaType)) { + return mediaType; + } + } + return MediaType.parseMediaType(contentTypes[0]); + } + + /** + * Select the body to use for the request + * @param obj the body object + * @param formParams the form parameters + * @param contentType the content type of the request + * @return Object the selected body + */ + protected Object selectBody(Object obj, MultiValueMap formParams, MediaType contentType) { + boolean isForm = MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType); + return isForm ? formParams : obj; + } + + /** + * Expand path template with variables + * @param pathTemplate path template with placeholders + * @param variables variables to replace + * @return path with placeholders replaced by variables + */ + public String expandPath(String pathTemplate, Map variables) { + return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString(); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param the return type to use + * @param path The sub-path of the HTTP URL + * @param method The request method + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return ResponseEntity<T> The response of the chosen type + */ + public ResponseEntity invokeAPI(String path, HttpMethod method, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap cookieParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames, ParameterizedTypeReference returnType) throws RestClientException { + updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); + + final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path); + if (queryParams != null) { + //encode the query parameters in case they contain unsafe characters + for (List values : queryParams.values()) { + if (values != null) { + for (int i = 0; i < values.size(); i++) { + try { + values.set(i, URLEncoder.encode(values.get(i), "utf8")); + } catch (UnsupportedEncodingException e) { + + } + } + } + } + builder.queryParams(queryParams); + } + + URI uri; + try { + uri = new URI(builder.build().toUriString()); + } catch(URISyntaxException ex) { + throw new RestClientException("Could not build URL: " + builder.toUriString(), ex); + } + + final BodyBuilder requestBuilder = RequestEntity.method(method, uri); + if(accept != null) { + requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); + } + if(contentType != null) { + requestBuilder.contentType(contentType); + } + + addHeadersToRequest(headerParams, requestBuilder); + addHeadersToRequest(defaultHeaders, requestBuilder); + addCookiesToRequest(cookieParams, requestBuilder); + addCookiesToRequest(defaultCookies, requestBuilder); + + RequestEntity requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); + + ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + return responseEntity; + } else { + // The error handler built into the RestTemplate should handle 400 and 500 series errors. + throw new RestClientException("API returned " + responseEntity.getStatusCode() + " and it wasn't handled by the RestTemplate error handler"); + } + } + + /** + * Add headers to the request that is being built + * @param headers The headers to add + * @param requestBuilder The current request + */ + protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) { + for (Entry> entry : headers.entrySet()) { + List values = entry.getValue(); + for(String value : values) { + if (value != null) { + requestBuilder.header(entry.getKey(), value); + } + } + } + } + + /** + * Add cookies to the request that is being built + * @param cookies The cookies to add + * @param requestBuilder The current request + */ + protected void addCookiesToRequest(MultiValueMap cookies, BodyBuilder requestBuilder) { + if (!cookies.isEmpty()) { + requestBuilder.header("Cookie", buildCookieHeader(cookies)); + } + } + + /** + * Build cookie header. Keeps a single value per cookie (as per + * RFC6265 section 5.3). + * + * @param cookies map all cookies + * @return header string for cookies. + */ + private String buildCookieHeader(MultiValueMap cookies) { + final StringBuilder cookieValue = new StringBuilder(); + String delimiter = ""; + for (final Map.Entry> entry : cookies.entrySet()) { + final String value = entry.getValue().get(entry.getValue().size() - 1); + cookieValue.append(String.format("%s%s=%s", delimiter, entry.getKey(), value)); + delimiter = "; "; + } + return cookieValue.toString(); + } + + /** + * Build the RestTemplate used to make HTTP requests. + * @return RestTemplate + */ + protected RestTemplate buildRestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + for(HttpMessageConverter converter:restTemplate.getMessageConverters()){ + if(converter instanceof AbstractJackson2HttpMessageConverter){ + ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper(); + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + mapper.registerModule(module); + mapper.registerModule(new JsonNullableModule()); + } + } + // This allows us to read the response more than once - Necessary for debugging. + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory())); + return restTemplate; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams The query parameters + * @param headerParams The header parameters + */ + private void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RestClientException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams); + } + } + + private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + logRequest(request, body); + ClientHttpResponse response = execution.execute(request, body); + logResponse(response); + return response; + } + + private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException { + log.info("URI: " + request.getURI()); + log.info("HTTP Method: " + request.getMethod()); + log.info("HTTP Headers: " + headersToString(request.getHeaders())); + log.info("Request Body: " + new String(body, StandardCharsets.UTF_8)); + } + + private void logResponse(ClientHttpResponse response) throws IOException { + log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("Status Text: " + response.getStatusText()); + log.info("HTTP Headers: " + headersToString(response.getHeaders())); + log.info("Response Body: " + bodyToString(response.getBody())); + } + + private String headersToString(HttpHeaders headers) { + StringBuilder builder = new StringBuilder(); + for(Entry> entry : headers.entrySet()) { + builder.append(entry.getKey()).append("=["); + for(String value : entry.getValue()) { + builder.append(value).append(","); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + builder.append("],"); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + return builder.toString(); + } + + private String bodyToString(InputStream body) throws IOException { + StringBuilder builder = new StringBuilder(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); + String line = bufferedReader.readLine(); + while (line != null) { + builder.append(line).append(System.lineSeparator()); + line = bufferedReader.readLine(); + } + bufferedReader.close(); + return builder.toString(); + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/CustomInstantDeserializer.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/CustomInstantDeserializer.java new file mode 100644 index 0000000000..6957818fb4 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/CustomInstantDeserializer.java @@ -0,0 +1,233 @@ +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonTokenId; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils; +import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase; +import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction; +import com.fasterxml.jackson.datatype.threetenbp.function.Function; + +import java.io.IOException; +import java.math.BigDecimal; + +import org.threeten.bp.DateTimeException; +import org.threeten.bp.DateTimeUtils; +import org.threeten.bp.Instant; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.ZonedDateTime; +import org.threeten.bp.format.DateTimeFormatter; +import org.threeten.bp.temporal.Temporal; +import org.threeten.bp.temporal.TemporalAccessor; + +/** + * Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s. + * Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format. + * + * @author Nick Williams + */ +public class CustomInstantDeserializer + extends ThreeTenDateTimeDeserializerBase { + private static final long serialVersionUID = 1L; + + public static final CustomInstantDeserializer INSTANT = new CustomInstantDeserializer( + Instant.class, DateTimeFormatter.ISO_INSTANT, + new Function() { + @Override + public Instant apply(TemporalAccessor temporalAccessor) { + return Instant.from(temporalAccessor); + } + }, + new Function() { + @Override + public Instant apply(FromIntegerArguments a) { + return Instant.ofEpochMilli(a.value); + } + }, + new Function() { + @Override + public Instant apply(FromDecimalArguments a) { + return Instant.ofEpochSecond(a.integer, a.fraction); + } + }, + null + ); + + public static final CustomInstantDeserializer OFFSET_DATE_TIME = new CustomInstantDeserializer( + OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, + new Function() { + @Override + public OffsetDateTime apply(TemporalAccessor temporalAccessor) { + return OffsetDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromIntegerArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromDecimalArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public OffsetDateTime apply(OffsetDateTime d, ZoneId z) { + return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())); + } + } + ); + + public static final CustomInstantDeserializer ZONED_DATE_TIME = new CustomInstantDeserializer( + ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, + new Function() { + @Override + public ZonedDateTime apply(TemporalAccessor temporalAccessor) { + return ZonedDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromIntegerArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromDecimalArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) { + return zonedDateTime.withZoneSameInstant(zoneId); + } + } + ); + + protected final Function fromMilliseconds; + + protected final Function fromNanoseconds; + + protected final Function parsedToValue; + + protected final BiFunction adjust; + + protected CustomInstantDeserializer(Class supportedType, + DateTimeFormatter parser, + Function parsedToValue, + Function fromMilliseconds, + Function fromNanoseconds, + BiFunction adjust) { + super(supportedType, parser); + this.parsedToValue = parsedToValue; + this.fromMilliseconds = fromMilliseconds; + this.fromNanoseconds = fromNanoseconds; + this.adjust = adjust == null ? new BiFunction() { + @Override + public T apply(T t, ZoneId zoneId) { + return t; + } + } : adjust; + } + + @SuppressWarnings("unchecked") + protected CustomInstantDeserializer(CustomInstantDeserializer base, DateTimeFormatter f) { + super((Class) base.handledType(), f); + parsedToValue = base.parsedToValue; + fromMilliseconds = base.fromMilliseconds; + fromNanoseconds = base.fromNanoseconds; + adjust = base.adjust; + } + + @Override + protected JsonDeserializer withDateFormat(DateTimeFormatter dtf) { + if (dtf == _formatter) { + return this; + } + return new CustomInstantDeserializer(this, dtf); + } + + @Override + public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { + //NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only + //string values have to be adjusted to the configured TZ. + switch (parser.getCurrentTokenId()) { + case JsonTokenId.ID_NUMBER_FLOAT: { + BigDecimal value = parser.getDecimalValue(); + long seconds = value.longValue(); + int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); + return fromNanoseconds.apply(new FromDecimalArguments( + seconds, nanoseconds, getZone(context))); + } + + case JsonTokenId.ID_NUMBER_INT: { + long timestamp = parser.getLongValue(); + if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { + return this.fromNanoseconds.apply(new FromDecimalArguments( + timestamp, 0, this.getZone(context) + )); + } + return this.fromMilliseconds.apply(new FromIntegerArguments( + timestamp, this.getZone(context) + )); + } + + case JsonTokenId.ID_STRING: { + String string = parser.getText().trim(); + if (string.length() == 0) { + return null; + } + if (string.endsWith("+0000")) { + string = string.substring(0, string.length() - 5) + "Z"; + } + T value; + try { + TemporalAccessor acc = _formatter.parse(string); + value = parsedToValue.apply(acc); + if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { + return adjust.apply(value, this.getZone(context)); + } + } catch (DateTimeException e) { + throw _peelDTE(e); + } + return value; + } + } + throw context.mappingException("Expected type float, integer, or string."); + } + + private ZoneId getZone(DeserializationContext context) { + // Instants are always in UTC, so don't waste compute cycles + return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone()); + } + + private static class FromIntegerArguments { + public final long value; + public final ZoneId zoneId; + + private FromIntegerArguments(long value, ZoneId zoneId) { + this.value = value; + this.zoneId = zoneId; + } + } + + private static class FromDecimalArguments { + public final long integer; + public final int fraction; + public final ZoneId zoneId; + + private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) { + this.integer = integer; + this.fraction = fraction; + this.zoneId = zoneId; + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java new file mode 100644 index 0000000000..46083815a6 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java new file mode 100644 index 0000000000..b494b52050 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java @@ -0,0 +1,62 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location.equals("query")) { + queryParams.add(paramName, value); + } else if (location.equals("header")) { + headerParams.add(paramName, value); + } else if (location.equals("cookie")) { + cookieParams.add(paramName, value); + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java new file mode 100644 index 0000000000..8d55110d1b --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java @@ -0,0 +1,14 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +public interface Authentication { + /** + * Apply authentication settings to header and / or query parameters. + * @param queryParams The query parameters for the request + * @param headerParams The header parameters for the request + * @param cookieParams The cookie parameters for the request + */ + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams); +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java new file mode 100644 index 0000000000..4c1dad6e7c --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java @@ -0,0 +1,38 @@ +package com.baeldung.petstore.client.invoker.auth; + +import java.nio.charset.StandardCharsets; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.Base64Utils; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBearerAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBearerAuth.java new file mode 100644 index 0000000000..46ab6cabce --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBearerAuth.java @@ -0,0 +1,34 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + public String getBearerToken() { + return bearerToken; + } + + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (bearerToken == null) { + return; + } + headerParams.add(HttpHeaders.AUTHORIZATION, (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java new file mode 100644 index 0000000000..b9e0f986ac --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java @@ -0,0 +1,24 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (accessToken != null) { + headerParams.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java new file mode 100644 index 0000000000..235e0b7f55 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package com.baeldung.petstore.client.invoker.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java new file mode 100644 index 0000000000..2bb7ebe9f6 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java @@ -0,0 +1,131 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Category + */ +@JsonPropertyOrder({ + Category.JSON_PROPERTY_ID, + Category.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Category { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + + public Category id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Category name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java new file mode 100644 index 0000000000..107e08b8b9 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java @@ -0,0 +1,162 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * ModelApiResponse + */ +@JsonPropertyOrder({ + ModelApiResponse.JSON_PROPERTY_CODE, + ModelApiResponse.JSON_PROPERTY_TYPE, + ModelApiResponse.JSON_PROPERTY_MESSAGE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class ModelApiResponse { + public static final String JSON_PROPERTY_CODE = "code"; + private Integer code; + + public static final String JSON_PROPERTY_TYPE = "type"; + private String type; + + public static final String JSON_PROPERTY_MESSAGE = "message"; + private String message; + + + public ModelApiResponse code(Integer code) { + + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_CODE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Integer getCode() { + return code; + } + + + public void setCode(Integer code) { + this.code = code; + } + + + public ModelApiResponse type(String type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getType() { + return type; + } + + + public void setType(String type) { + this.type = type; + } + + + public ModelApiResponse message(String message) { + + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_MESSAGE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getMessage() { + return message; + } + + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java new file mode 100644 index 0000000000..b041595785 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java @@ -0,0 +1,296 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.Objects; + +import org.threeten.bp.OffsetDateTime; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Order + */ +@JsonPropertyOrder({ + Order.JSON_PROPERTY_ID, + Order.JSON_PROPERTY_PET_ID, + Order.JSON_PROPERTY_QUANTITY, + Order.JSON_PROPERTY_SHIP_DATE, + Order.JSON_PROPERTY_STATUS, + Order.JSON_PROPERTY_COMPLETE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Order { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_PET_ID = "petId"; + private Long petId; + + public static final String JSON_PROPERTY_QUANTITY = "quantity"; + private Integer quantity; + + public static final String JSON_PROPERTY_SHIP_DATE = "shipDate"; + private OffsetDateTime shipDate; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_STATUS = "status"; + private StatusEnum status; + + public static final String JSON_PROPERTY_COMPLETE = "complete"; + private Boolean complete; + + + public Order id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Order petId(Long petId) { + + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PET_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getPetId() { + return petId; + } + + + public void setPetId(Long petId) { + this.petId = petId; + } + + + public Order quantity(Integer quantity) { + + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_QUANTITY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Integer getQuantity() { + return quantity; + } + + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + public Order shipDate(OffsetDateTime shipDate) { + + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_SHIP_DATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public OffsetDateTime getShipDate() { + return shipDate; + } + + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + + public Order status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "Order Status") + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public StatusEnum getStatus() { + return status; + } + + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + public Order complete(Boolean complete) { + + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_COMPLETE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Boolean getComplete() { + return complete; + } + + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java new file mode 100644 index 0000000000..3709cd5371 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java @@ -0,0 +1,310 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.baeldung.petstore.client.model.Category; +import com.baeldung.petstore.client.model.Tag; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Pet + */ +@JsonPropertyOrder({ + Pet.JSON_PROPERTY_ID, + Pet.JSON_PROPERTY_CATEGORY, + Pet.JSON_PROPERTY_NAME, + Pet.JSON_PROPERTY_PHOTO_URLS, + Pet.JSON_PROPERTY_TAGS, + Pet.JSON_PROPERTY_STATUS +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Pet { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_CATEGORY = "category"; + private Category category; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public static final String JSON_PROPERTY_PHOTO_URLS = "photoUrls"; + private List photoUrls = new ArrayList<>(); + + public static final String JSON_PROPERTY_TAGS = "tags"; + private List tags = null; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_STATUS = "status"; + private StatusEnum status; + + + public Pet id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Pet category(Category category) { + + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_CATEGORY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Category getCategory() { + return category; + } + + + public void setCategory(Category category) { + this.category = category; + } + + + public Pet name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + public Pet photoUrls(List photoUrls) { + + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty(JSON_PROPERTY_PHOTO_URLS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getPhotoUrls() { + return photoUrls; + } + + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + public Pet tags(List tags) { + + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_TAGS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getTags() { + return tags; + } + + + public void setTags(List tags) { + this.tags = tags; + } + + + public Pet status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "pet status in the store") + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public StatusEnum getStatus() { + return status; + } + + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java new file mode 100644 index 0000000000..7ee50c69b0 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java @@ -0,0 +1,131 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Tag + */ +@JsonPropertyOrder({ + Tag.JSON_PROPERTY_ID, + Tag.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Tag { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + + public Tag id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Tag name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/User.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/User.java new file mode 100644 index 0000000000..ba12953ed3 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/User.java @@ -0,0 +1,317 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * User + */ +@JsonPropertyOrder({ + User.JSON_PROPERTY_ID, + User.JSON_PROPERTY_USERNAME, + User.JSON_PROPERTY_FIRST_NAME, + User.JSON_PROPERTY_LAST_NAME, + User.JSON_PROPERTY_EMAIL, + User.JSON_PROPERTY_PASSWORD, + User.JSON_PROPERTY_PHONE, + User.JSON_PROPERTY_USER_STATUS +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class User { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_USERNAME = "username"; + private String username; + + public static final String JSON_PROPERTY_FIRST_NAME = "firstName"; + private String firstName; + + public static final String JSON_PROPERTY_LAST_NAME = "lastName"; + private String lastName; + + public static final String JSON_PROPERTY_EMAIL = "email"; + private String email; + + public static final String JSON_PROPERTY_PASSWORD = "password"; + private String password; + + public static final String JSON_PROPERTY_PHONE = "phone"; + private String phone; + + public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; + private Integer userStatus; + + + public User id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public User username(String username) { + + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_USERNAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getUsername() { + return username; + } + + + public void setUsername(String username) { + this.username = username; + } + + + public User firstName(String firstName) { + + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_FIRST_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getFirstName() { + return firstName; + } + + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + public User lastName(String lastName) { + + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_LAST_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getLastName() { + return lastName; + } + + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + public User email(String email) { + + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_EMAIL) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getEmail() { + return email; + } + + + public void setEmail(String email) { + this.email = email; + } + + + public User password(String password) { + + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PASSWORD) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getPassword() { + return password; + } + + + public void setPassword(String password) { + this.password = password; + } + + + public User phone(String phone) { + + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PHONE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getPhone() { + return phone; + } + + + public void setPhone(String phone) { + this.phone = phone; + } + + + public User userStatus(Integer userStatus) { + + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "User Status") + @JsonProperty(JSON_PROPERTY_USER_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Integer getUserStatus() { + return userStatus; + } + + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java new file mode 100644 index 0000000000..8854e8e3d4 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java @@ -0,0 +1,167 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.ModelApiResponse; +import com.baeldung.petstore.client.model.Pet; + +import java.io.File; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * API tests for PetApi + */ +@Ignore +public class PetApiTest { + + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() { + Pet body = null; + api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + api.deletePet(petId, apiKey); + + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() { + List status = null; + List response = api.findPetsByStatus(status); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() { + Long petId = null; + Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() { + Pet body = null; + api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + File file = null; + ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java new file mode 100644 index 0000000000..444429bd42 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java @@ -0,0 +1,95 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.Order; + +import java.util.Map; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * API tests for StoreApi + */ +@Ignore +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() { + Long orderId = null; + api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() { + Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() { + Order body = null; + Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java new file mode 100644 index 0000000000..c73b47ecb2 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java @@ -0,0 +1,161 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.User; + +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * API tests for UserApi + */ +@Ignore +public class UserApiTest { + + private final UserApi api = new UserApi(); + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() { + User body = null; + api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() { + List body = null; + api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() { + List body = null; + api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() { + String username = null; + api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() { + String username = null; + User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() { + api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() { + String username = null; + User body = null; + api.updateUser(username, body); + + // TODO: test validations + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/CategoryTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/CategoryTest.java new file mode 100644 index 0000000000..7be1b285c3 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/CategoryTest.java @@ -0,0 +1,49 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/ModelApiResponseTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/ModelApiResponseTest.java new file mode 100644 index 0000000000..55f742f862 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/ModelApiResponseTest.java @@ -0,0 +1,57 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/OrderTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/OrderTest.java new file mode 100644 index 0000000000..edbacea028 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/OrderTest.java @@ -0,0 +1,81 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/PetTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/PetTest.java new file mode 100644 index 0000000000..78951acaba --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/PetTest.java @@ -0,0 +1,81 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/TagTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/TagTest.java new file mode 100644 index 0000000000..16efed2570 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/TagTest.java @@ -0,0 +1,49 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/UserTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/UserTest.java new file mode 100644 index 0000000000..d84cfb21ca --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/UserTest.java @@ -0,0 +1,97 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java rename to spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/com/baeldung/SpringContextTest.java index 79b2b7fa88..54949598aa 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-threads/README.md b/spring-threads/README.md new file mode 100644 index 0000000000..c3762cd86f --- /dev/null +++ b/spring-threads/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize](https://www.baeldung.com/java-threadpooltaskexecutor-core-vs-max-poolsize) diff --git a/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java b/spring-vertx/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-vertx/src/test/java/org/baeldung/SpringContextTest.java rename to spring-vertx/src/test/java/com/baeldung/SpringContextTest.java index 4ce94ec16a..386d83b47b 100644 --- a/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-vertx/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index 7cef9ee8f6..5f307c2f0b 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -8,8 +8,6 @@ - [Mockito When/Then Cookbook](https://www.baeldung.com/mockito-behavior) - [Getting Started with Mockito @Mock, @Spy, @Captor and @InjectMocks](https://www.baeldung.com/mockito-annotations) - [Mockito’s Mock Methods](https://www.baeldung.com/mockito-mock-methods) -- [Introduction to PowerMock](https://www.baeldung.com/intro-to-powermock) -- [Mocking of Private Methods Using PowerMock](https://www.baeldung.com/powermock-private-method) - [Mocking Exception Throwing using Mockito](https://www.baeldung.com/mockito-exceptions) - [Mocking Void Methods with Mockito](https://www.baeldung.com/mockito-void-methods) - [Mock Final Classes and Methods with Mockito](https://www.baeldung.com/mockito-final) diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index aae3981c66..ea5ef4c322 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -44,19 +44,6 @@ - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - org.springframework.boot spring-boot-starter diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index f4a8368581..951909b36f 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -40,6 +40,7 @@ xmlunit-2 junit-4 testing-libraries + powermock diff --git a/testing-modules/powermock/README.md b/testing-modules/powermock/README.md new file mode 100644 index 0000000000..df9fb0088c --- /dev/null +++ b/testing-modules/powermock/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Introduction to PowerMock](https://www.baeldung.com/intro-to-powermock) +- [Mocking of Private Methods Using PowerMock](https://www.baeldung.com/powermock-private-method) diff --git a/testing-modules/powermock/pom.xml b/testing-modules/powermock/pom.xml new file mode 100644 index 0000000000..21b2e98af0 --- /dev/null +++ b/testing-modules/powermock/pom.xml @@ -0,0 +1,33 @@ + + + + testing-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + powermock + + + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.version} + test + + + + + 2.21.0 + 2.0.2 + + \ No newline at end of file diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java similarity index 98% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java index 4943b0486a..1b2bb99896 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java +++ b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java @@ -68,7 +68,7 @@ public class PowerMockitoUnitTest { when(mock.finalMethod()).thenReturn("I am a final mock method."); returnValue = mock.finalMethod(); - verify(mock,times(3)).finalMethod(); + verify(mock).finalMethod(); assertEquals("I am a final mock method.", returnValue); when(mock, "privateMethod").thenReturn("I am a private mock method.");