From 388f03ae9a1ecc3a81ebd15ad589b16f61611d59 Mon Sep 17 00:00:00 2001 From: Michael Angstadt Date: Tue, 26 May 2020 15:46:28 -0400 Subject: [PATCH 001/132] Use ServiceLoader class to obtain service instance In the "main-app" module, the `HelloInterface` service instance, `HelloModules`, was just being treated like an ordinary class that was exported from the "hello.modules" module. The code was not treating the class as a service class. This is not a good example of how services are used. This commit makes use of the `ServiceLoader` class, which provides access to the `HelloInterface` instance as defined in the "hello.modules" module. This serves as a better example for how services are used. --- .../main.app/com/baeldung/modules/main/MainApp.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-9-jigsaw/src/simple-modules/main.app/com/baeldung/modules/main/MainApp.java b/core-java-modules/core-java-9-jigsaw/src/simple-modules/main.app/com/baeldung/modules/main/MainApp.java index eb32cafa31..270bf66c81 100644 --- a/core-java-modules/core-java-9-jigsaw/src/simple-modules/main.app/com/baeldung/modules/main/MainApp.java +++ b/core-java-modules/core-java-9-jigsaw/src/simple-modules/main.app/com/baeldung/modules/main/MainApp.java @@ -1,12 +1,15 @@ package com.baeldung.modules.main; +import com.baeldung.modules.hello.HelloInterface; import com.baeldung.modules.hello.HelloModules; +import java.util.ServiceLoader; public class MainApp { public static void main(String[] args) { HelloModules.doSomething(); - - HelloModules module = new HelloModules(); - module.sayHello(); + + Iterable services = ServiceLoader.load(HelloInterface.class); + HelloInterface service = services.iterator().next(); + service.sayHello(); } } From 1c61ba62abf38bd6c3962dc2a4a293baf4523a18 Mon Sep 17 00:00:00 2001 From: joe zhang Date: Fri, 19 Jun 2020 11:06:53 +0800 Subject: [PATCH 002/132] Leasy Zhang/shiwangzhihe@gmail.com --- .../convertlisttomap/ListToMapUnitTest.java | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java b/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java new file mode 100644 index 0000000000..e2340a5a9a --- /dev/null +++ b/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java @@ -0,0 +1,102 @@ +package com.baeldung.convertlisttomap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class ListToMapUnitTest { + + @Test + public void givenAList_whenConvertWithJava8GroupBy_thenReturnMap() { + List strings = Arrays.asList("List", "Map", "Set", "Tree"); + + Map> convertedMap = new HashMap<>(); + + Supplier> listSupplier = () -> { + return new ArrayList<>(); + }; + + Supplier>> mapFactory = () -> { + return new HashMap<>(); + }; + convertedMap = strings.stream() + .collect(Collectors.groupingBy(String::length, mapFactory, Collectors.toCollection(listSupplier))); + + assertEquals(2, convertedMap.size()); + assertTrue(convertedMap.get(3) + .contains("Map")); + } + + @Test + public void givenAList_whenConvertWithJava8Collect_thenReturnMap() { + List strings = Arrays.asList("List", "Map", "Set", "Tree"); + + Map> convertedMap = new HashMap<>(); + + Supplier>> mapFactory = () -> { + return new HashMap<>(); + }; + + Supplier> listSupplier = () -> { + return new ArrayList<>(); + }; + + BiConsumer>, String> accumulator = (response, element) -> { + Integer key = element.length(); + List values = response.getOrDefault(key, listSupplier.get()); + values.add(element); + response.put(key, values); + }; + + BiConsumer>, Map>> combiner = (res1, res2) -> { + res1.putAll(res2); + }; + + convertedMap = strings.stream() + .collect(mapFactory, accumulator, combiner); + + assertEquals(2, convertedMap.size()); + assertTrue(convertedMap.get(3) + .contains("Map")); + } + + @Test + public void givenAList_whenConvertWithCollectorToMap_thenReturnMap() { + List strings = Arrays.asList("List", "Map", "Set", "Tree"); + + Map> convertedMap = new HashMap<>(); + + Supplier>> mapFactory = () -> { + return new HashMap<>(); + }; + + Supplier> listSupplier = () -> { + return new ArrayList<>(); + }; + + convertedMap = strings.stream() + .collect(Collectors.toMap(String::length, (p) -> { + List strs = listSupplier.get(); + strs.add(p); + return strs; + }, (existing, replacement) -> { + existing.addAll(replacement); + return existing; + }, mapFactory)); + + assertEquals(2, convertedMap.size()); + assertTrue(convertedMap.get(3) + .contains("Map")); + } + +} From 672ffdbe9f9fe6de186e38a4a7d28aa6e95378ee Mon Sep 17 00:00:00 2001 From: joe zhang Date: Mon, 29 Jun 2020 22:34:19 +0800 Subject: [PATCH 003/132] update unit test for collectors.toMap method --- .../convertlisttomap/ListToMapUnitTest.java | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java b/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java index e2340a5a9a..5a875a904e 100644 --- a/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java +++ b/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java @@ -9,6 +9,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; +import java.util.function.BinaryOperator; +import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -84,15 +86,23 @@ public class ListToMapUnitTest { return new ArrayList<>(); }; + Function keyMapper = (element) -> { + return element.length(); + }; + + Function> valueMapper = (element) -> { + List collection = listSupplier.get(); + collection.add(element); + return collection; + }; + + BinaryOperator> mergeFunction = (existing, replacement) -> { + existing.addAll(replacement); + return existing; + }; + convertedMap = strings.stream() - .collect(Collectors.toMap(String::length, (p) -> { - List strs = listSupplier.get(); - strs.add(p); - return strs; - }, (existing, replacement) -> { - existing.addAll(replacement); - return existing; - }, mapFactory)); + .collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapFactory)); assertEquals(2, convertedMap.size()); assertTrue(convertedMap.get(3) From 1b7edfdfad9f2eb12e15a808974b8679c40c33db Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Thu, 2 Jul 2020 20:21:57 +0200 Subject: [PATCH 004/132] [BAEL-4074] Accessing Maven properties in Java --- maven-all/maven-2/.gitignore | 2 + maven-all/maven-2/README.md | 6 +++ maven-all/maven-2/pom.xml | 51 +++++++++++++++++++ .../maven/properties/PropertiesReader.java | 41 +++++++++++++++ .../properties/PropertiesReaderUnitTest.java | 27 ++++++++++ 5 files changed, 127 insertions(+) create mode 100644 maven-all/maven-2/.gitignore create mode 100644 maven-all/maven-2/README.md create mode 100644 maven-all/maven-2/pom.xml create mode 100644 maven-all/maven-2/src/main/java/com/baeldung/maven/properties/PropertiesReader.java create mode 100644 maven-all/maven-2/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java diff --git a/maven-all/maven-2/.gitignore b/maven-all/maven-2/.gitignore new file mode 100644 index 0000000000..bae0b0d7ce --- /dev/null +++ b/maven-all/maven-2/.gitignore @@ -0,0 +1,2 @@ +/output-resources +/.idea/ diff --git a/maven-all/maven-2/README.md b/maven-all/maven-2/README.md new file mode 100644 index 0000000000..5878a4f732 --- /dev/null +++ b/maven-all/maven-2/README.md @@ -0,0 +1,6 @@ +## Apache Maven + +This module contains articles about core Apache Maven. Articles about other Maven plugins (such as the Maven WAR Plugin) +have their own dedicated modules. + +### Relevant Articles diff --git a/maven-all/maven-2/pom.xml b/maven-all/maven-2/pom.xml new file mode 100644 index 0000000000..629da573b5 --- /dev/null +++ b/maven-all/maven-2/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + maven-2 + 0.0.1-SNAPSHOT + maven-2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../.. + + + + + junit + junit + 4.13 + + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + generate-resources + + write-project-properties + + + ${project.build.outputDirectory}/properties-from-pom.properties + + + + + + + + + ${project.name} + property-from-pom + + + \ No newline at end of file diff --git a/maven-all/maven-2/src/main/java/com/baeldung/maven/properties/PropertiesReader.java b/maven-all/maven-2/src/main/java/com/baeldung/maven/properties/PropertiesReader.java new file mode 100644 index 0000000000..e7000ec2ce --- /dev/null +++ b/maven-all/maven-2/src/main/java/com/baeldung/maven/properties/PropertiesReader.java @@ -0,0 +1,41 @@ +package com.baeldung.maven.properties; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +/** + * Reads properties from one file. + * + * @author Donato Rimenti + */ +public class PropertiesReader { + + /** + * Properties managed by this reader. + */ + private Properties properties; + + /** + * Reads the property file with the given name. + * + * @param propertyFileName the name of the property file to read + * @throws IOException if the file is not found or there's a problem reading it + */ + public PropertiesReader(String propertyFileName) throws IOException { + InputStream is = getClass().getClassLoader() + .getResourceAsStream(propertyFileName); + this.properties = new Properties(); + this.properties.load(is); + } + + /** + * Gets the property with the given name from the property file. + * @param propertyName the name of the property to read + * @return the property with the given name + */ + public String getProperty(String propertyName) { + return this.properties.getProperty(propertyName); + } + +} \ No newline at end of file diff --git a/maven-all/maven-2/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java b/maven-all/maven-2/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java new file mode 100644 index 0000000000..a1d6e66047 --- /dev/null +++ b/maven-all/maven-2/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.maven.properties; + +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Test for {@link PropertiesReader}. + * + * @author Donato Rimenti + */ +public class PropertiesReaderUnitTest { + + /** + * Reads a property and checks that's the one expected. + * + * @throws IOException if anything goes wrong + */ + @Test + public void givenPomProperties_whenPropertyRead_thenPropertyReturned() throws IOException { + PropertiesReader reader = new PropertiesReader("properties-from-pom.properties"); + String property = reader.getProperty("my.awesome.property"); + Assert.assertEquals("property-from-pom", property); + } + +} \ No newline at end of file From e955c836adb16087392f1f29aa0b6c2d8a7ad5d6 Mon Sep 17 00:00:00 2001 From: Daniel Garrett Date: Mon, 6 Jul 2020 11:07:36 +0100 Subject: [PATCH 005/132] feat: add class to conditionally ignore unit tests --- .../ConditionallyIgnoreTestsUnitTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java diff --git a/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java b/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java new file mode 100644 index 0000000000..af571eb808 --- /dev/null +++ b/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.assume; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assume.assumeThat; +import static org.junit.Assume.assumeTrue; + +import org.junit.Test; + +public class ConditionallyIgnoreTestsUnitTest { + + + @Test + public void whenAssumeThatCodeVersionIsNot1_thenIgnore() { + final int codeVersion = 1; + assumeThat(codeVersion, is(2)); + + assertEquals("hello", "HELLO".toLowerCase()); + } + + @Test + public void whenAssumeTrueOnCondition_thenIgnore() { + final int codeVersion = 1; + assumeTrue(isCodeVersion2(codeVersion)); + + assertEquals("hello", "HELLO".toLowerCase()); + } + + private boolean isCodeVersion2(final int codeVersion) { + return codeVersion == 2; + } +} From 278b5f8efa6d1ba238ba9761079529a12fcf56bc Mon Sep 17 00:00:00 2001 From: Daniel Garrett Date: Mon, 6 Jul 2020 11:15:35 +0100 Subject: [PATCH 006/132] fix: rename test --- .../com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java b/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java index af571eb808..0a95ed4522 100644 --- a/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java +++ b/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java @@ -11,7 +11,7 @@ public class ConditionallyIgnoreTestsUnitTest { @Test - public void whenAssumeThatCodeVersionIsNot1_thenIgnore() { + public void whenAssumeThatCodeVersionIsNot2_thenIgnore() { final int codeVersion = 1; assumeThat(codeVersion, is(2)); From 4f6c33f935dfbbedbc693a76ac65130a1cd7ab8f Mon Sep 17 00:00:00 2001 From: helga_sh Date: Mon, 6 Jul 2020 17:39:18 +0300 Subject: [PATCH 007/132] Top k elements in an array --- .../BruteForceTopKElementsFinder.java | 26 ++++++++++ .../MaxHeapTopKElementsFinder.java | 26 ++++++++++ .../topnelements/TopKElementsFinder.java | 7 +++ .../TreeSetTopKElementsFinder.java | 17 +++++++ .../TopKElementsFinderUnitTest.java | 50 +++++++++++++++++++ 5 files changed, 126 insertions(+) create mode 100644 algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/BruteForceTopKElementsFinder.java create mode 100644 algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/MaxHeapTopKElementsFinder.java create mode 100644 algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TopKElementsFinder.java create mode 100644 algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TreeSetTopKElementsFinder.java create mode 100644 algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/BruteForceTopKElementsFinder.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/BruteForceTopKElementsFinder.java new file mode 100644 index 0000000000..d2a3acce16 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/BruteForceTopKElementsFinder.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.topnelements; + +import java.util.ArrayList; +import java.util.List; + +public class BruteForceTopKElementsFinder implements TopKElementsFinder { + + public List findTopK(List input, int k) { + List array = new ArrayList<>(input); + List topKList = new ArrayList<>(); + + for (int i = 0; i < k; i++) { + int maxIndex = 0; + + for (int j = 1; j < array.size(); j++) { + if (array.get(j) > array.get(maxIndex)) { + maxIndex = j; + } + } + + topKList.add(array.remove(maxIndex)); + } + + return topKList; + } +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/MaxHeapTopKElementsFinder.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/MaxHeapTopKElementsFinder.java new file mode 100644 index 0000000000..e39eb7ccb2 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/MaxHeapTopKElementsFinder.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.topnelements; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.PriorityQueue; + +public class MaxHeapTopKElementsFinder implements TopKElementsFinder { + + public List findTopK(List input, int k) { + PriorityQueue maxHeap = new PriorityQueue<>(); + + input.forEach(number -> { + maxHeap.add(number); + + if (maxHeap.size() > k) { + maxHeap.poll(); + } + }); + + List topKList = new ArrayList<>(maxHeap); + Collections.reverse(topKList); + + return topKList; + } +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TopKElementsFinder.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TopKElementsFinder.java new file mode 100644 index 0000000000..d1bd48efa5 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TopKElementsFinder.java @@ -0,0 +1,7 @@ +package com.baeldung.algorithms.topnelements; + +import java.util.List; + +public interface TopKElementsFinder> { + List findTopK(List input, int k); +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TreeSetTopKElementsFinder.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TreeSetTopKElementsFinder.java new file mode 100644 index 0000000000..c1fc8914d0 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TreeSetTopKElementsFinder.java @@ -0,0 +1,17 @@ +package com.baeldung.algorithms.topnelements; + +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; + +public class TreeSetTopKElementsFinder implements TopKElementsFinder { + + public List findTopK(List input, int k) { + Set sortedSet = new TreeSet<>(Comparator.reverseOrder()); + sortedSet.addAll(input); + + return sortedSet.stream().limit(k).collect(Collectors.toList()); + } +} diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java new file mode 100644 index 0000000000..5c02cefe23 --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.algorithms.topkelements; + +import com.baeldung.algorithms.topnelements.BruteForceTopKElementsFinder; +import com.baeldung.algorithms.topnelements.MaxHeapTopKElementsFinder; +import com.baeldung.algorithms.topnelements.TopKElementsFinder; +import com.baeldung.algorithms.topnelements.TreeSetTopKElementsFinder; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +public class TopKElementsFinderUnitTest { + private final TopKElementsFinder bruteForceFinder = new BruteForceTopKElementsFinder(); + private final TopKElementsFinder maxHeapFinder = new MaxHeapTopKElementsFinder(); + private final TopKElementsFinder treeSetFinder = new TreeSetTopKElementsFinder(); + + private final int k = 4; + private final List distinctIntegers = Arrays.asList(1, 2, 3, 9, 7, 6, 12); + private final List distinctIntegersTopK = Arrays.asList(9, 7, 6, 12); + private final List nonDistinctIntegers = Arrays.asList(1, 2, 3, 3, 9, 9, 7, 6, 12); + private final List nonDistinctIntegersTopK = Arrays.asList(9, 9, 7, 12); + + + @Test + public void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { + assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); + } + + @Test + public void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { + assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); + } + + @Test + public void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() { + assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); + } + + @Test + public void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { + assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK); + } + + @Test + public void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { + assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK); + } +} From 53ffdd9f3d3e5008455ac1d9634610c2b94b494e Mon Sep 17 00:00:00 2001 From: helga_sh Date: Mon, 6 Jul 2020 17:49:10 +0300 Subject: [PATCH 008/132] Rename folder --- .../BruteForceTopKElementsFinder.java | 2 +- .../MaxHeapTopKElementsFinder.java | 2 +- .../{topnelements => topkelements}/TopKElementsFinder.java | 2 +- .../TreeSetTopKElementsFinder.java | 2 +- .../algorithms/topkelements/TopKElementsFinderUnitTest.java | 4 ---- 5 files changed, 4 insertions(+), 8 deletions(-) rename algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/{topnelements => topkelements}/BruteForceTopKElementsFinder.java (93%) rename algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/{topnelements => topkelements}/MaxHeapTopKElementsFinder.java (93%) rename algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/{topnelements => topkelements}/TopKElementsFinder.java (74%) rename algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/{topnelements => topkelements}/TreeSetTopKElementsFinder.java (91%) diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/BruteForceTopKElementsFinder.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/BruteForceTopKElementsFinder.java similarity index 93% rename from algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/BruteForceTopKElementsFinder.java rename to algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/BruteForceTopKElementsFinder.java index d2a3acce16..c0962c7079 100644 --- a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/BruteForceTopKElementsFinder.java +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/BruteForceTopKElementsFinder.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.topnelements; +package com.baeldung.algorithms.topkelements; import java.util.ArrayList; import java.util.List; diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/MaxHeapTopKElementsFinder.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/MaxHeapTopKElementsFinder.java similarity index 93% rename from algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/MaxHeapTopKElementsFinder.java rename to algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/MaxHeapTopKElementsFinder.java index e39eb7ccb2..16ae7f1254 100644 --- a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/MaxHeapTopKElementsFinder.java +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/MaxHeapTopKElementsFinder.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.topnelements; +package com.baeldung.algorithms.topkelements; import java.util.ArrayList; import java.util.Collections; diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TopKElementsFinder.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TopKElementsFinder.java similarity index 74% rename from algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TopKElementsFinder.java rename to algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TopKElementsFinder.java index d1bd48efa5..a9c7881408 100644 --- a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TopKElementsFinder.java +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TopKElementsFinder.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.topnelements; +package com.baeldung.algorithms.topkelements; import java.util.List; diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TreeSetTopKElementsFinder.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TreeSetTopKElementsFinder.java similarity index 91% rename from algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TreeSetTopKElementsFinder.java rename to algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TreeSetTopKElementsFinder.java index c1fc8914d0..0b898df21d 100644 --- a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topnelements/TreeSetTopKElementsFinder.java +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TreeSetTopKElementsFinder.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.topnelements; +package com.baeldung.algorithms.topkelements; import java.util.Comparator; import java.util.List; diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java index 5c02cefe23..41fa5e067e 100644 --- a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java @@ -1,9 +1,5 @@ package com.baeldung.algorithms.topkelements; -import com.baeldung.algorithms.topnelements.BruteForceTopKElementsFinder; -import com.baeldung.algorithms.topnelements.MaxHeapTopKElementsFinder; -import com.baeldung.algorithms.topnelements.TopKElementsFinder; -import com.baeldung.algorithms.topnelements.TreeSetTopKElementsFinder; import org.junit.Test; import java.util.Arrays; From 4f987c9198d52a4068454f7f9d3e61266e1ac08e Mon Sep 17 00:00:00 2001 From: joe zhang Date: Tue, 7 Jul 2020 13:20:06 +0800 Subject: [PATCH 009/132] update labmda function --- .../convertlisttomap/ListToMapUnitTest.java | 28 +++++-------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java b/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java index 5a875a904e..4ca5671e29 100644 --- a/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java +++ b/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java @@ -24,13 +24,9 @@ public class ListToMapUnitTest { Map> convertedMap = new HashMap<>(); - Supplier> listSupplier = () -> { - return new ArrayList<>(); - }; + Supplier> listSupplier = ArrayList::new; - Supplier>> mapFactory = () -> { - return new HashMap<>(); - }; + Supplier>> mapFactory = HashMap::new; convertedMap = strings.stream() .collect(Collectors.groupingBy(String::length, mapFactory, Collectors.toCollection(listSupplier))); @@ -45,13 +41,9 @@ public class ListToMapUnitTest { Map> convertedMap = new HashMap<>(); - Supplier>> mapFactory = () -> { - return new HashMap<>(); - }; + Supplier>> mapFactory = HashMap::new; - Supplier> listSupplier = () -> { - return new ArrayList<>(); - }; + Supplier> listSupplier = ArrayList::new; BiConsumer>, String> accumulator = (response, element) -> { Integer key = element.length(); @@ -78,17 +70,11 @@ public class ListToMapUnitTest { Map> convertedMap = new HashMap<>(); - Supplier>> mapFactory = () -> { - return new HashMap<>(); - }; + Supplier>> mapFactory = HashMap::new; - Supplier> listSupplier = () -> { - return new ArrayList<>(); - }; + Supplier> listSupplier = ArrayList::new; - Function keyMapper = (element) -> { - return element.length(); - }; + Function keyMapper = String::length; Function> valueMapper = (element) -> { List collection = listSupplier.get(); From ecff38abf64bf603db9564f0640e705d847cd2d7 Mon Sep 17 00:00:00 2001 From: Daniel Garrett Date: Tue, 7 Jul 2020 16:14:30 +0100 Subject: [PATCH 010/132] feat: add test for assumeFalse --- .../assume/ConditionallyIgnoreTestsUnitTest.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java b/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java index 0a95ed4522..b5cc82d79d 100644 --- a/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java +++ b/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java @@ -2,8 +2,7 @@ package com.baeldung.assume; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeThat; -import static org.junit.Assume.assumeTrue; +import static org.junit.Assume.*; import org.junit.Test; @@ -26,6 +25,14 @@ public class ConditionallyIgnoreTestsUnitTest { assertEquals("hello", "HELLO".toLowerCase()); } + @Test + public void whenAssumeFalseOnCondition_thenIgnore() { + final int codeVersion = 2; + assumeFalse(isCodeVersion2(codeVersion)); + + assertEquals("hello", "HELLO".toLowerCase()); + } + private boolean isCodeVersion2(final int codeVersion) { return codeVersion == 2; } From 0865321f82538eaa0e1b26a7731d1d4f7532bc2c Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Tue, 7 Jul 2020 19:01:50 +0200 Subject: [PATCH 011/132] JAVA-1645: Get rid of the overriden spring-boot.version property --- persistence-modules/spring-data-redis/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index d2bf074d03..d271df31c7 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -98,7 +98,6 @@ 3.2.4 0.10.0 0.6 - 2.1.9.RELEASE From 749b832ef8ba3db73745b262fa580d8f610a29db Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Tue, 7 Jul 2020 19:02:09 +0200 Subject: [PATCH 012/132] JAVA-1645: Use ReactiveStringRedisTemplate --- .../spring/data/reactive/redis/config/RedisConfig.java | 5 ----- .../template/RedisTemplateListOpsIntegrationTest.java | 9 ++++----- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java index d23d0092eb..de8e447ef8 100644 --- a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java @@ -31,11 +31,6 @@ public class RedisConfig { return new ReactiveRedisTemplate<>(factory, context); } - @Bean - public ReactiveRedisTemplate reactiveRedisTemplateString(ReactiveRedisConnectionFactory connectionFactory) { - return new ReactiveRedisTemplate<>(connectionFactory, RedisSerializationContext.string()); - } - @Bean public ReactiveKeyCommands keyCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) { return reactiveRedisConnectionFactory.getReactiveConnection() diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java index 58846d7c27..cd5994c854 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java @@ -2,9 +2,6 @@ package com.baeldung.spring.data.reactive.redis.template; import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; - -import java.io.IOException; - import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; @@ -13,7 +10,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.ReactiveListOperations; -import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.core.ReactiveStringRedisTemplate; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.SpringRunner; @@ -21,6 +18,8 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import redis.embedded.RedisServerBuilder; +import java.io.IOException; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) @@ -30,7 +29,7 @@ public class RedisTemplateListOpsIntegrationTest { private static redis.embedded.RedisServer redisServer; @Autowired - private ReactiveRedisTemplate redisTemplate; + private ReactiveStringRedisTemplate redisTemplate; private ReactiveListOperations reactiveListOps; From a909a79f718c0129ee56b66910ba0b058aa3464b Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Sat, 11 Jul 2020 20:34:36 -0600 Subject: [PATCH 013/132] BAEL-4148: Demo app for spring boot and Docker --- docker/docker-spring-boot/mvnw | 310 ++++++++++++++++++ docker/docker-spring-boot/mvnw.cmd | 182 ++++++++++ docker/docker-spring-boot/pom.xml | 54 +++ .../src/main/docker/Dockerfile | 15 + .../com/baeldung/docker/DemoApplication.java | 13 + .../com/baeldung/docker/HelloController.java | 16 + .../src/main/resources/application.properties | 1 + 7 files changed, 591 insertions(+) create mode 100755 docker/docker-spring-boot/mvnw create mode 100644 docker/docker-spring-boot/mvnw.cmd create mode 100644 docker/docker-spring-boot/pom.xml create mode 100644 docker/docker-spring-boot/src/main/docker/Dockerfile create mode 100644 docker/docker-spring-boot/src/main/java/com/baeldung/docker/DemoApplication.java create mode 100644 docker/docker-spring-boot/src/main/java/com/baeldung/docker/HelloController.java create mode 100644 docker/docker-spring-boot/src/main/resources/application.properties diff --git a/docker/docker-spring-boot/mvnw b/docker/docker-spring-boot/mvnw new file mode 100755 index 0000000000..a16b5431b4 --- /dev/null +++ b/docker/docker-spring-boot/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/docker/docker-spring-boot/mvnw.cmd b/docker/docker-spring-boot/mvnw.cmd new file mode 100644 index 0000000000..c8d43372c9 --- /dev/null +++ b/docker/docker-spring-boot/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/docker/docker-spring-boot/pom.xml b/docker/docker-spring-boot/pom.xml new file mode 100644 index 0000000000..b9c80bc43a --- /dev/null +++ b/docker/docker-spring-boot/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + com.baeldung.docker + spring-boot-docker + 0.0.1-SNAPSHOT + spring-boot-docker + Demo project showing Spring Boot and Docker + + + 8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + true + + + + + + + diff --git a/docker/docker-spring-boot/src/main/docker/Dockerfile b/docker/docker-spring-boot/src/main/docker/Dockerfile new file mode 100644 index 0000000000..fa147dd69b --- /dev/null +++ b/docker/docker-spring-boot/src/main/docker/Dockerfile @@ -0,0 +1,15 @@ +# To build, run the following command from the top level project directory: +# +# docker build -f src/main/docker/Dockerfile . + +FROM adoptopenjdk:11-jre-hotspot as builder +ARG JAR_FILE=target/*.jar +COPY ${JAR_FILE} application.jar +RUN java -Djarmode=layertools -jar application.jar extract + +FROM adoptopenjdk:11-jre-hotspot +COPY --from=builder dependencies/ ./ +COPY --from=builder snapshot-dependencies/ ./ +COPY --from=builder spring-boot-loader/ ./ +COPY --from=builder application/ ./ +ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"] \ No newline at end of file diff --git a/docker/docker-spring-boot/src/main/java/com/baeldung/docker/DemoApplication.java b/docker/docker-spring-boot/src/main/java/com/baeldung/docker/DemoApplication.java new file mode 100644 index 0000000000..e0c1d57e89 --- /dev/null +++ b/docker/docker-spring-boot/src/main/java/com/baeldung/docker/DemoApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.docker; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/docker/docker-spring-boot/src/main/java/com/baeldung/docker/HelloController.java b/docker/docker-spring-boot/src/main/java/com/baeldung/docker/HelloController.java new file mode 100644 index 0000000000..b463bb557f --- /dev/null +++ b/docker/docker-spring-boot/src/main/java/com/baeldung/docker/HelloController.java @@ -0,0 +1,16 @@ +package com.baeldung.docker; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HelloController { + + @GetMapping("/hello") + public ResponseEntity hello() + { + return ResponseEntity.ok("hello2 "); + } + +} diff --git a/docker/docker-spring-boot/src/main/resources/application.properties b/docker/docker-spring-boot/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/docker/docker-spring-boot/src/main/resources/application.properties @@ -0,0 +1 @@ + From 9e82ccd8957cf9d51d6d2ee266a7ad7ae3f49798 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 12 Jul 2020 08:56:13 +0530 Subject: [PATCH 014/132] JAVA-619: Split or move core-java-modules/core-java-io-apis module --- core-java-modules/core-java-io-apis/README.md | 1 - libraries-apache-commons/README.md | 1 + libraries-apache-commons/pom.xml | 6 ++++++ .../baeldung/dirmonitoring/DirectoryMonitoringExample.java | 0 4 files changed, 7 insertions(+), 1 deletion(-) rename {core-java-modules/core-java-io-apis => libraries-apache-commons}/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java (100%) diff --git a/core-java-modules/core-java-io-apis/README.md b/core-java-modules/core-java-io-apis/README.md index 4d2bb0afb1..9399443ebd 100644 --- a/core-java-modules/core-java-io-apis/README.md +++ b/core-java-modules/core-java-io-apis/README.md @@ -7,7 +7,6 @@ This module contains articles about core Java input/output(IO) APIs. - [A Guide to the Java FileReader Class](https://www.baeldung.com/java-filereader) - [The Java File Class](https://www.baeldung.com/java-io-file) - [Java FileWriter](https://www.baeldung.com/java-filewriter) -- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](https://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library) - [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](https://www.baeldung.com/java-path) - [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter) - [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader) diff --git a/libraries-apache-commons/README.md b/libraries-apache-commons/README.md index 439587266b..aceea3282a 100644 --- a/libraries-apache-commons/README.md +++ b/libraries-apache-commons/README.md @@ -13,3 +13,4 @@ This module contains articles about Apache Commons libraries. - [Apache Commons BeanUtils](https://www.baeldung.com/apache-commons-beanutils) - [Histograms with Apache Commons Frequency](https://www.baeldung.com/apache-commons-frequency) - [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) +- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](https://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library) \ No newline at end of file diff --git a/libraries-apache-commons/pom.xml b/libraries-apache-commons/pom.xml index 688a500c4a..74adddabcf 100644 --- a/libraries-apache-commons/pom.xml +++ b/libraries-apache-commons/pom.xml @@ -57,6 +57,11 @@ xchart ${xchart-version} + + commons-io + commons-io + ${common-io.version} + @@ -68,6 +73,7 @@ 1.6 3.5.2 3.6.1 + 2.5 diff --git a/core-java-modules/core-java-io-apis/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java b/libraries-apache-commons/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java similarity index 100% rename from core-java-modules/core-java-io-apis/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java rename to libraries-apache-commons/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java From 7cbb0833d40610344c1d11da0cf7597ca24e52ad Mon Sep 17 00:00:00 2001 From: joe zhang Date: Sun, 12 Jul 2020 16:19:08 +0800 Subject: [PATCH 015/132] refactor unit test into utility class --- .../convertlisttomap/ListToMapConverter.java | 70 +++++++++++++++++ .../convertlisttomap/ListToMapUnitTest.java | 78 ++++--------------- 2 files changed, 83 insertions(+), 65 deletions(-) create mode 100644 java-collections-conversions-2/src/main/java/com/baeldung/convertlisttomap/ListToMapConverter.java diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/convertlisttomap/ListToMapConverter.java b/java-collections-conversions-2/src/main/java/com/baeldung/convertlisttomap/ListToMapConverter.java new file mode 100644 index 0000000000..8450f54f9d --- /dev/null +++ b/java-collections-conversions-2/src/main/java/com/baeldung/convertlisttomap/ListToMapConverter.java @@ -0,0 +1,70 @@ +package com.baeldung.convertlisttomap; + +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.BinaryOperator; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +/** + * Convert a string list to a map whose key is the string's length and value is the collection with same length. + * Give a list {"Baeldung", "is", "very", "cool"}. + * After conversion we'll get a map like: + * {8 : ["Baeldung"], 2 : ["is"], 4 : ["very", "cool"]}. + * + * @author leasy.zhang + * + */ +public class ListToMapConverter { + + public Map> groupingByStringLength(List source, + Supplier>> mapSupplier, + Supplier> listSupplier) { + + return source.stream() + .collect(Collectors.groupingBy(String::length, mapSupplier, Collectors.toCollection(listSupplier))); + } + + public Map> streamCollectByStringLength(List source, + Supplier>> mapSupplier, + Supplier> listSupplier) { + + BiConsumer>, String> accumulator = (response, element) -> { + Integer key = element.length(); + List values = response.getOrDefault(key, listSupplier.get()); + values.add(element); + response.put(key, values); + }; + + BiConsumer>, Map>> combiner = (res1, res2) -> { + res1.putAll(res2); + }; + + return source.stream() + .collect(mapSupplier, accumulator, combiner); + } + + public Map> collectorToMapByStringLength(List source, + Supplier>> mapSupplier, + Supplier> listSupplier) { + + Function keyMapper = String::length; + + Function> valueMapper = (element) -> { + List collection = listSupplier.get(); + collection.add(element); + return collection; + }; + + BinaryOperator> mergeFunction = (existing, replacement) -> { + existing.addAll(replacement); + return existing; + }; + + return source.stream() + .collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)); + } + +} diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java b/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java index 4ca5671e29..2b43813822 100644 --- a/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java +++ b/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.convertlisttomap; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; @@ -8,89 +7,38 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.BiConsumer; -import java.util.function.BinaryOperator; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collectors; +import org.junit.Before; import org.junit.Test; public class ListToMapUnitTest { + private ListToMapConverter converter; + private List source; + + @Before + public void setUp() { + converter = new ListToMapConverter(); + source = Arrays.asList("List", "Map", "Set", "Tree"); + } + @Test public void givenAList_whenConvertWithJava8GroupBy_thenReturnMap() { - List strings = Arrays.asList("List", "Map", "Set", "Tree"); - - Map> convertedMap = new HashMap<>(); - - Supplier> listSupplier = ArrayList::new; - - Supplier>> mapFactory = HashMap::new; - convertedMap = strings.stream() - .collect(Collectors.groupingBy(String::length, mapFactory, Collectors.toCollection(listSupplier))); - - assertEquals(2, convertedMap.size()); + Map> convertedMap = converter.groupingByStringLength(source, HashMap::new, ArrayList::new); assertTrue(convertedMap.get(3) .contains("Map")); } @Test public void givenAList_whenConvertWithJava8Collect_thenReturnMap() { - List strings = Arrays.asList("List", "Map", "Set", "Tree"); - - Map> convertedMap = new HashMap<>(); - - Supplier>> mapFactory = HashMap::new; - - Supplier> listSupplier = ArrayList::new; - - BiConsumer>, String> accumulator = (response, element) -> { - Integer key = element.length(); - List values = response.getOrDefault(key, listSupplier.get()); - values.add(element); - response.put(key, values); - }; - - BiConsumer>, Map>> combiner = (res1, res2) -> { - res1.putAll(res2); - }; - - convertedMap = strings.stream() - .collect(mapFactory, accumulator, combiner); - - assertEquals(2, convertedMap.size()); + Map> convertedMap = converter.streamCollectByStringLength(source, HashMap::new, ArrayList::new); assertTrue(convertedMap.get(3) .contains("Map")); } @Test public void givenAList_whenConvertWithCollectorToMap_thenReturnMap() { - List strings = Arrays.asList("List", "Map", "Set", "Tree"); - - Map> convertedMap = new HashMap<>(); - - Supplier>> mapFactory = HashMap::new; - - Supplier> listSupplier = ArrayList::new; - - Function keyMapper = String::length; - - Function> valueMapper = (element) -> { - List collection = listSupplier.get(); - collection.add(element); - return collection; - }; - - BinaryOperator> mergeFunction = (existing, replacement) -> { - existing.addAll(replacement); - return existing; - }; - - convertedMap = strings.stream() - .collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapFactory)); - - assertEquals(2, convertedMap.size()); + Map> convertedMap = converter.collectorToMapByStringLength(source, HashMap::new, ArrayList::new); assertTrue(convertedMap.get(3) .contains("Map")); } From c1740e57ec42404c72d0b41dad06bd6c47a9542d Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Sun, 12 Jul 2020 11:38:22 +0200 Subject: [PATCH 016/132] Fixed formatting. --- maven-all/maven-2/pom.xml | 86 +++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/maven-all/maven-2/pom.xml b/maven-all/maven-2/pom.xml index 629da573b5..74bae61f03 100644 --- a/maven-all/maven-2/pom.xml +++ b/maven-all/maven-2/pom.xml @@ -1,51 +1,51 @@ - 4.0.0 - maven-2 - 0.0.1-SNAPSHOT - maven-2 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + maven-2 + 0.0.1-SNAPSHOT + maven-2 - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../.. - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../.. + - - - junit - junit - 4.13 - - + + + junit + junit + 4.13 + + - - - - org.codehaus.mojo - properties-maven-plugin - 1.0.0 - - - generate-resources - - write-project-properties - - - ${project.build.outputDirectory}/properties-from-pom.properties - - - - - - + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + generate-resources + + write-project-properties + + + ${project.build.outputDirectory}/properties-from-pom.properties + + + + + + - - ${project.name} - property-from-pom - + + ${project.name} + property-from-pom + \ No newline at end of file From 637f81023d7c74156e2473543a322e3195e683f9 Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Sun, 12 Jul 2020 11:45:26 +0200 Subject: [PATCH 017/132] Moved and renamed maven-all/maven-2 to maven-modules/maven-properties --- maven-modules/maven-properties/.gitignore | 2 + maven-modules/maven-properties/README.md | 8 +++ maven-modules/maven-properties/pom.xml | 51 +++++++++++++++++++ .../maven/properties/PropertiesReader.java | 41 +++++++++++++++ .../properties/PropertiesReaderUnitTest.java | 27 ++++++++++ maven-modules/pom.xml | 1 + 6 files changed, 130 insertions(+) create mode 100644 maven-modules/maven-properties/.gitignore create mode 100644 maven-modules/maven-properties/README.md create mode 100644 maven-modules/maven-properties/pom.xml create mode 100644 maven-modules/maven-properties/src/main/java/com/baeldung/maven/properties/PropertiesReader.java create mode 100644 maven-modules/maven-properties/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java diff --git a/maven-modules/maven-properties/.gitignore b/maven-modules/maven-properties/.gitignore new file mode 100644 index 0000000000..bae0b0d7ce --- /dev/null +++ b/maven-modules/maven-properties/.gitignore @@ -0,0 +1,2 @@ +/output-resources +/.idea/ diff --git a/maven-modules/maven-properties/README.md b/maven-modules/maven-properties/README.md new file mode 100644 index 0000000000..65d976189c --- /dev/null +++ b/maven-modules/maven-properties/README.md @@ -0,0 +1,8 @@ +## Apache Maven + +This module contains articles about core Apache Maven. Articles about other Maven plugins (such as the Maven WAR Plugin) +have their own dedicated modules. + +### Relevant Articles + +- [Accessing Maven Properties in Java] \ No newline at end of file diff --git a/maven-modules/maven-properties/pom.xml b/maven-modules/maven-properties/pom.xml new file mode 100644 index 0000000000..2cd92da42f --- /dev/null +++ b/maven-modules/maven-properties/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + maven-properties + 0.0.1-SNAPSHOT + maven-properties + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../.. + + + + + junit + junit + 4.13 + + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + generate-resources + + write-project-properties + + + ${project.build.outputDirectory}/properties-from-pom.properties + + + + + + + + + ${project.name} + property-from-pom + + + \ No newline at end of file diff --git a/maven-modules/maven-properties/src/main/java/com/baeldung/maven/properties/PropertiesReader.java b/maven-modules/maven-properties/src/main/java/com/baeldung/maven/properties/PropertiesReader.java new file mode 100644 index 0000000000..e7000ec2ce --- /dev/null +++ b/maven-modules/maven-properties/src/main/java/com/baeldung/maven/properties/PropertiesReader.java @@ -0,0 +1,41 @@ +package com.baeldung.maven.properties; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +/** + * Reads properties from one file. + * + * @author Donato Rimenti + */ +public class PropertiesReader { + + /** + * Properties managed by this reader. + */ + private Properties properties; + + /** + * Reads the property file with the given name. + * + * @param propertyFileName the name of the property file to read + * @throws IOException if the file is not found or there's a problem reading it + */ + public PropertiesReader(String propertyFileName) throws IOException { + InputStream is = getClass().getClassLoader() + .getResourceAsStream(propertyFileName); + this.properties = new Properties(); + this.properties.load(is); + } + + /** + * Gets the property with the given name from the property file. + * @param propertyName the name of the property to read + * @return the property with the given name + */ + public String getProperty(String propertyName) { + return this.properties.getProperty(propertyName); + } + +} \ No newline at end of file diff --git a/maven-modules/maven-properties/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java b/maven-modules/maven-properties/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java new file mode 100644 index 0000000000..a1d6e66047 --- /dev/null +++ b/maven-modules/maven-properties/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.maven.properties; + +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Test for {@link PropertiesReader}. + * + * @author Donato Rimenti + */ +public class PropertiesReaderUnitTest { + + /** + * Reads a property and checks that's the one expected. + * + * @throws IOException if anything goes wrong + */ + @Test + public void givenPomProperties_whenPropertyRead_thenPropertyReturned() throws IOException { + PropertiesReader reader = new PropertiesReader("properties-from-pom.properties"); + String property = reader.getProperty("my.awesome.property"); + Assert.assertEquals("property-from-pom", property); + } + +} \ No newline at end of file diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml index c4d8c253df..2de8560244 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -24,6 +24,7 @@ maven-profiles versions-maven-plugin version-collision + maven-properties From 6bd023a04d02eb2304d974fcf0701d75c3b15b9b Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Sun, 12 Jul 2020 11:47:27 +0200 Subject: [PATCH 018/132] Fixed pom formatting. --- maven-modules/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml index 2de8560244..d990ed16c1 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -24,7 +24,7 @@ maven-profiles versions-maven-plugin version-collision - maven-properties + maven-properties From 480775b0c43b81e0f515a58abd70b454f331d8c7 Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Sun, 12 Jul 2020 18:01:22 +0200 Subject: [PATCH 019/132] Removed maven-all project since it was moved to maven-modules. --- maven-all/maven-2/.gitignore | 2 - maven-all/maven-2/README.md | 6 --- maven-all/maven-2/pom.xml | 51 ------------------- .../maven/properties/PropertiesReader.java | 41 --------------- .../properties/PropertiesReaderUnitTest.java | 27 ---------- 5 files changed, 127 deletions(-) delete mode 100644 maven-all/maven-2/.gitignore delete mode 100644 maven-all/maven-2/README.md delete mode 100644 maven-all/maven-2/pom.xml delete mode 100644 maven-all/maven-2/src/main/java/com/baeldung/maven/properties/PropertiesReader.java delete mode 100644 maven-all/maven-2/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java diff --git a/maven-all/maven-2/.gitignore b/maven-all/maven-2/.gitignore deleted file mode 100644 index bae0b0d7ce..0000000000 --- a/maven-all/maven-2/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/output-resources -/.idea/ diff --git a/maven-all/maven-2/README.md b/maven-all/maven-2/README.md deleted file mode 100644 index 5878a4f732..0000000000 --- a/maven-all/maven-2/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Apache Maven - -This module contains articles about core Apache Maven. Articles about other Maven plugins (such as the Maven WAR Plugin) -have their own dedicated modules. - -### Relevant Articles diff --git a/maven-all/maven-2/pom.xml b/maven-all/maven-2/pom.xml deleted file mode 100644 index 74bae61f03..0000000000 --- a/maven-all/maven-2/pom.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - 4.0.0 - maven-2 - 0.0.1-SNAPSHOT - maven-2 - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../.. - - - - - junit - junit - 4.13 - - - - - - - org.codehaus.mojo - properties-maven-plugin - 1.0.0 - - - generate-resources - - write-project-properties - - - ${project.build.outputDirectory}/properties-from-pom.properties - - - - - - - - - ${project.name} - property-from-pom - - - \ No newline at end of file diff --git a/maven-all/maven-2/src/main/java/com/baeldung/maven/properties/PropertiesReader.java b/maven-all/maven-2/src/main/java/com/baeldung/maven/properties/PropertiesReader.java deleted file mode 100644 index e7000ec2ce..0000000000 --- a/maven-all/maven-2/src/main/java/com/baeldung/maven/properties/PropertiesReader.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.maven.properties; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * Reads properties from one file. - * - * @author Donato Rimenti - */ -public class PropertiesReader { - - /** - * Properties managed by this reader. - */ - private Properties properties; - - /** - * Reads the property file with the given name. - * - * @param propertyFileName the name of the property file to read - * @throws IOException if the file is not found or there's a problem reading it - */ - public PropertiesReader(String propertyFileName) throws IOException { - InputStream is = getClass().getClassLoader() - .getResourceAsStream(propertyFileName); - this.properties = new Properties(); - this.properties.load(is); - } - - /** - * Gets the property with the given name from the property file. - * @param propertyName the name of the property to read - * @return the property with the given name - */ - public String getProperty(String propertyName) { - return this.properties.getProperty(propertyName); - } - -} \ No newline at end of file diff --git a/maven-all/maven-2/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java b/maven-all/maven-2/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java deleted file mode 100644 index a1d6e66047..0000000000 --- a/maven-all/maven-2/src/test/java/com/baeldung/maven/properties/PropertiesReaderUnitTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.maven.properties; - -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Test; - -/** - * Test for {@link PropertiesReader}. - * - * @author Donato Rimenti - */ -public class PropertiesReaderUnitTest { - - /** - * Reads a property and checks that's the one expected. - * - * @throws IOException if anything goes wrong - */ - @Test - public void givenPomProperties_whenPropertyRead_thenPropertyReturned() throws IOException { - PropertiesReader reader = new PropertiesReader("properties-from-pom.properties"); - String property = reader.getProperty("my.awesome.property"); - Assert.assertEquals("property-from-pom", property); - } - -} \ No newline at end of file From c6b1b43bdde33f0f02178c2c477d49f1e3e3300a Mon Sep 17 00:00:00 2001 From: Ali Ben Messaoud Date: Mon, 6 Jul 2020 01:01:19 +0200 Subject: [PATCH 020/132] BAEL-4350: Difference between Statement and PreparedStatement Signed-off-by: Ali Ben Messaoud --- .../DatasourceFactory.java | 23 +++++ .../PersonEntity.java | 42 ++++++++ .../PreparedStatementPersonDao.java | 88 +++++++++++++++++ .../StatementPersonDao.java | 75 +++++++++++++++ .../DatasourceFactoryUnitTest.java | 22 +++++ .../PreparedStatementPersonDaoUnitTest.java | 94 ++++++++++++++++++ .../StatementPersonDaoUnitTest.java | 96 +++++++++++++++++++ 7 files changed, 440 insertions(+) create mode 100644 persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactory.java create mode 100644 persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/PersonEntity.java create mode 100644 persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDao.java create mode 100644 persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/StatementPersonDao.java create mode 100644 persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactoryUnitTest.java create mode 100644 persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDaoUnitTest.java create mode 100644 persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/StatementPersonDaoUnitTest.java diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactory.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactory.java new file mode 100644 index 0000000000..adbdc66030 --- /dev/null +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactory.java @@ -0,0 +1,23 @@ +package com.baeldung.statmentVsPreparedstatment; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class DatasourceFactory { + + private Connection connection; + + public Connection getConnection() throws ClassNotFoundException, SQLException { + Class.forName("org.h2.Driver"); + connection = DriverManager.getConnection("jdbc:h2:mem:db_basic", "SA", ""); + connection.setAutoCommit(false); + return connection; + } + + public boolean createTables() throws SQLException { + String query = "create table if not exists PERSONS (ID INT, NAME VARCHAR(45))"; + return connection.createStatement().executeUpdate(query) == 0; + } + +} diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/PersonEntity.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/PersonEntity.java new file mode 100644 index 0000000000..72fc0c1e24 --- /dev/null +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/PersonEntity.java @@ -0,0 +1,42 @@ +package com.baeldung.statmentVsPreparedstatment; + +import java.util.Objects; + +public class PersonEntity { + private int id; + private String name; + + public PersonEntity(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; + } + + @Override public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + PersonEntity that = (PersonEntity) o; + return id == that.id && Objects.equals(name, that.name); + } + + @Override public int hashCode() { + return Objects.hash(id, name); + } +} diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDao.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDao.java new file mode 100644 index 0000000000..47124d9139 --- /dev/null +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDao.java @@ -0,0 +1,88 @@ +package com.baeldung.statmentVsPreparedstatment; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class PreparedStatementPersonDao { + + private final Connection connection; + + public PreparedStatementPersonDao(Connection connection) { + this.connection = connection; + } + + public Optional getById(int id) throws SQLException { + String query = "SELECT id, name FROM persons WHERE id = ?"; + + PreparedStatement preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, id); + ResultSet resultSet = preparedStatement.executeQuery(); + + if (resultSet.first()) { + + PersonEntity result = new PersonEntity(resultSet.getInt("id"), + resultSet.getString("name")); + + return Optional.of(result); + } else { + return Optional.empty(); + } + + } + + public void insert(PersonEntity personEntity) throws SQLException { + + String query = "INSERT INTO persons(id, name) VALUES( ?, ?)"; + + PreparedStatement preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, personEntity.getId()); + preparedStatement.setString(2, personEntity.getName()); + preparedStatement.executeUpdate(); + + } + + public void insert(List personEntities) throws SQLException { + String query = "INSERT INTO persons(id, name) VALUES( ?, ?)"; + + PreparedStatement preparedStatement = connection.prepareStatement(query); + for (PersonEntity personEntity : personEntities) { + preparedStatement.setInt(1, personEntity.getId()); + preparedStatement.setString(2, personEntity.getName()); + preparedStatement.addBatch(); + } + preparedStatement.executeBatch(); + + } + + public void update(PersonEntity personEntity) throws SQLException { + String query = "UPDATE persons SET name = ? WHERE id = ?"; + PreparedStatement preparedStatement = connection.prepareStatement(query); + preparedStatement.setString(1, personEntity.getName()); + preparedStatement.setInt(2, personEntity.getId()); + preparedStatement.executeUpdate(); + } + + public void deleteById(int id) throws SQLException { + String query = "DELETE FROM persons WHERE id = ?"; + PreparedStatement preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, id); + preparedStatement.executeUpdate(); + } + + public List getAll() throws SQLException { + String query = "SELECT id, name FROM persons"; + + PreparedStatement preparedStatement = connection.prepareStatement(query); + ResultSet resultSet = preparedStatement.executeQuery(); + List result = new ArrayList<>(); + while (resultSet.next()) { + result.add(new PersonEntity(resultSet.getInt("id"), resultSet.getString("name"))); + } + return result; + } +} diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/StatementPersonDao.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/StatementPersonDao.java new file mode 100644 index 0000000000..935ba8efa2 --- /dev/null +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/StatementPersonDao.java @@ -0,0 +1,75 @@ +package com.baeldung.statmentVsPreparedstatment; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class StatementPersonDao { + + private final Connection connection; + + public StatementPersonDao(Connection connection) { + this.connection = connection; + } + + public Optional getById(int id) throws SQLException { + String query = "SELECT id, name, FROM persons WHERE id = '" + id + "'"; + + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(query); + + if (resultSet.first()) { + PersonEntity result = new PersonEntity(resultSet.getInt("id"), + resultSet.getString("name")); + return Optional.of(result); + } else { + return Optional.empty(); + } + } + + public void insert(PersonEntity personEntity) throws SQLException { + String query = "INSERT INTO persons(id, name) VALUES(" + personEntity.getId() + ", '" + + personEntity.getName() + "')"; + + Statement statement = connection.createStatement(); + statement.executeUpdate(query); + } + + public void insert(List personEntities) throws SQLException { + for (PersonEntity personEntity : personEntities) { + insert(personEntity); + } + } + + public void update(PersonEntity personEntity) throws SQLException { + + String query = "UPDATE persons SET name = '" + personEntity.getName() + "' WHERE id = " + + personEntity.getId(); + + Statement statement = connection.createStatement(); + statement.executeUpdate(query); + + } + + public void deleteById(int id) throws SQLException { + String query = "DELETE FROM persons WHERE id = " + id; + Statement statement = connection.createStatement(); + statement.executeUpdate(query); + } + + public List getAll() throws SQLException { + String query = "SELECT id, name, FROM persons"; + + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(query); + List result = new ArrayList<>(); + while (resultSet.next()) { + result.add(new PersonEntity(resultSet.getInt("id"), resultSet.getString("name"))); + } + return result; + } +} diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactoryUnitTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactoryUnitTest.java new file mode 100644 index 0000000000..5d3b151d5d --- /dev/null +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactoryUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.statmentVsPreparedstatment; + +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DatasourceFactoryUnitTest { + + @Test + void whenCreateConnectionAndTables_thenConnectionIsOpenAndTableIsCreated() + throws SQLException, ClassNotFoundException { + DatasourceFactory factory = new DatasourceFactory(); + Connection connection = factory.getConnection(); + + assertFalse(connection.isClosed()); + assertTrue(factory.createTables()); + } +} \ No newline at end of file diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDaoUnitTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDaoUnitTest.java new file mode 100644 index 0000000000..ce79f47802 --- /dev/null +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDaoUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.statmentVsPreparedstatment; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +class PreparedStatementPersonDaoUnitTest { + private PreparedStatementPersonDao dao; + + @BeforeEach + void setup() throws SQLException, ClassNotFoundException { + DatasourceFactory datasourceFactory = new DatasourceFactory(); + Connection connection = datasourceFactory.getConnection(); + datasourceFactory.createTables(); + dao = new PreparedStatementPersonDao(connection); + } + + @Test + void whenInsertAPerson_thenItNeverThrowsAnException() { + assertDoesNotThrow(() -> dao.insert(new PersonEntity(1, "john"))); + } + + @Test + void whenInsertAPersonWithQuoteInText_thenItNeverThrowsAnException() { + assertDoesNotThrow(() -> dao.insert(new PersonEntity(1, "O'Brien"))); + } + + @Test + void whenGetAPersonById_thenItReturnThePersonInDatabase() throws SQLException { + dao.insert(new PersonEntity(1, "john")); + + Optional maybeEmployee = dao.getById(1); + assertTrue(maybeEmployee.isPresent()); + + PersonEntity personEntity = maybeEmployee.get(); + + assertEquals(1, personEntity.getId()); + assertEquals("john", personEntity.getName()); + } + + @Test + void whenInsertAndGetMultiplePersons_thenItNeverThrowsAnException() throws SQLException { + assertDoesNotThrow(() -> dao.insert( + Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skit")))); + + List result = dao.getAll(); + + assertEquals(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skit")), + result); + } + + @Test + void whenUpdateAnExistentPerson_thenItReturnsTheUpdatedPerson() throws SQLException { + dao.insert(new PersonEntity(1, "john")); + dao.update(new PersonEntity(1, "johnny")); + + Optional maybePerson = dao.getById(1); + + assertTrue(maybePerson.isPresent()); + + PersonEntity personEntity = maybePerson.get(); + + assertEquals(1, personEntity.getId()); + assertEquals("johnny", personEntity.getName()); + } + + @Test + void whenDeleteAPersonById_thenItWillBeAbsentInDatabase() throws SQLException { + dao.insert(new PersonEntity(1, "john")); + dao.deleteById(1); + + Optional maybePerson = dao.getById(1); + + assertFalse(maybePerson.isPresent()); + } + + @Test + void whenAHackerUpdateAPerson_thenItUpdatesTheTargetPerson() throws SQLException { + dao.insert(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skeet"))); + dao.update(new PersonEntity(1, "hacker' --")); + + List result = dao.getAll(); + + assertEquals(Arrays.asList(new PersonEntity(1, "hacker' --"), new PersonEntity(2, "skeet")), + result); + } +} \ No newline at end of file diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/StatementPersonDaoUnitTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/StatementPersonDaoUnitTest.java new file mode 100644 index 0000000000..b31bdcc296 --- /dev/null +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/statmentVsPreparedstatment/StatementPersonDaoUnitTest.java @@ -0,0 +1,96 @@ +package com.baeldung.statmentVsPreparedstatment; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +class StatementPersonDaoUnitTest { + + private StatementPersonDao dao; + + @BeforeEach + void setup() throws SQLException, ClassNotFoundException { + DatasourceFactory datasourceFactory = new DatasourceFactory(); + Connection connection = datasourceFactory.getConnection(); + datasourceFactory.createTables(); + dao = new StatementPersonDao(connection); + } + + @Test + void whenInsertAPerson_thenItNeverThrowsAnException() { + assertDoesNotThrow(() -> dao.insert(new PersonEntity(1, "john"))); + } + + @Test + void whenInsertAPersonWithQuoteInText_thenItWillThrowAnException() { + assertThrows(SQLException.class, () -> dao.insert(new PersonEntity(1, "O'Brien"))); + } + + @Test + void whenGetAPersonById_thenItReturnThePersonInDatabase() throws SQLException { + dao.insert(new PersonEntity(1, "john")); + + Optional maybeEmployee = dao.getById(1); + + assertTrue(maybeEmployee.isPresent()); + + PersonEntity personEntity = maybeEmployee.get(); + + assertEquals(1, personEntity.getId()); + assertEquals("john", personEntity.getName()); + } + + @Test + void whenInsertAndGetMultiplePersons_thenItNeverThrowsAnException() throws SQLException { + assertDoesNotThrow(() -> dao.insert( + Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skeet")))); + + List result = dao.getAll(); + + assertEquals(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skeet")), + result); + } + + @Test + void whenUpdateAnExistentPerson_thenItReturnsTheUpdatedPerson() throws SQLException { + dao.insert(new PersonEntity(1, "john")); + dao.update(new PersonEntity(1, "johnny")); + + Optional maybePerson = dao.getById(1); + + assertTrue(maybePerson.isPresent()); + + PersonEntity personEntity = maybePerson.get(); + + assertEquals(1, personEntity.getId()); + assertEquals("johnny", personEntity.getName()); + } + + @Test + void whenDeleteAPersonById_thenItWillBeAbsentInDatabase() throws SQLException { + dao.insert(new PersonEntity(1, "john")); + dao.deleteById(1); + + Optional maybePerson = dao.getById(1); + + assertFalse(maybePerson.isPresent()); + } + + @Test + void whenAHackerUpdateAPerson_thenItAllPersonsAreUpdated() throws SQLException { + dao.insert(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skeet"))); + dao.update(new PersonEntity(1, "hacker' --")); + + List result = dao.getAll(); + + assertEquals(Arrays.asList(new PersonEntity(1, "hacker"), new PersonEntity(2, "hacker")), + result); + } +} \ No newline at end of file From 1145918e228134b8cece158b4d24edc47eb586f7 Mon Sep 17 00:00:00 2001 From: Daniel Garrett Date: Mon, 13 Jul 2020 10:07:50 +0100 Subject: [PATCH 021/132] fix: replace * imports with single imports: --- .../com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java b/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java index b5cc82d79d..0aa184f2e1 100644 --- a/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java +++ b/testing-modules/junit-4/src/test/java/com/baeldung/assume/ConditionallyIgnoreTestsUnitTest.java @@ -2,7 +2,9 @@ package com.baeldung.assume; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; -import static org.junit.Assume.*; +import static org.junit.Assume.assumeFalse; +import static org.junit.Assume.assumeThat; +import static org.junit.Assume.assumeTrue; import org.junit.Test; From d2e386881d0b6b280479996fae1936fb16eb3c9e Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 13 Jul 2020 20:58:32 +0200 Subject: [PATCH 022/132] JAVA-1636: Get rid of the overriden spring-boot.version property --- spring-cloud/spring-cloud-functions/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml index 4654d70dd7..7e6f5dfbdc 100644 --- a/spring-cloud/spring-cloud-functions/pom.xml +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -85,7 +85,6 @@ 1.0.1.RELEASE 2.0.2 1.1.0 - 2.0.4.RELEASE 1.0.10.RELEASE From 9f09a0b30d79404a32671ab66cb46a5b317f1351 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Tue, 14 Jul 2020 20:19:17 +0430 Subject: [PATCH 023/132] A Guide to @Contended & False Sharing --- .../main/java/com/baeldung/FalseSharing.java | 22 + jmh/src/main/java/com/baeldung/LongAdder.java | 235 +++++++++++ jmh/src/main/java/com/baeldung/Striped64.java | 393 ++++++++++++++++++ 3 files changed, 650 insertions(+) create mode 100644 jmh/src/main/java/com/baeldung/FalseSharing.java create mode 100644 jmh/src/main/java/com/baeldung/LongAdder.java create mode 100644 jmh/src/main/java/com/baeldung/Striped64.java diff --git a/jmh/src/main/java/com/baeldung/FalseSharing.java b/jmh/src/main/java/com/baeldung/FalseSharing.java new file mode 100644 index 0000000000..24ba0c0b6b --- /dev/null +++ b/jmh/src/main/java/com/baeldung/FalseSharing.java @@ -0,0 +1,22 @@ +package com.baeldung; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; + +@State(Scope.Benchmark) +public class FalseSharing { + + private java.util.concurrent.atomic.LongAdder builtin = new java.util.concurrent.atomic.LongAdder(); + private LongAdder custom = new LongAdder(); + + @Benchmark + public void builtin() { + builtin.increment(); + } + + @Benchmark + public void custom() { + custom.increment(); + } +} diff --git a/jmh/src/main/java/com/baeldung/LongAdder.java b/jmh/src/main/java/com/baeldung/LongAdder.java new file mode 100644 index 0000000000..8fd2b85c4f --- /dev/null +++ b/jmh/src/main/java/com/baeldung/LongAdder.java @@ -0,0 +1,235 @@ +package com.baeldung; + +import java.io.Serializable; +import java.util.concurrent.atomic.AtomicLong; + +/** + * One or more variables that together maintain an initially zero + * {@code long} sum. When updates (method {@link #add}) are contended + * across threads, the set of variables may grow dynamically to reduce + * contention. Method {@link #sum} (or, equivalently, {@link + * #longValue}) returns the current total combined across the + * variables maintaining the sum. + * + *

This class is usually preferable to {@link AtomicLong} when + * multiple threads update a common sum that is used for purposes such + * as collecting statistics, not for fine-grained synchronization + * control. Under low update contention, the two classes have similar + * characteristics. But under high contention, expected throughput of + * this class is significantly higher, at the expense of higher space + * consumption. + * + *

LongAdders can be used with a {@link + * java.util.concurrent.ConcurrentHashMap} to maintain a scalable + * frequency map (a form of histogram or multiset). For example, to + * add a count to a {@code ConcurrentHashMap freqs}, + * initializing if not already present, you can use {@code + * freqs.computeIfAbsent(k -> new LongAdder()).increment();} + * + *

This class extends {@link Number}, but does not define + * methods such as {@code equals}, {@code hashCode} and {@code + * compareTo} because instances are expected to be mutated, and so are + * not useful as collection keys. + * + * @since 1.8 + * @author Doug Lea + */ +public class LongAdder extends Striped64 implements Serializable { + private static final long serialVersionUID = 7249069246863182397L; + + /** + * Creates a new adder with initial sum of zero. + */ + public LongAdder() { + } + + /** + * Adds the given value. + * + * @param x the value to add + */ + public void add(long x) { + Cell[] as; long b, v; int m; Cell a; + if ((as = cells) != null || !casBase(b = base, b + x)) { + boolean uncontended = true; + if (as == null || (m = as.length - 1) < 0 || + (a = as[getProbe() & m]) == null || + !(uncontended = a.cas(v = a.value, v + x))) + longAccumulate(x, null, uncontended); + } + } + + /** + * Equivalent to {@code add(1)}. + */ + public void increment() { + add(1L); + } + + /** + * Equivalent to {@code add(-1)}. + */ + public void decrement() { + add(-1L); + } + + /** + * Returns the current sum. The returned value is NOT an + * atomic snapshot; invocation in the absence of concurrent + * updates returns an accurate result, but concurrent updates that + * occur while the sum is being calculated might not be + * incorporated. + * + * @return the sum + */ + public long sum() { + Cell[] as = cells; Cell a; + long sum = base; + if (as != null) { + for (int i = 0; i < as.length; ++i) { + if ((a = as[i]) != null) + sum += a.value; + } + } + return sum; + } + + /** + * Resets variables maintaining the sum to zero. This method may + * be a useful alternative to creating a new adder, but is only + * effective if there are no concurrent updates. Because this + * method is intrinsically racy, it should only be used when it is + * known that no threads are concurrently updating. + */ + public void reset() { + Cell[] as = cells; Cell a; + base = 0L; + if (as != null) { + for (int i = 0; i < as.length; ++i) { + if ((a = as[i]) != null) + a.value = 0L; + } + } + } + + /** + * Equivalent in effect to {@link #sum} followed by {@link + * #reset}. This method may apply for example during quiescent + * points between multithreaded computations. If there are + * updates concurrent with this method, the returned value is + * not guaranteed to be the final value occurring before + * the reset. + * + * @return the sum + */ + public long sumThenReset() { + Cell[] as = cells; Cell a; + long sum = base; + base = 0L; + if (as != null) { + for (int i = 0; i < as.length; ++i) { + if ((a = as[i]) != null) { + sum += a.value; + a.value = 0L; + } + } + } + return sum; + } + + /** + * Returns the String representation of the {@link #sum}. + * @return the String representation of the {@link #sum} + */ + public String toString() { + return Long.toString(sum()); + } + + /** + * Equivalent to {@link #sum}. + * + * @return the sum + */ + public long longValue() { + return sum(); + } + + /** + * Returns the {@link #sum} as an {@code int} after a narrowing + * primitive conversion. + */ + public int intValue() { + return (int)sum(); + } + + /** + * Returns the {@link #sum} as a {@code float} + * after a widening primitive conversion. + */ + public float floatValue() { + return (float)sum(); + } + + /** + * Returns the {@link #sum} as a {@code double} after a widening + * primitive conversion. + */ + public double doubleValue() { + return (double)sum(); + } + + /** + * Serialization proxy, used to avoid reference to the non-public + * Striped64 superclass in serialized forms. + * @serial include + */ + private static class SerializationProxy implements Serializable { + private static final long serialVersionUID = 7249069246863182397L; + + /** + * The current value returned by sum(). + * @serial + */ + private final long value; + + SerializationProxy(LongAdder a) { + value = a.sum(); + } + + /** + * Return a {@code LongAdder} object with initial state + * held by this proxy. + * + * @return a {@code LongAdder} object with initial state + * held by this proxy. + */ + private Object readResolve() { + LongAdder a = new LongAdder(); + a.base = value; + return a; + } + } + + /** + * Returns a + * + * SerializationProxy + * representing the state of this instance. + * + * @return a {@link SerializationProxy} + * representing the state of this instance + */ + private Object writeReplace() { + return new SerializationProxy(this); + } + + /** + * @param s the stream + * @throws java.io.InvalidObjectException always + */ + private void readObject(java.io.ObjectInputStream s) + throws java.io.InvalidObjectException { + throw new java.io.InvalidObjectException("Proxy required"); + } + +} diff --git a/jmh/src/main/java/com/baeldung/Striped64.java b/jmh/src/main/java/com/baeldung/Striped64.java new file mode 100644 index 0000000000..d305c334e0 --- /dev/null +++ b/jmh/src/main/java/com/baeldung/Striped64.java @@ -0,0 +1,393 @@ +package com.baeldung; + +import sun.misc.Unsafe; + +import java.lang.reflect.Field; +import java.util.function.LongBinaryOperator; +import java.util.function.DoubleBinaryOperator; +import java.util.concurrent.ThreadLocalRandom; + +/** + * A package-local class holding common representation and mechanics + * for classes supporting dynamic striping on 64bit values. The class + * extends Number so that concrete subclasses must publicly do so. + */ +@SuppressWarnings("serial") +abstract class Striped64 extends Number { + /* + * This class maintains a lazily-initialized table of atomically + * updated variables, plus an extra "base" field. The table size + * is a power of two. Indexing uses masked per-thread hash codes. + * Nearly all declarations in this class are package-private, + * accessed directly by subclasses. + * + * Table entries are of class Cell; a variant of AtomicLong padded + * (via @sun.misc.Contended) to reduce cache contention. Padding + * is overkill for most Atomics because they are usually + * irregularly scattered in memory and thus don't interfere much + * with each other. But Atomic objects residing in arrays will + * tend to be placed adjacent to each other, and so will most + * often share cache lines (with a huge negative performance + * impact) without this precaution. + * + * In part because Cells are relatively large, we avoid creating + * them until they are needed. When there is no contention, all + * updates are made to the base field. Upon first contention (a + * failed CAS on base update), the table is initialized to size 2. + * The table size is doubled upon further contention until + * reaching the nearest power of two greater than or equal to the + * number of CPUS. Table slots remain empty (null) until they are + * needed. + * + * A single spinlock ("cellsBusy") is used for initializing and + * resizing the table, as well as populating slots with new Cells. + * There is no need for a blocking lock; when the lock is not + * available, threads try other slots (or the base). During these + * retries, there is increased contention and reduced locality, + * which is still better than alternatives. + * + * The Thread probe fields maintained via ThreadLocalRandom serve + * as per-thread hash codes. We let them remain uninitialized as + * zero (if they come in this way) until they contend at slot + * 0. They are then initialized to values that typically do not + * often conflict with others. Contention and/or table collisions + * are indicated by failed CASes when performing an update + * operation. Upon a collision, if the table size is less than + * the capacity, it is doubled in size unless some other thread + * holds the lock. If a hashed slot is empty, and lock is + * available, a new Cell is created. Otherwise, if the slot + * exists, a CAS is tried. Retries proceed by "double hashing", + * using a secondary hash (Marsaglia XorShift) to try to find a + * free slot. + * + * The table size is capped because, when there are more threads + * than CPUs, supposing that each thread were bound to a CPU, + * there would exist a perfect hash function mapping threads to + * slots that eliminates collisions. When we reach capacity, we + * search for this mapping by randomly varying the hash codes of + * colliding threads. Because search is random, and collisions + * only become known via CAS failures, convergence can be slow, + * and because threads are typically not bound to CPUS forever, + * may not occur at all. However, despite these limitations, + * observed contention rates are typically low in these cases. + * + * It is possible for a Cell to become unused when threads that + * once hashed to it terminate, as well as in the case where + * doubling the table causes no thread to hash to it under + * expanded mask. We do not try to detect or remove such cells, + * under the assumption that for long-running instances, observed + * contention levels will recur, so the cells will eventually be + * needed again; and for short-lived ones, it does not matter. + */ + + /** + * Padded variant of AtomicLong supporting only raw accesses plus CAS. + * + * JVM intrinsics note: It would be possible to use a release-only + * form of CAS here, if it were provided. + */ + @sun.misc.Contended static final class Cell { + volatile long value; + Cell(long x) { value = x; } + final boolean cas(long cmp, long val) { + return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val); + } + + // Unsafe mechanics + private static final sun.misc.Unsafe UNSAFE; + private static final long valueOffset; + static { + try { + UNSAFE = getUnsafe(); + Class ak = Striped64.Cell.class; + valueOffset = UNSAFE.objectFieldOffset + (ak.getDeclaredField("value")); + } catch (Exception e) { + throw new Error(e); + } + } + } + + /** Number of CPUS, to place bound on table size */ + static final int NCPU = Runtime.getRuntime().availableProcessors(); + + /** + * Table of cells. When non-null, size is a power of 2. + */ + transient volatile Striped64.Cell[] cells; + + /** + * Base value, used mainly when there is no contention, but also as + * a fallback during table initialization races. Updated via CAS. + */ + transient volatile long base; + + /** + * Spinlock (locked via CAS) used when resizing and/or creating Cells. + */ + transient volatile int cellsBusy; + + /** + * Package-private default constructor + */ + Striped64() { + } + + /** + * CASes the base field. + */ + final boolean casBase(long cmp, long val) { + return UNSAFE.compareAndSwapLong(this, BASE, cmp, val); + } + + /** + * CASes the cellsBusy field from 0 to 1 to acquire lock. + */ + final boolean casCellsBusy() { + return UNSAFE.compareAndSwapInt(this, CELLSBUSY, 0, 1); + } + + /** + * Returns the probe value for the current thread. + * Duplicated from ThreadLocalRandom because of packaging restrictions. + */ + static final int getProbe() { + return UNSAFE.getInt(Thread.currentThread(), PROBE); + } + + /** + * Pseudo-randomly advances and records the given probe value for the + * given thread. + * Duplicated from ThreadLocalRandom because of packaging restrictions. + */ + static final int advanceProbe(int probe) { + probe ^= probe << 13; // xorshift + probe ^= probe >>> 17; + probe ^= probe << 5; + UNSAFE.putInt(Thread.currentThread(), PROBE, probe); + return probe; + } + + /** + * Handles cases of updates involving initialization, resizing, + * creating new Cells, and/or contention. See above for + * explanation. This method suffers the usual non-modularity + * problems of optimistic retry code, relying on rechecked sets of + * reads. + * + * @param x the value + * @param fn the update function, or null for add (this convention + * avoids the need for an extra field or function in LongAdder). + * @param wasUncontended false if CAS failed before call + */ + final void longAccumulate(long x, LongBinaryOperator fn, + boolean wasUncontended) { + int h; + if ((h = getProbe()) == 0) { + ThreadLocalRandom.current(); // force initialization + h = getProbe(); + wasUncontended = true; + } + boolean collide = false; // True if last slot nonempty + for (;;) { + Striped64.Cell[] as; Striped64.Cell a; int n; long v; + if ((as = cells) != null && (n = as.length) > 0) { + if ((a = as[(n - 1) & h]) == null) { + if (cellsBusy == 0) { // Try to attach new Cell + Striped64.Cell r = new Striped64.Cell(x); // Optimistically create + if (cellsBusy == 0 && casCellsBusy()) { + boolean created = false; + try { // Recheck under lock + Striped64.Cell[] rs; int m, j; + if ((rs = cells) != null && + (m = rs.length) > 0 && + rs[j = (m - 1) & h] == null) { + rs[j] = r; + created = true; + } + } finally { + cellsBusy = 0; + } + if (created) + break; + continue; // Slot is now non-empty + } + } + collide = false; + } + else if (!wasUncontended) // CAS already known to fail + wasUncontended = true; // Continue after rehash + else if (a.cas(v = a.value, ((fn == null) ? v + x : + fn.applyAsLong(v, x)))) + break; + else if (n >= NCPU || cells != as) + collide = false; // At max size or stale + else if (!collide) + collide = true; + else if (cellsBusy == 0 && casCellsBusy()) { + try { + if (cells == as) { // Expand table unless stale + Striped64.Cell[] rs = new Striped64.Cell[n << 1]; + for (int i = 0; i < n; ++i) + rs[i] = as[i]; + cells = rs; + } + } finally { + cellsBusy = 0; + } + collide = false; + continue; // Retry with expanded table + } + h = advanceProbe(h); + } + else if (cellsBusy == 0 && cells == as && casCellsBusy()) { + boolean init = false; + try { // Initialize table + if (cells == as) { + Striped64.Cell[] rs = new Striped64.Cell[2]; + rs[h & 1] = new Striped64.Cell(x); + cells = rs; + init = true; + } + } finally { + cellsBusy = 0; + } + if (init) + break; + } + else if (casBase(v = base, ((fn == null) ? v + x : + fn.applyAsLong(v, x)))) + break; // Fall back on using base + } + } + + /** + * Same as longAccumulate, but injecting long/double conversions + * in too many places to sensibly merge with long version, given + * the low-overhead requirements of this class. So must instead be + * maintained by copy/paste/adapt. + */ + final void doubleAccumulate(double x, DoubleBinaryOperator fn, + boolean wasUncontended) { + int h; + if ((h = getProbe()) == 0) { + ThreadLocalRandom.current(); // force initialization + h = getProbe(); + wasUncontended = true; + } + boolean collide = false; // True if last slot nonempty + for (;;) { + Striped64.Cell[] as; Striped64.Cell a; int n; long v; + if ((as = cells) != null && (n = as.length) > 0) { + if ((a = as[(n - 1) & h]) == null) { + if (cellsBusy == 0) { // Try to attach new Cell + Striped64.Cell r = new Striped64.Cell(Double.doubleToRawLongBits(x)); + if (cellsBusy == 0 && casCellsBusy()) { + boolean created = false; + try { // Recheck under lock + Striped64.Cell[] rs; int m, j; + if ((rs = cells) != null && + (m = rs.length) > 0 && + rs[j = (m - 1) & h] == null) { + rs[j] = r; + created = true; + } + } finally { + cellsBusy = 0; + } + if (created) + break; + continue; // Slot is now non-empty + } + } + collide = false; + } + else if (!wasUncontended) // CAS already known to fail + wasUncontended = true; // Continue after rehash + else if (a.cas(v = a.value, + ((fn == null) ? + Double.doubleToRawLongBits + (Double.longBitsToDouble(v) + x) : + Double.doubleToRawLongBits + (fn.applyAsDouble + (Double.longBitsToDouble(v), x))))) + break; + else if (n >= NCPU || cells != as) + collide = false; // At max size or stale + else if (!collide) + collide = true; + else if (cellsBusy == 0 && casCellsBusy()) { + try { + if (cells == as) { // Expand table unless stale + Striped64.Cell[] rs = new Striped64.Cell[n << 1]; + for (int i = 0; i < n; ++i) + rs[i] = as[i]; + cells = rs; + } + } finally { + cellsBusy = 0; + } + collide = false; + continue; // Retry with expanded table + } + h = advanceProbe(h); + } + else if (cellsBusy == 0 && cells == as && casCellsBusy()) { + boolean init = false; + try { // Initialize table + if (cells == as) { + Striped64.Cell[] rs = new Striped64.Cell[2]; + rs[h & 1] = new Striped64.Cell(Double.doubleToRawLongBits(x)); + cells = rs; + init = true; + } + } finally { + cellsBusy = 0; + } + if (init) + break; + } + else if (casBase(v = base, + ((fn == null) ? + Double.doubleToRawLongBits + (Double.longBitsToDouble(v) + x) : + Double.doubleToRawLongBits + (fn.applyAsDouble + (Double.longBitsToDouble(v), x))))) + break; // Fall back on using base + } + } + + // Unsafe mechanics + private static final sun.misc.Unsafe UNSAFE; + private static final long BASE; + private static final long CELLSBUSY; + private static final long PROBE; + static { + try { + UNSAFE = getUnsafe(); + Class sk = Striped64.class; + BASE = UNSAFE.objectFieldOffset + (sk.getDeclaredField("base")); + CELLSBUSY = UNSAFE.objectFieldOffset + (sk.getDeclaredField("cellsBusy")); + Class tk = Thread.class; + PROBE = UNSAFE.objectFieldOffset + (tk.getDeclaredField("threadLocalRandomProbe")); + } catch (Exception e) { + throw new Error(e); + } + } + + private static Unsafe getUnsafe() { + try { + Field field = Unsafe.class.getDeclaredField("theUnsafe"); + field.setAccessible(true); + + return (Unsafe) field.get(null); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} \ No newline at end of file From 34d2e20e56029b05f6da6b510f2ab9d87e7ebf10 Mon Sep 17 00:00:00 2001 From: mikr Date: Wed, 15 Jul 2020 12:33:27 +0200 Subject: [PATCH 024/132] JAVA-2096 Update "Create File" article --- core-java-modules/core-java-io-2/README.md | 2 +- core-java-modules/core-java-io-3/README.md | 7 ++ core-java-modules/core-java-io-3/pom.xml | 86 +++++++++++++++++++ .../createfile/CreateFileUnitTest.java | 50 +++++++++++ core-java-modules/pom.xml | 1 + 5 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-io-3/README.md create mode 100644 core-java-modules/core-java-io-3/pom.xml create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/createfile/CreateFileUnitTest.java diff --git a/core-java-modules/core-java-io-2/README.md b/core-java-modules/core-java-io-2/README.md index 84cabc5992..b078a66a7a 100644 --- a/core-java-modules/core-java-io-2/README.md +++ b/core-java-modules/core-java-io-2/README.md @@ -13,4 +13,4 @@ This module contains articles about core Java input and output (IO) - [How to Copy a File with Java](https://www.baeldung.com/java-copy-file) - [Create a Directory in Java](https://www.baeldung.com/java-create-directory) - [Java IO vs NIO](https://www.baeldung.com/java-io-vs-nio) -- [[<-- Prev]](/core-java-modules/core-java-io) +- [[<-- Prev]](/core-java-modules/core-java-io)[[More -->]](/core-java-modules/core-java-io-3) diff --git a/core-java-modules/core-java-io-3/README.md b/core-java-modules/core-java-io-3/README.md new file mode 100644 index 0000000000..39752346d3 --- /dev/null +++ b/core-java-modules/core-java-io-3/README.md @@ -0,0 +1,7 @@ +## Core Java IO + +This module contains articles about core Java input and output (IO) + +### Relevant Articles: +- [Java – Create a File](https://www.baeldung.com/java-how-to-create-a-file) +- [[<-- Prev]](/core-java-modules/core-java-io-2) diff --git a/core-java-modules/core-java-io-3/pom.xml b/core-java-modules/core-java-io-3/pom.xml new file mode 100644 index 0000000000..cb341ca2ae --- /dev/null +++ b/core-java-modules/core-java-io-3/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + core-java-io-3 + 0.1.0-SNAPSHOT + core-java-io-3 + jar + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + ../ + + + + + + com.google.guava + guava + ${guava.version} + + + + commons-io + commons-io + ${commons-io.version} + + + + log4j + log4j + ${log4j.version} + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + com.github.tomakehurst + wiremock + ${wiremock.version} + test + + + + + + core-java-io-3 + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 3.6.1 + 3.0.0-M1 + 2.26.3 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/createfile/CreateFileUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/createfile/CreateFileUnitTest.java new file mode 100644 index 0000000000..f3cdb22f4d --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/createfile/CreateFileUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.createfile; + +import org.apache.commons.io.FileUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class CreateFileUnitTest { + + private final String FILE_NAME = "src/test/resources/fileToCreate.txt"; + + @AfterEach + @BeforeEach + public void cleanUpFiles() { + File targetFile = new File(FILE_NAME); + targetFile.delete(); + } + + @Test + public void givenUsingNio_whenCreatingFile_thenCorrect() throws IOException { + Path newFilePath = Paths.get(FILE_NAME); + Files.createFile(newFilePath); + } + + @Test + public void givenUsingFile_whenCreatingFile_thenCorrect() throws IOException { + File newFile = new File(FILE_NAME); + boolean success = newFile.createNewFile(); + assertTrue(success); + } + + @Test + public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException { + com.google.common.io.Files.touch(new File(FILE_NAME)); + } + + @Test + public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException { + FileUtils.touch(new File(FILE_NAME)); + } + +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 03b15f60d6..589097cf48 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -72,6 +72,7 @@ core-java-io core-java-io-2 + core-java-io-3 core-java-io-apis core-java-io-conversions core-java-io-conversions-2 From 05446fb887c488d11e3944cd1e3ed7f5b0f1b8eb Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 15 Jul 2020 17:24:34 +0530 Subject: [PATCH 025/132] JAVA-628: Moved 3 articles from spring-core --- spring-core/README.md | 4 +- .../com/baeldung/lombok/ApologizeService.java | 22 --------- .../com/baeldung/lombok/FarewellService.java | 18 -------- .../com/baeldung/lombok/GreetingService.java | 15 ------- .../com/baeldung/lombok/ThankingService.java | 15 ------- .../java/com/baeldung/lombok/Translator.java | 5 --- ...pplicationContextTestResourceNameType.java | 16 ------- ...plicationContextTestResourceQualifier.java | 22 --------- ...ogizeServiceAutowiringIntegrationTest.java | 33 -------------- .../ApologizeServiceIntegrationTest.java | 21 --------- .../FarewellAutowiringIntegrationTest.java | 31 ------------- .../FarewellServiceIntegrationTest.java | 20 --------- .../GreetingServiceIntegrationTest.java | 37 --------------- .../java/com/baeldung/lombok/TestConfig.java | 17 ------- ...nkingServiceAutowiringIntegrationTest.java | 31 ------------- .../ThankingServiceIntegrationTest.java | 20 --------- ...FieldResourceInjectionIntegrationTest.java | 30 ------------- ...hodByQualifierResourceIntegrationTest.java | 45 ------------------- .../MethodByTypeResourceIntegrationTest.java | 34 -------------- ...ethodResourceInjectionIntegrationTest.java | 34 -------------- .../NamedResourceIntegrationTest.java | 29 ------------ ...ifierResourceInjectionIntegrationTest.java | 42 ----------------- ...etterResourceInjectionIntegrationTest.java | 33 -------------- 23 files changed, 1 insertion(+), 573 deletions(-) delete mode 100644 spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java delete mode 100644 spring-core/src/main/java/com/baeldung/lombok/FarewellService.java delete mode 100644 spring-core/src/main/java/com/baeldung/lombok/GreetingService.java delete mode 100644 spring-core/src/main/java/com/baeldung/lombok/ThankingService.java delete mode 100644 spring-core/src/main/java/com/baeldung/lombok/Translator.java delete mode 100644 spring-core/src/test/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java delete mode 100644 spring-core/src/test/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java delete mode 100644 spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/lombok/TestConfig.java delete mode 100644 spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java diff --git a/spring-core/README.md b/spring-core/README.md index 1f3dcb783b..b8d46f6b34 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -3,10 +3,8 @@ This module contains articles about core Spring functionality ### Relevant Articles: -- [Wiring in Spring: @Autowired, @Resource and @Inject](https://www.baeldung.com/spring-annotations-resource-inject-autowire) -- [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok) + - [Introduction to Spring’s StreamUtils](https://www.baeldung.com/spring-stream-utils) -- [XML-Based Injection in Spring](https://www.baeldung.com/spring-xml-injection) - [A Quick Guide to the Spring @Lazy Annotation](https://www.baeldung.com/spring-lazy-annotation) - [BeanNameAware and BeanFactoryAware Interfaces in Spring](https://www.baeldung.com/spring-bean-name-factory-aware) - [Access a File from the Classpath in a Spring Application](https://www.baeldung.com/spring-classpath-file-access) diff --git a/spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java b/spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java deleted file mode 100644 index 76c3df8217..0000000000 --- a/spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.lombok; - -import lombok.RequiredArgsConstructor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -@RequiredArgsConstructor -public class ApologizeService { - - private final Translator translator; - private final String message; - - @Autowired - public ApologizeService(Translator translator) { - this(translator, "sorry"); - } - - public String apologize() { - return translator.translate(message); - } -} diff --git a/spring-core/src/main/java/com/baeldung/lombok/FarewellService.java b/spring-core/src/main/java/com/baeldung/lombok/FarewellService.java deleted file mode 100644 index 4e8c4993cb..0000000000 --- a/spring-core/src/main/java/com/baeldung/lombok/FarewellService.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.lombok; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class FarewellService { - - private final Translator translator; - - public FarewellService(Translator translator) { - this.translator = translator; - } - - public String farewell() { - return translator.translate("bye"); - } -} diff --git a/spring-core/src/main/java/com/baeldung/lombok/GreetingService.java b/spring-core/src/main/java/com/baeldung/lombok/GreetingService.java deleted file mode 100644 index 0e03e177e1..0000000000 --- a/spring-core/src/main/java/com/baeldung/lombok/GreetingService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.lombok; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class GreetingService { - - @Autowired - private Translator translator; - - public String greet() { - return translator.translate("hello"); - } -} diff --git a/spring-core/src/main/java/com/baeldung/lombok/ThankingService.java b/spring-core/src/main/java/com/baeldung/lombok/ThankingService.java deleted file mode 100644 index 2e0c398d2d..0000000000 --- a/spring-core/src/main/java/com/baeldung/lombok/ThankingService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.lombok; - -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -@Component -@RequiredArgsConstructor -public class ThankingService { - - private final Translator translator; - - public String thank() { - return translator.translate("thank you"); - } -} diff --git a/spring-core/src/main/java/com/baeldung/lombok/Translator.java b/spring-core/src/main/java/com/baeldung/lombok/Translator.java deleted file mode 100644 index 2dea20b726..0000000000 --- a/spring-core/src/main/java/com/baeldung/lombok/Translator.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.lombok; - -public interface Translator { - String translate(String input); -} diff --git a/spring-core/src/test/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java b/spring-core/src/test/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java deleted file mode 100644 index cb1b5981e8..0000000000 --- a/spring-core/src/test/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.configuration; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.io.File; - -@Configuration -public class ApplicationContextTestResourceNameType { - - @Bean(name = "namedFile") - public File namedFile() { - File namedFile = new File("namedFile.txt"); - return namedFile; - } -} diff --git a/spring-core/src/test/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java b/spring-core/src/test/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java deleted file mode 100644 index c9aa2f4a7d..0000000000 --- a/spring-core/src/test/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.configuration; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.io.File; - -@Configuration -public class ApplicationContextTestResourceQualifier { - - @Bean(name = "defaultFile") - public File defaultFile() { - File defaultFile = new File("defaultFile.txt"); - return defaultFile; - } - - @Bean(name = "namedFile") - public File namedFile() { - File namedFile = new File("namedFile.txt"); - return namedFile; - } -} diff --git a/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java deleted file mode 100644 index a49dd84f11..0000000000 --- a/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.lombok; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = TestConfig.class) -public class ApologizeServiceAutowiringIntegrationTest { - - private final static String TRANSLATED = "TRANSLATED"; - - @Autowired - private ApologizeService apologizeService; - - @Autowired - private Translator translator; - - @Test - public void apologizeWithTranslatedMessage() { - when(translator.translate("sorry")).thenReturn(TRANSLATED); - assertEquals(TRANSLATED, apologizeService.apologize()); - } - -} \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java deleted file mode 100644 index 77f0c94299..0000000000 --- a/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.lombok; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class ApologizeServiceIntegrationTest { - - private final static String MESSAGE = "MESSAGE"; - private final static String TRANSLATED = "TRANSLATED"; - - @Test - public void apologizeWithCustomTranslatedMessage() { - Translator translator = mock(Translator.class); - ApologizeService apologizeService = new ApologizeService(translator, MESSAGE); - when(translator.translate(MESSAGE)).thenReturn(TRANSLATED); - assertEquals(TRANSLATED, apologizeService.apologize()); - } -} diff --git a/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java b/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java deleted file mode 100644 index ec0793bd2e..0000000000 --- a/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.lombok; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = TestConfig.class) -public class FarewellAutowiringIntegrationTest { - - @Autowired - private FarewellService farewellService; - - @Autowired - private Translator translator; - - @Test - public void sayByeWithTranslatedMessage() { - String translated = "translated"; - when(translator.translate("bye")).thenReturn(translated); - assertEquals(translated, farewellService.farewell()); - } -} diff --git a/spring-core/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java deleted file mode 100644 index 38959a511f..0000000000 --- a/spring-core/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.lombok; - -import org.junit.Test; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class FarewellServiceIntegrationTest { - - private final static String TRANSLATED = "TRANSLATED"; - - @Test - public void sayByeWithTranslatedMessage() { - Translator translator = mock(Translator.class); - when(translator.translate("bye")).thenReturn(TRANSLATED); - FarewellService farewellService = new FarewellService(translator); - assertEquals(TRANSLATED, farewellService.farewell()); - } -} \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java deleted file mode 100644 index 0516b5eb56..0000000000 --- a/spring-core/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.lombok; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = TestConfig.class) -public class GreetingServiceIntegrationTest { - - @Autowired - private GreetingService greetingService; - - @Autowired - private Translator translator; - - @Test - public void greetWithTranslatedMessage() { - String translated = "translated"; - when(translator.translate("hello")).thenReturn(translated); - assertEquals(translated, greetingService.greet()); - } - - @Test(expected = NullPointerException.class) - public void throwWhenInstantiated() { - GreetingService greetingService = new GreetingService(); - greetingService.greet(); - } -} \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/TestConfig.java b/spring-core/src/test/java/com/baeldung/lombok/TestConfig.java deleted file mode 100644 index 3278a8188f..0000000000 --- a/spring-core/src/test/java/com/baeldung/lombok/TestConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.lombok; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -import static org.mockito.Mockito.mock; - -@Configuration -@ComponentScan("com.baeldung.lombok") -class TestConfig { - - @Bean - public Translator mockTranslator() { - return mock(Translator.class); - } -} diff --git a/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java deleted file mode 100644 index fb9abbad46..0000000000 --- a/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.lombok; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = TestConfig.class) -public class ThankingServiceAutowiringIntegrationTest { - - @Autowired - private ThankingService thankingService; - - @Autowired - private Translator translator; - - @Test - public void thankWithTranslatedMessage() { - String translated = "translated"; - when(translator.translate("thank you")).thenReturn(translated); - assertEquals(translated, thankingService.thank()); - } -} \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java deleted file mode 100644 index 680f926717..0000000000 --- a/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.lombok; - -import org.junit.Test; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class ThankingServiceIntegrationTest { - - private final static String TRANSLATED = "TRANSLATED"; - - @Test - public void thankWithTranslatedMessage() { - Translator translator = mock(Translator.class); - when(translator.translate("thank you")).thenReturn(TRANSLATED); - ThankingService thankingService = new ThankingService(translator); - assertEquals(TRANSLATED, thankingService.thank()); - } -} \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java deleted file mode 100644 index 63a25cb499..0000000000 --- a/spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.resource; - -import com.baeldung.configuration.ApplicationContextTestResourceNameType; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.annotation.Resource; -import java.io.File; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestResourceNameType.class) -public class FieldResourceInjectionIntegrationTest { - - @Resource(name = "namedFile") - private File defaultFile; - - @Test - public void givenResourceAnnotation_WhenOnField_ThenDependencyValid() { - assertNotNull(defaultFile); - assertEquals("namedFile.txt", defaultFile.getName()); - } -} diff --git a/spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java deleted file mode 100644 index f5bb9f10cf..0000000000 --- a/spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.resource; - -import com.baeldung.configuration.ApplicationContextTestResourceQualifier; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.annotation.Resource; -import java.io.File; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestResourceQualifier.class) -public class MethodByQualifierResourceIntegrationTest { - - private File arbDependency; - private File anotherArbDependency; - - @Test - public void givenResourceQualifier_WhenSetter_ThenValidDependencies() { - assertNotNull(arbDependency); - assertEquals("namedFile.txt", arbDependency.getName()); - assertNotNull(anotherArbDependency); - assertEquals("defaultFile.txt", anotherArbDependency.getName()); - } - - @Resource - @Qualifier("namedFile") - public void setArbDependency(File arbDependency) { - this.arbDependency = arbDependency; - } - - @Resource - @Qualifier("defaultFile") - public void setAnotherArbDependency(File anotherArbDependency) { - this.anotherArbDependency = anotherArbDependency; - } -} diff --git a/spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java deleted file mode 100644 index 171cbfea47..0000000000 --- a/spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.resource; - -import com.baeldung.configuration.ApplicationContextTestResourceNameType; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.annotation.Resource; -import java.io.File; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestResourceNameType.class) -public class MethodByTypeResourceIntegrationTest { - - private File defaultFile; - - @Resource - protected void setDefaultFile(File defaultFile) { - this.defaultFile = defaultFile; - } - - @Test - public void givenResourceAnnotation_WhenSetter_ThenValidDependency() { - assertNotNull(defaultFile); - assertEquals("namedFile.txt", defaultFile.getName()); - } -} diff --git a/spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java deleted file mode 100644 index 2e1c3c39a9..0000000000 --- a/spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.resource; - -import com.baeldung.configuration.ApplicationContextTestResourceNameType; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.annotation.Resource; -import java.io.File; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestResourceNameType.class) -public class MethodResourceInjectionIntegrationTest { - - private File defaultFile; - - @Resource(name = "namedFile") - protected void setDefaultFile(File defaultFile) { - this.defaultFile = defaultFile; - } - - @Test - public void givenResourceAnnotation_WhenSetter_ThenDependencyValid() { - assertNotNull(defaultFile); - assertEquals("namedFile.txt", defaultFile.getName()); - } -} diff --git a/spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java deleted file mode 100644 index d52660e9b8..0000000000 --- a/spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.resource; - -import com.baeldung.configuration.ApplicationContextTestResourceNameType; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.annotation.Resource; -import java.io.File; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestResourceNameType.class) -public class NamedResourceIntegrationTest { - - @Resource(name = "namedFile") - private File testFile; - - @Test - public void givenResourceAnnotation_WhenOnField_THEN_DEPENDENCY_Found() { - assertNotNull(testFile); - assertEquals("namedFile.txt", testFile.getName()); - } -} diff --git a/spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java deleted file mode 100644 index 3f812350c9..0000000000 --- a/spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.resource; - -import com.baeldung.configuration.ApplicationContextTestResourceQualifier; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.annotation.Resource; -import java.io.File; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestResourceQualifier.class) -public class QualifierResourceInjectionIntegrationTest { - - @Resource - @Qualifier("defaultFile") - private File dependency1; - - @Resource - @Qualifier("namedFile") - private File dependency2; - - @Test - public void givenResourceAnnotation_WhenField_ThenDependency1Valid() { - assertNotNull(dependency1); - assertEquals("defaultFile.txt", dependency1.getName()); - } - - @Test - public void givenResourceQualifier_WhenField_ThenDependency2Valid() { - assertNotNull(dependency2); - assertEquals("namedFile.txt", dependency2.getName()); - } -} diff --git a/spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java deleted file mode 100644 index ae13b2336a..0000000000 --- a/spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.resource; - -import com.baeldung.configuration.ApplicationContextTestResourceNameType; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.annotation.Resource; -import java.io.File; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestResourceNameType.class) -public class SetterResourceInjectionIntegrationTest { - - private File defaultFile; - - @Resource - protected void setDefaultFile(File defaultFile) { - this.defaultFile = defaultFile; - } - - @Test - public void givenResourceAnnotation_WhenOnSetter_THEN_MUST_INJECT_Dependency() { - assertNotNull(defaultFile); - assertEquals("namedFile.txt", defaultFile.getName()); - } -} From cf4ed21884090db86ff4b86ace4b506193b5a2c2 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 15 Jul 2020 17:25:43 +0530 Subject: [PATCH 026/132] JAVA-628: Moved 4 articles from spring-core-2 --- spring-core-2/README.md | 4 - .../CustomAnnotationConfiguration.java | 9 -- .../baeldung/customannotation/DataAccess.java | 14 --- .../DataAccessAnnotationProcessor.java | 37 ------- .../DataAccessFieldCallback.java | 96 ------------------- .../baeldung/customannotation/GenericDAO.java | 30 ------ .../com/baeldung/customscope/TenantBean.java | 14 --- .../TenantBeanFactoryPostProcessor.java | 13 --- .../customscope/TenantBeansConfig.java | 21 ---- .../com/baeldung/customscope/TenantScope.java | 43 --------- .../customscope/TenantScopeConfig.java | 14 --- .../baeldung/sampleabstract/BallService.java | 28 ------ .../sampleabstract/BasketballService.java | 13 --- .../com/baeldung/sampleabstract/DemoApp.java | 18 ---- .../sampleabstract/LogRepository.java | 12 --- .../sampleabstract/RuleRepository.java | 12 --- .../startup/AllStrategiesExampleBean.java | 35 ------- .../startup/EventListenerExampleBean.java | 21 ---- .../startup/InitMethodExampleBean.java | 24 ----- .../startup/InitializingBeanExampleBean.java | 26 ----- .../startup/InvalidInitExampleBean.java | 18 ---- .../LogicInConstructorExampleBean.java | 22 ----- .../startup/PostConstructExampleBean.java | 27 ------ .../baeldung/startup/SpringStartupConfig.java | 9 -- .../StartupApplicationListenerExample.java | 22 ----- .../src/main/resources/startupConfig.xml | 16 ---- .../baeldung/customannotation/Account.java | 40 -------- .../customannotation/BeanWithGenericDAO.java | 18 ---- .../DataAccessAnnotationIntegrationTest.java | 57 ----------- ...ataAccessFieldCallbackIntegrationTest.java | 51 ---------- .../com/baeldung/customannotation/Person.java | 31 ------ .../TenantScopeIntegrationTest.java | 72 -------------- .../startup/SpringStartupIntegrationTest.java | 44 --------- ...SpringStartupXMLConfigIntegrationTest.java | 26 ----- 34 files changed, 937 deletions(-) delete mode 100644 spring-core-2/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/customannotation/DataAccess.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/customannotation/GenericDAO.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/customscope/TenantBean.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/customscope/TenantBeansConfig.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/customscope/TenantScope.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/customscope/TenantScopeConfig.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/sampleabstract/BallService.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/sampleabstract/BasketballService.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/sampleabstract/DemoApp.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/sampleabstract/LogRepository.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/sampleabstract/RuleRepository.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/startup/EventListenerExampleBean.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/startup/InitMethodExampleBean.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/startup/PostConstructExampleBean.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/startup/SpringStartupConfig.java delete mode 100644 spring-core-2/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java delete mode 100644 spring-core-2/src/main/resources/startupConfig.xml delete mode 100644 spring-core-2/src/test/java/com/baeldung/customannotation/Account.java delete mode 100644 spring-core-2/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java delete mode 100644 spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java delete mode 100644 spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java delete mode 100644 spring-core-2/src/test/java/com/baeldung/customannotation/Person.java delete mode 100644 spring-core-2/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java delete mode 100644 spring-core-2/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java delete mode 100644 spring-core-2/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java diff --git a/spring-core-2/README.md b/spring-core-2/README.md index 10d3080b45..3c6bd05876 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -6,13 +6,9 @@ This module contains articles about core Spring functionality - [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire) - [Spring Profiles](http://www.baeldung.com/spring-profiles) -- [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) -- [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope) - [@Order in Spring](http://www.baeldung.com/spring-order) - [Spring @Primary Annotation](http://www.baeldung.com/spring-primary) - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) -- [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) -- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) - More articles: [[<-- prev]](/spring-core)[[next -->]](/spring-core-3) diff --git a/spring-core-2/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java b/spring-core-2/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java deleted file mode 100644 index 2e42a3f744..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.customannotation; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("com.baeldung.customannotation") -public class CustomAnnotationConfiguration { -} diff --git a/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccess.java b/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccess.java deleted file mode 100644 index 4160bad16d..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccess.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.customannotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) -@Documented -public @interface DataAccess { - Class entity(); -} diff --git a/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java b/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java deleted file mode 100644 index 27008176a8..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.customannotation; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.stereotype.Component; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.FieldCallback; - -@Component -public class DataAccessAnnotationProcessor implements BeanPostProcessor { - - private ConfigurableListableBeanFactory configurableListableBeanFactory; - - @Autowired - public DataAccessAnnotationProcessor(ConfigurableListableBeanFactory bf) { - configurableListableBeanFactory = bf; - } - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - scanDataAccessAnnotation(bean, beanName); - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - return bean; - } - - protected void scanDataAccessAnnotation(Object bean, String beanName) { - Class managedBeanClass = bean.getClass(); - FieldCallback fcb = new DataAccessFieldCallback(configurableListableBeanFactory, bean); - ReflectionUtils.doWithFields(managedBeanClass, fcb); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java b/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java deleted file mode 100644 index 07b5298ea9..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.baeldung.customannotation; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.FieldCallback; - -public final class DataAccessFieldCallback implements FieldCallback { - - private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class); - private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; - - private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + "value should have same type with injected generic type."; - private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " + "to raw (non-generic) declaration. This will make your code less type-safe."; - private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " + "type '{}' or instance creation is failed because: {}"; - - private ConfigurableListableBeanFactory configurableListableBeanFactory; - private Object bean; - - public DataAccessFieldCallback(final ConfigurableListableBeanFactory bf, final Object bean) { - configurableListableBeanFactory = bf; - this.bean = bean; - } - - @Override - public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { - if (!field.isAnnotationPresent(DataAccess.class)) { - return; - } - ReflectionUtils.makeAccessible(field); - final Type fieldGenericType = field.getGenericType(); - // In this example, get actual "GenericDAO' type. - final Class generic = field.getType(); - final Class classValue = field.getDeclaredAnnotation(DataAccess.class).entity(); - - if (genericTypeIsValid(classValue, fieldGenericType)) { - final String beanName = classValue.getSimpleName() + generic.getSimpleName(); - final Object beanInstance = getBeanInstance(beanName, generic, classValue); - field.set(bean, beanInstance); - } else { - throw new IllegalArgumentException(ERROR_ENTITY_VALUE_NOT_SAME); - } - } - - /** - * For example, if user write: - *

-     * @DataAccess(entity=Person.class) 
-     * private GenericDAO<Account> personGenericDAO;
-     * 
- * then this is should be failed. - */ - public boolean genericTypeIsValid(final Class clazz, final Type field) { - if (field instanceof ParameterizedType) { - final ParameterizedType parameterizedType = (ParameterizedType) field; - final Type type = parameterizedType.getActualTypeArguments()[0]; - - return type.equals(clazz); - } else { - logger.warn(WARN_NON_GENERIC_VALUE); - return true; - } - } - - public final Object getBeanInstance(final String beanName, final Class genericClass, final Class paramClass) { - Object daoInstance = null; - if (!configurableListableBeanFactory.containsBean(beanName)) { - logger.info("Creating new DataAccess bean named '{}'.", beanName); - - Object toRegister = null; - try { - final Constructor ctr = genericClass.getConstructor(Class.class); - toRegister = ctr.newInstance(paramClass); - } catch (final Exception e) { - logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e); - throw new RuntimeException(e); - } - - daoInstance = configurableListableBeanFactory.initializeBean(toRegister, beanName); - configurableListableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true); - configurableListableBeanFactory.registerSingleton(beanName, daoInstance); - logger.info("Bean named '{}' created successfully.", beanName); - } else { - daoInstance = configurableListableBeanFactory.getBean(beanName); - logger.info("Bean named '{}' already exist used as current bean reference.", beanName); - } - return daoInstance; - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/customannotation/GenericDAO.java b/spring-core-2/src/main/java/com/baeldung/customannotation/GenericDAO.java deleted file mode 100644 index 0edd33b049..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customannotation/GenericDAO.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.customannotation; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -public class GenericDAO { - - private Class entityClass; - private String message; - - public GenericDAO(Class entityClass) { - this.entityClass = entityClass; - } - - public List findAll() { - message = "Would create findAll query from " + entityClass.getSimpleName(); - return Collections.emptyList(); - } - - public Optional persist(E toPersist) { - message = "Would create persist query from " + toPersist.getClass().getSimpleName(); - return Optional.empty(); - } - - /** Only used for unit-testing. */ - public final String getMessage() { - return message; - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/customscope/TenantBean.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantBean.java deleted file mode 100644 index e892ae9d9b..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customscope/TenantBean.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.customscope; - -public class TenantBean { - - private final String name; - - public TenantBean(String name) { - this.name = name; - } - - public void sayHello() { - System.out.println(String.format("Hello from %s of type %s", this.name, this.getClass().getName())); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java deleted file mode 100644 index 84ed0b46d7..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.customscope; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; - -public class TenantBeanFactoryPostProcessor implements BeanFactoryPostProcessor { - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException { - factory.registerScope("tenant", new TenantScope()); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeansConfig.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeansConfig.java deleted file mode 100644 index c219000fe6..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeansConfig.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.customscope; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Scope; - -@Configuration -public class TenantBeansConfig { - - @Scope(scopeName = "tenant") - @Bean - public TenantBean foo() { - return new TenantBean("foo"); - } - - @Scope(scopeName = "tenant") - @Bean - public TenantBean bar() { - return new TenantBean("bar"); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/customscope/TenantScope.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantScope.java deleted file mode 100644 index f3077bc4c2..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customscope/TenantScope.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.customscope; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.springframework.beans.factory.ObjectFactory; -import org.springframework.beans.factory.config.Scope; - -public class TenantScope implements Scope { - - private Map scopedObjects = Collections.synchronizedMap(new HashMap()); - private Map destructionCallbacks = Collections.synchronizedMap(new HashMap()); - - @Override - public Object get(String name, ObjectFactory objectFactory) { - if (!scopedObjects.containsKey(name)) { - scopedObjects.put(name, objectFactory.getObject()); - } - return scopedObjects.get(name); - } - - @Override - public Object remove(String name) { - destructionCallbacks.remove(name); - return scopedObjects.remove(name); - } - - @Override - public void registerDestructionCallback(String name, Runnable callback) { - destructionCallbacks.put(name, callback); - } - - @Override - public Object resolveContextualObject(String key) { - return null; - } - - @Override - public String getConversationId() { - return "tenant"; - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/customscope/TenantScopeConfig.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantScopeConfig.java deleted file mode 100644 index 1829e1e8c4..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/customscope/TenantScopeConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.customscope; - -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class TenantScopeConfig { - - @Bean - public static BeanFactoryPostProcessor beanFactoryPostProcessor() { - return new TenantBeanFactoryPostProcessor(); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/sampleabstract/BallService.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/BallService.java deleted file mode 100644 index 0d951aac8b..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/sampleabstract/BallService.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.sampleabstract; - -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; - -public abstract class BallService { - - private RuleRepository ruleRepository; - - private LogRepository logRepository; - - public BallService(RuleRepository ruleRepository) { - this.ruleRepository = ruleRepository; - } - - @Autowired - public final void setLogRepository(LogRepository logRepository) { - this.logRepository = logRepository; - } - - @PostConstruct - public void afterInitialize() { - - System.out.println(ruleRepository.toString()); - System.out.println(logRepository.toString()); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/sampleabstract/BasketballService.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/BasketballService.java deleted file mode 100644 index 4d6345b069..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/sampleabstract/BasketballService.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.sampleabstract; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class BasketballService extends BallService { - - @Autowired - public BasketballService(RuleRepository ruleRepository) { - super(ruleRepository); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/sampleabstract/DemoApp.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/DemoApp.java deleted file mode 100644 index 5a308b2671..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/sampleabstract/DemoApp.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.sampleabstract; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages = "com.baeldung.sampleabstract") -public class DemoApp { - - - public static void main(String[] args) { - - ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApp.class); - } - -} diff --git a/spring-core-2/src/main/java/com/baeldung/sampleabstract/LogRepository.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/LogRepository.java deleted file mode 100644 index 84979768b5..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/sampleabstract/LogRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.sampleabstract; - -import org.springframework.stereotype.Component; - -@Component -public class LogRepository { - - @Override - public String toString() { - return "logRepository"; - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/sampleabstract/RuleRepository.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/RuleRepository.java deleted file mode 100644 index a1c5b5067f..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/sampleabstract/RuleRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.sampleabstract; - -import org.springframework.stereotype.Component; - -@Component -public class RuleRepository { - - @Override - public String toString() { - return "ruleRepository"; - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java deleted file mode 100644 index e08309d474..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.startup; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; - -@Component -@Scope(value = "prototype") -public class AllStrategiesExampleBean implements InitializingBean { - - private static final Logger LOG = LoggerFactory.getLogger(AllStrategiesExampleBean.class); - - public AllStrategiesExampleBean() { - LOG.info("Constructor"); - } - - @Override - public void afterPropertiesSet() throws Exception { - LOG.info("InitializingBean"); - } - - @PostConstruct - public void postConstruct() { - LOG.info("PostConstruct"); - } - - public void init() { - LOG.info("init-method"); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/startup/EventListenerExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/EventListenerExampleBean.java deleted file mode 100644 index a76fc6a2b2..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/startup/EventListenerExampleBean.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.startup; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Component; - -@Component -public class EventListenerExampleBean { - private static final Logger LOG = LoggerFactory.getLogger(EventListenerExampleBean.class); - - public static int counter; - - @EventListener - public void onApplicationEvent(ContextRefreshedEvent event) { - LOG.info("Increment counter"); - counter++; - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/startup/InitMethodExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/InitMethodExampleBean.java deleted file mode 100644 index a3b12028d1..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/startup/InitMethodExampleBean.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.startup; - -import java.util.Arrays; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Scope(value = "prototype") -public class InitMethodExampleBean { - - private static final Logger LOG = LoggerFactory.getLogger(InitMethodExampleBean.class); - - @Autowired - private Environment environment; - - public void init() { - LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles())); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java deleted file mode 100644 index c625a172fd..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.startup; - -import java.util.Arrays; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Scope(value = "prototype") -public class InitializingBeanExampleBean implements InitializingBean { - - private static final Logger LOG = LoggerFactory.getLogger(InitializingBeanExampleBean.class); - - @Autowired - private Environment environment; - - @Override - public void afterPropertiesSet() throws Exception { - LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles())); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java deleted file mode 100644 index d31aee8acd..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.startup; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Scope("prototype") -public class InvalidInitExampleBean { - - @Autowired - private Environment environment; - - public InvalidInitExampleBean() { - environment.getActiveProfiles(); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java deleted file mode 100644 index ade7573bbe..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.startup; - -import java.util.Arrays; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Scope(value = "prototype") -public class LogicInConstructorExampleBean { - - private static final Logger LOG = LoggerFactory.getLogger(LogicInConstructorExampleBean.class); - - @Autowired - public LogicInConstructorExampleBean(Environment environment) { - LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles())); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/startup/PostConstructExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/PostConstructExampleBean.java deleted file mode 100644 index 1001043d86..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/startup/PostConstructExampleBean.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.startup; - -import java.util.Arrays; - -import javax.annotation.PostConstruct; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Scope(value = "prototype") -public class PostConstructExampleBean { - - private static final Logger LOG = LoggerFactory.getLogger(PostConstructExampleBean.class); - - @Autowired - private Environment environment; - - @PostConstruct - public void init() { - LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles())); - } -} diff --git a/spring-core-2/src/main/java/com/baeldung/startup/SpringStartupConfig.java b/spring-core-2/src/main/java/com/baeldung/startup/SpringStartupConfig.java deleted file mode 100644 index ad6492dadc..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/startup/SpringStartupConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.startup; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("com.baeldung.startup") -public class SpringStartupConfig { -} \ No newline at end of file diff --git a/spring-core-2/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java b/spring-core-2/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java deleted file mode 100644 index 2cc5e6abcb..0000000000 --- a/spring-core-2/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.startup; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.stereotype.Component; - -@Component -public class StartupApplicationListenerExample implements ApplicationListener { - - private static final Logger LOG = LoggerFactory.getLogger(StartupApplicationListenerExample.class); - - public static int counter; - - @Override - public void onApplicationEvent(ContextRefreshedEvent event) { - LOG.info("Increment counter"); - counter++; - } -} diff --git a/spring-core-2/src/main/resources/startupConfig.xml b/spring-core-2/src/main/resources/startupConfig.xml deleted file mode 100644 index d42e0f6c2b..0000000000 --- a/spring-core-2/src/main/resources/startupConfig.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/spring-core-2/src/test/java/com/baeldung/customannotation/Account.java b/spring-core-2/src/test/java/com/baeldung/customannotation/Account.java deleted file mode 100644 index cfdd8815e4..0000000000 --- a/spring-core-2/src/test/java/com/baeldung/customannotation/Account.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.customannotation; - -import java.io.Serializable; - -public class Account implements Serializable { - - private static final long serialVersionUID = 7857541629844398625L; - - private Long id; - private String email; - private Person person; - - public Account() { - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public Person getPerson() { - return person; - } - - public void setPerson(Person person) { - this.person = person; - } - -} diff --git a/spring-core-2/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java b/spring-core-2/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java deleted file mode 100644 index a0707f263b..0000000000 --- a/spring-core-2/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.customannotation; - -import org.springframework.stereotype.Repository; - -@Repository -public class BeanWithGenericDAO { - - @DataAccess(entity = Person.class) - private GenericDAO personGenericDAO; - - public BeanWithGenericDAO() { - } - - public GenericDAO getPersonGenericDAO() { - return personGenericDAO; - } - -} diff --git a/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java deleted file mode 100644 index 1baea4505b..0000000000 --- a/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.customannotation; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) -public class DataAccessAnnotationIntegrationTest { - - @DataAccess(entity = Person.class) - private GenericDAO personGenericDAO; - @DataAccess(entity = Account.class) - private GenericDAO accountGenericDAO; - @DataAccess(entity = Person.class) - private GenericDAO anotherPersonGenericDAO; - - @Test - public void whenGenericDAOInitialized_thenNotNull() { - assertThat(personGenericDAO, is(notNullValue())); - assertThat(accountGenericDAO, is(notNullValue())); - } - - @Test - public void whenGenericDAOInjected_thenItIsSingleton() { - assertThat(personGenericDAO, not(sameInstance(accountGenericDAO))); - assertThat(personGenericDAO, not(equalTo(accountGenericDAO))); - - assertThat(personGenericDAO, sameInstance(anotherPersonGenericDAO)); - } - - @Test - public void whenFindAll_thenMessagesIsCorrect() { - personGenericDAO.findAll(); - assertThat(personGenericDAO.getMessage(), is("Would create findAll query from Person")); - - accountGenericDAO.findAll(); - assertThat(accountGenericDAO.getMessage(), is("Would create findAll query from Account")); - } - - @Test - public void whenPersist_thenMakeSureThatMessagesIsCorrect() { - personGenericDAO.persist(new Person()); - assertThat(personGenericDAO.getMessage(), is("Would create persist query from Person")); - - accountGenericDAO.persist(new Account()); - assertThat(accountGenericDAO.getMessage(), is("Would create persist query from Account")); - } -} diff --git a/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java deleted file mode 100644 index bc7a5f7246..0000000000 --- a/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.customannotation; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.lang.reflect.Type; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) -public class DataAccessFieldCallbackIntegrationTest { - - @Autowired - private ConfigurableListableBeanFactory configurableListableBeanFactory; - - @Autowired - private BeanWithGenericDAO beanWithGenericDAO; - - @Rule - public ExpectedException ex = ExpectedException.none(); - - @Test - public void whenObjectCreated_thenObjectCreationIsSuccessful() { - final DataAccessFieldCallback dataAccessFieldCallback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO); - assertThat(dataAccessFieldCallback, is(notNullValue())); - } - - @Test - public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() throws NoSuchFieldException, SecurityException { - final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO); - final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType(); - final boolean result = callback.genericTypeIsValid(Person.class, fieldType); - assertThat(result, is(true)); - } - - @Test - public void whenMethodGetBeanInstanceCalled_thenReturnCorrectInstance() { - final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO); - final Object result = callback.getBeanInstance("personGenericDAO", GenericDAO.class, Person.class); - assertThat((result instanceof GenericDAO), is(true)); - } -} diff --git a/spring-core-2/src/test/java/com/baeldung/customannotation/Person.java b/spring-core-2/src/test/java/com/baeldung/customannotation/Person.java deleted file mode 100644 index 4fa70e51af..0000000000 --- a/spring-core-2/src/test/java/com/baeldung/customannotation/Person.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.customannotation; - -import java.io.Serializable; - -public class Person implements Serializable { - - private static final long serialVersionUID = 9005331414216374586L; - - private Long id; - private String name; - - public Person() { - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - -} diff --git a/spring-core-2/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java deleted file mode 100644 index 1cd7357a09..0000000000 --- a/spring-core-2/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.customscope; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Map; - -import org.junit.Test; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class TenantScopeIntegrationTest { - - @Test - public final void whenRegisterScopeAndBeans_thenContextContainsFooAndBar() { - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); - try { - ctx.register(TenantScopeConfig.class); - ctx.register(TenantBeansConfig.class); - ctx.refresh(); - - TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class); - foo.sayHello(); - TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class); - bar.sayHello(); - Map foos = ctx.getBeansOfType(TenantBean.class); - - assertThat(foo, not(equalTo(bar))); - assertThat(foos.size(), equalTo(2)); - assertTrue(foos.containsValue(foo)); - assertTrue(foos.containsValue(bar)); - - BeanDefinition fooDefinition = ctx.getBeanDefinition("foo"); - BeanDefinition barDefinition = ctx.getBeanDefinition("bar"); - - assertThat(fooDefinition.getScope(), equalTo("tenant")); - assertThat(barDefinition.getScope(), equalTo("tenant")); - } finally { - ctx.close(); - } - } - - @Test - public final void whenComponentScan_thenContextContainsFooAndBar() { - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); - try { - ctx.scan("com.baeldung.customscope"); - ctx.refresh(); - - TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class); - foo.sayHello(); - TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class); - bar.sayHello(); - Map foos = ctx.getBeansOfType(TenantBean.class); - - assertThat(foo, not(equalTo(bar))); - assertThat(foos.size(), equalTo(2)); - assertTrue(foos.containsValue(foo)); - assertTrue(foos.containsValue(bar)); - - BeanDefinition fooDefinition = ctx.getBeanDefinition("foo"); - BeanDefinition barDefinition = ctx.getBeanDefinition("bar"); - - assertThat(fooDefinition.getScope(), equalTo("tenant")); - assertThat(barDefinition.getScope(), equalTo("tenant")); - } finally { - ctx.close(); - } - } -} diff --git a/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java deleted file mode 100644 index b58c093c31..0000000000 --- a/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.startup; - -import org.assertj.core.api.Assertions; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { SpringStartupConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringStartupIntegrationTest { - - @Autowired - private ApplicationContext ctx; - - @Test(expected = BeanCreationException.class) - public void whenInstantiating_shouldThrowBCE() throws Exception { - ctx.getBean(InvalidInitExampleBean.class); - } - - @Test - public void whenPostConstruct_shouldLogEnv() throws Exception { - ctx.getBean(PostConstructExampleBean.class); - } - - @Test - public void whenConstructorInjection_shouldLogEnv() throws Exception { - ctx.getBean(LogicInConstructorExampleBean.class); - } - - @Test - public void whenInitializingBean_shouldLogEnv() throws Exception { - ctx.getBean(InitializingBeanExampleBean.class); - } - - @Test - public void whenApplicationListener_shouldRunOnce() throws Exception { - Assertions.assertThat(StartupApplicationListenerExample.counter).isEqualTo(1); - } -} \ No newline at end of file diff --git a/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java deleted file mode 100644 index 3dfd4835df..0000000000 --- a/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.startup; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:startupConfig.xml") -public class SpringStartupXMLConfigIntegrationTest { - - @Autowired - private ApplicationContext ctx; - - @Test - public void whenPostConstruct_shouldLogEnv() throws Exception { - ctx.getBean(InitMethodExampleBean.class); - } - - @Test - public void whenAllStrategies_shouldLogOrder() throws Exception { - ctx.getBean(AllStrategiesExampleBean.class); - } -} From c3e41be3c43254f54c9b3c4e64506c7aa9376af4 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 15 Jul 2020 17:27:20 +0530 Subject: [PATCH 027/132] JAVA-628: Moved 2 articles from spring-core-3 --- spring-core-3/README.md | 4 +- .../com/baeldung/collection/BaeldungBean.java | 18 ------ .../baeldung/collection/CollectionConfig.java | 50 --------------- .../collection/CollectionInjectionDemo.java | 21 ------- .../baeldung/collection/CollectionsBean.java | 62 ------------------- .../staticvalue/injection/Application.java | 16 ----- .../injection/PropertyController.java | 30 --------- 7 files changed, 2 insertions(+), 199 deletions(-) delete mode 100644 spring-core-3/src/main/java/com/baeldung/collection/BaeldungBean.java delete mode 100644 spring-core-3/src/main/java/com/baeldung/collection/CollectionConfig.java delete mode 100644 spring-core-3/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java delete mode 100644 spring-core-3/src/main/java/com/baeldung/collection/CollectionsBean.java delete mode 100644 spring-core-3/src/main/java/com/baeldung/staticvalue/injection/Application.java delete mode 100644 spring-core-3/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java diff --git a/spring-core-3/README.md b/spring-core-3/README.md index 6c210b23ef..b6257cb9a4 100644 --- a/spring-core-3/README.md +++ b/spring-core-3/README.md @@ -7,8 +7,8 @@ This module contains articles about core Spring functionality - [Understanding getBean() in Spring](https://www.baeldung.com/spring-getbean) - [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) - [Difference Between BeanFactory and ApplicationContext](https://www.baeldung.com/spring-beanfactory-vs-applicationcontext) +- [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) +- [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope) - More articles: [[<-- prev]](/spring-core-2) diff --git a/spring-core-3/src/main/java/com/baeldung/collection/BaeldungBean.java b/spring-core-3/src/main/java/com/baeldung/collection/BaeldungBean.java deleted file mode 100644 index 6d7351df02..0000000000 --- a/spring-core-3/src/main/java/com/baeldung/collection/BaeldungBean.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.collection; - -/** - * Created by Gebruiker on 5/22/2018. - */ -public class BaeldungBean { - - private String name; - - public BaeldungBean(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } -} diff --git a/spring-core-3/src/main/java/com/baeldung/collection/CollectionConfig.java b/spring-core-3/src/main/java/com/baeldung/collection/CollectionConfig.java deleted file mode 100644 index fbae2963e5..0000000000 --- a/spring-core-3/src/main/java/com/baeldung/collection/CollectionConfig.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.collection; - -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; - -import java.util.*; - -@Configuration -public class CollectionConfig { - - @Bean - public CollectionsBean getCollectionsBean() { - return new CollectionsBean(new HashSet<>(Arrays.asList("John", "Adam", "Harry"))); - } - - @Bean - public List nameList(){ - return Arrays.asList("John", "Adam", "Harry", null); - } - - @Bean - public Map nameMap(){ - Map nameMap = new HashMap<>(); - nameMap.put(1, "John"); - nameMap.put(2, "Adam"); - nameMap.put(3, "Harry"); - return nameMap; - } - - @Bean - @Qualifier("CollectionsBean") - @Order(2) - public BaeldungBean getElement() { - return new BaeldungBean("John"); - } - - @Bean - @Order(3) - public BaeldungBean getAnotherElement() { - return new BaeldungBean("Adam"); - } - - @Bean - @Order(1) - public BaeldungBean getOneMoreElement() { - return new BaeldungBean("Harry"); - } -} diff --git a/spring-core-3/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java b/spring-core-3/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java deleted file mode 100644 index 2ee265f134..0000000000 --- a/spring-core-3/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.collection; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -/** - * Created by Gebruiker on 5/18/2018. - */ -public class CollectionInjectionDemo { - - public static void main(String[] args) { - - ApplicationContext context = new AnnotationConfigApplicationContext(CollectionConfig.class); - CollectionsBean collectionsBean = context.getBean(CollectionsBean.class); - collectionsBean.printNameList(); - collectionsBean.printNameSet(); - collectionsBean.printNameMap(); - collectionsBean.printBeanList(); - collectionsBean.printNameListWithDefaults(); - } -} diff --git a/spring-core-3/src/main/java/com/baeldung/collection/CollectionsBean.java b/spring-core-3/src/main/java/com/baeldung/collection/CollectionsBean.java deleted file mode 100644 index fc90f2c6ff..0000000000 --- a/spring-core-3/src/main/java/com/baeldung/collection/CollectionsBean.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.collection; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; - -/** - * Created by Gebruiker on 5/18/2018. - */ -public class CollectionsBean { - - @Autowired - private List nameList; - - private Set nameSet; - - private Map nameMap; - - @Autowired(required = false) - @Qualifier("CollectionsBean") - private List beanList = new ArrayList<>(); - - @Value("${names.list:}#{T(java.util.Collections).emptyList()}") - private List nameListWithDefaultValue; - - public CollectionsBean() { - } - - public CollectionsBean(Set strings) { - this.nameSet = strings; - } - - @Autowired - public void setNameMap(Map nameMap) { - this.nameMap = nameMap; - } - - public void printNameList() { - System.out.println(nameList); - } - - public void printNameSet() { - System.out.println(nameSet); - } - - public void printNameMap() { - System.out.println(nameMap); - } - - public void printBeanList() { - System.out.println(beanList); - } - - public void printNameListWithDefaults() { - System.out.println(nameListWithDefaultValue); - } -} diff --git a/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/Application.java b/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/Application.java deleted file mode 100644 index 45c47c955f..0000000000 --- a/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/Application.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.staticvalue.injection; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.PropertySource; - -@SpringBootApplication -@PropertySource("/application.properties") - -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java b/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java deleted file mode 100644 index f5910ea4f8..0000000000 --- a/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.staticvalue.injection; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Arrays; -import java.util.List; - -@RestController -public class PropertyController { - - @Value("${name}") - private String name; - - @Value("${name}") - private static String NAME_NULL; - - private static String NAME_STATIC; - - @Value("${name}") - public void setNameStatic(String name){ - PropertyController.NAME_STATIC = name; - } - - @GetMapping("/properties") - public List getProperties(){ - return Arrays.asList(this.name, NAME_STATIC, NAME_NULL) ; - } -} From 502bf3c45c3eed30562b7ef09e34b4f651ba4b80 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 15 Jul 2020 17:27:50 +0530 Subject: [PATCH 028/132] JAVA-628: Moved 2 articles to spring-core-3 --- .../CustomAnnotationConfiguration.java | 9 ++ .../baeldung/customannotation/DataAccess.java | 14 +++ .../DataAccessAnnotationProcessor.java | 37 +++++++ .../DataAccessFieldCallback.java | 96 +++++++++++++++++++ .../baeldung/customannotation/GenericDAO.java | 30 ++++++ .../com/baeldung/customscope/TenantBean.java | 14 +++ .../TenantBeanFactoryPostProcessor.java | 13 +++ .../customscope/TenantBeansConfig.java | 21 ++++ .../com/baeldung/customscope/TenantScope.java | 43 +++++++++ .../customscope/TenantScopeConfig.java | 14 +++ .../baeldung/customannotation/Account.java | 40 ++++++++ .../customannotation/BeanWithGenericDAO.java | 18 ++++ .../DataAccessAnnotationIntegrationTest.java | 57 +++++++++++ ...ataAccessFieldCallbackIntegrationTest.java | 51 ++++++++++ .../com/baeldung/customannotation/Person.java | 31 ++++++ .../TenantScopeIntegrationTest.java | 72 ++++++++++++++ 16 files changed, 560 insertions(+) create mode 100644 spring-core-3/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java create mode 100644 spring-core-3/src/main/java/com/baeldung/customannotation/DataAccess.java create mode 100644 spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java create mode 100644 spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java create mode 100644 spring-core-3/src/main/java/com/baeldung/customannotation/GenericDAO.java create mode 100644 spring-core-3/src/main/java/com/baeldung/customscope/TenantBean.java create mode 100644 spring-core-3/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java create mode 100644 spring-core-3/src/main/java/com/baeldung/customscope/TenantBeansConfig.java create mode 100644 spring-core-3/src/main/java/com/baeldung/customscope/TenantScope.java create mode 100644 spring-core-3/src/main/java/com/baeldung/customscope/TenantScopeConfig.java create mode 100644 spring-core-3/src/test/java/com/baeldung/customannotation/Account.java create mode 100644 spring-core-3/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java create mode 100644 spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java create mode 100644 spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java create mode 100644 spring-core-3/src/test/java/com/baeldung/customannotation/Person.java create mode 100644 spring-core-3/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java b/spring-core-3/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java new file mode 100644 index 0000000000..2e42a3f744 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java @@ -0,0 +1,9 @@ +package com.baeldung.customannotation; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.customannotation") +public class CustomAnnotationConfiguration { +} diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccess.java b/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccess.java new file mode 100644 index 0000000000..4160bad16d --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccess.java @@ -0,0 +1,14 @@ +package com.baeldung.customannotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) +@Documented +public @interface DataAccess { + Class entity(); +} diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java b/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java new file mode 100644 index 0000000000..27008176a8 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java @@ -0,0 +1,37 @@ +package com.baeldung.customannotation; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.stereotype.Component; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.ReflectionUtils.FieldCallback; + +@Component +public class DataAccessAnnotationProcessor implements BeanPostProcessor { + + private ConfigurableListableBeanFactory configurableListableBeanFactory; + + @Autowired + public DataAccessAnnotationProcessor(ConfigurableListableBeanFactory bf) { + configurableListableBeanFactory = bf; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + scanDataAccessAnnotation(bean, beanName); + return bean; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + return bean; + } + + protected void scanDataAccessAnnotation(Object bean, String beanName) { + Class managedBeanClass = bean.getClass(); + FieldCallback fcb = new DataAccessFieldCallback(configurableListableBeanFactory, bean); + ReflectionUtils.doWithFields(managedBeanClass, fcb); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java b/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java new file mode 100644 index 0000000000..07b5298ea9 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java @@ -0,0 +1,96 @@ +package com.baeldung.customannotation; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.ReflectionUtils.FieldCallback; + +public final class DataAccessFieldCallback implements FieldCallback { + + private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class); + private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; + + private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + "value should have same type with injected generic type."; + private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " + "to raw (non-generic) declaration. This will make your code less type-safe."; + private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " + "type '{}' or instance creation is failed because: {}"; + + private ConfigurableListableBeanFactory configurableListableBeanFactory; + private Object bean; + + public DataAccessFieldCallback(final ConfigurableListableBeanFactory bf, final Object bean) { + configurableListableBeanFactory = bf; + this.bean = bean; + } + + @Override + public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { + if (!field.isAnnotationPresent(DataAccess.class)) { + return; + } + ReflectionUtils.makeAccessible(field); + final Type fieldGenericType = field.getGenericType(); + // In this example, get actual "GenericDAO' type. + final Class generic = field.getType(); + final Class classValue = field.getDeclaredAnnotation(DataAccess.class).entity(); + + if (genericTypeIsValid(classValue, fieldGenericType)) { + final String beanName = classValue.getSimpleName() + generic.getSimpleName(); + final Object beanInstance = getBeanInstance(beanName, generic, classValue); + field.set(bean, beanInstance); + } else { + throw new IllegalArgumentException(ERROR_ENTITY_VALUE_NOT_SAME); + } + } + + /** + * For example, if user write: + *
+     * @DataAccess(entity=Person.class) 
+     * private GenericDAO<Account> personGenericDAO;
+     * 
+ * then this is should be failed. + */ + public boolean genericTypeIsValid(final Class clazz, final Type field) { + if (field instanceof ParameterizedType) { + final ParameterizedType parameterizedType = (ParameterizedType) field; + final Type type = parameterizedType.getActualTypeArguments()[0]; + + return type.equals(clazz); + } else { + logger.warn(WARN_NON_GENERIC_VALUE); + return true; + } + } + + public final Object getBeanInstance(final String beanName, final Class genericClass, final Class paramClass) { + Object daoInstance = null; + if (!configurableListableBeanFactory.containsBean(beanName)) { + logger.info("Creating new DataAccess bean named '{}'.", beanName); + + Object toRegister = null; + try { + final Constructor ctr = genericClass.getConstructor(Class.class); + toRegister = ctr.newInstance(paramClass); + } catch (final Exception e) { + logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e); + throw new RuntimeException(e); + } + + daoInstance = configurableListableBeanFactory.initializeBean(toRegister, beanName); + configurableListableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true); + configurableListableBeanFactory.registerSingleton(beanName, daoInstance); + logger.info("Bean named '{}' created successfully.", beanName); + } else { + daoInstance = configurableListableBeanFactory.getBean(beanName); + logger.info("Bean named '{}' already exist used as current bean reference.", beanName); + } + return daoInstance; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/GenericDAO.java b/spring-core-3/src/main/java/com/baeldung/customannotation/GenericDAO.java new file mode 100644 index 0000000000..0edd33b049 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customannotation/GenericDAO.java @@ -0,0 +1,30 @@ +package com.baeldung.customannotation; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +public class GenericDAO { + + private Class entityClass; + private String message; + + public GenericDAO(Class entityClass) { + this.entityClass = entityClass; + } + + public List findAll() { + message = "Would create findAll query from " + entityClass.getSimpleName(); + return Collections.emptyList(); + } + + public Optional persist(E toPersist) { + message = "Would create persist query from " + toPersist.getClass().getSimpleName(); + return Optional.empty(); + } + + /** Only used for unit-testing. */ + public final String getMessage() { + return message; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/customscope/TenantBean.java b/spring-core-3/src/main/java/com/baeldung/customscope/TenantBean.java new file mode 100644 index 0000000000..e892ae9d9b --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customscope/TenantBean.java @@ -0,0 +1,14 @@ +package com.baeldung.customscope; + +public class TenantBean { + + private final String name; + + public TenantBean(String name) { + this.name = name; + } + + public void sayHello() { + System.out.println(String.format("Hello from %s of type %s", this.name, this.getClass().getName())); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java new file mode 100644 index 0000000000..84ed0b46d7 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java @@ -0,0 +1,13 @@ +package com.baeldung.customscope; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; + +public class TenantBeanFactoryPostProcessor implements BeanFactoryPostProcessor { + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException { + factory.registerScope("tenant", new TenantScope()); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/customscope/TenantBeansConfig.java b/spring-core-3/src/main/java/com/baeldung/customscope/TenantBeansConfig.java new file mode 100644 index 0000000000..c219000fe6 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customscope/TenantBeansConfig.java @@ -0,0 +1,21 @@ +package com.baeldung.customscope; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; + +@Configuration +public class TenantBeansConfig { + + @Scope(scopeName = "tenant") + @Bean + public TenantBean foo() { + return new TenantBean("foo"); + } + + @Scope(scopeName = "tenant") + @Bean + public TenantBean bar() { + return new TenantBean("bar"); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/customscope/TenantScope.java b/spring-core-3/src/main/java/com/baeldung/customscope/TenantScope.java new file mode 100644 index 0000000000..f3077bc4c2 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customscope/TenantScope.java @@ -0,0 +1,43 @@ +package com.baeldung.customscope; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.beans.factory.config.Scope; + +public class TenantScope implements Scope { + + private Map scopedObjects = Collections.synchronizedMap(new HashMap()); + private Map destructionCallbacks = Collections.synchronizedMap(new HashMap()); + + @Override + public Object get(String name, ObjectFactory objectFactory) { + if (!scopedObjects.containsKey(name)) { + scopedObjects.put(name, objectFactory.getObject()); + } + return scopedObjects.get(name); + } + + @Override + public Object remove(String name) { + destructionCallbacks.remove(name); + return scopedObjects.remove(name); + } + + @Override + public void registerDestructionCallback(String name, Runnable callback) { + destructionCallbacks.put(name, callback); + } + + @Override + public Object resolveContextualObject(String key) { + return null; + } + + @Override + public String getConversationId() { + return "tenant"; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/customscope/TenantScopeConfig.java b/spring-core-3/src/main/java/com/baeldung/customscope/TenantScopeConfig.java new file mode 100644 index 0000000000..1829e1e8c4 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/customscope/TenantScopeConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.customscope; + +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class TenantScopeConfig { + + @Bean + public static BeanFactoryPostProcessor beanFactoryPostProcessor() { + return new TenantBeanFactoryPostProcessor(); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/Account.java b/spring-core-3/src/test/java/com/baeldung/customannotation/Account.java new file mode 100644 index 0000000000..cfdd8815e4 --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/customannotation/Account.java @@ -0,0 +1,40 @@ +package com.baeldung.customannotation; + +import java.io.Serializable; + +public class Account implements Serializable { + + private static final long serialVersionUID = 7857541629844398625L; + + private Long id; + private String email; + private Person person; + + public Account() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Person getPerson() { + return person; + } + + public void setPerson(Person person) { + this.person = person; + } + +} diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java b/spring-core-3/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java new file mode 100644 index 0000000000..a0707f263b --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java @@ -0,0 +1,18 @@ +package com.baeldung.customannotation; + +import org.springframework.stereotype.Repository; + +@Repository +public class BeanWithGenericDAO { + + @DataAccess(entity = Person.class) + private GenericDAO personGenericDAO; + + public BeanWithGenericDAO() { + } + + public GenericDAO getPersonGenericDAO() { + return personGenericDAO; + } + +} diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java b/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java new file mode 100644 index 0000000000..1baea4505b --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.customannotation; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) +public class DataAccessAnnotationIntegrationTest { + + @DataAccess(entity = Person.class) + private GenericDAO personGenericDAO; + @DataAccess(entity = Account.class) + private GenericDAO accountGenericDAO; + @DataAccess(entity = Person.class) + private GenericDAO anotherPersonGenericDAO; + + @Test + public void whenGenericDAOInitialized_thenNotNull() { + assertThat(personGenericDAO, is(notNullValue())); + assertThat(accountGenericDAO, is(notNullValue())); + } + + @Test + public void whenGenericDAOInjected_thenItIsSingleton() { + assertThat(personGenericDAO, not(sameInstance(accountGenericDAO))); + assertThat(personGenericDAO, not(equalTo(accountGenericDAO))); + + assertThat(personGenericDAO, sameInstance(anotherPersonGenericDAO)); + } + + @Test + public void whenFindAll_thenMessagesIsCorrect() { + personGenericDAO.findAll(); + assertThat(personGenericDAO.getMessage(), is("Would create findAll query from Person")); + + accountGenericDAO.findAll(); + assertThat(accountGenericDAO.getMessage(), is("Would create findAll query from Account")); + } + + @Test + public void whenPersist_thenMakeSureThatMessagesIsCorrect() { + personGenericDAO.persist(new Person()); + assertThat(personGenericDAO.getMessage(), is("Would create persist query from Person")); + + accountGenericDAO.persist(new Account()); + assertThat(accountGenericDAO.getMessage(), is("Would create persist query from Account")); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java b/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java new file mode 100644 index 0000000000..bc7a5f7246 --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java @@ -0,0 +1,51 @@ +package com.baeldung.customannotation; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; + +import java.lang.reflect.Type; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) +public class DataAccessFieldCallbackIntegrationTest { + + @Autowired + private ConfigurableListableBeanFactory configurableListableBeanFactory; + + @Autowired + private BeanWithGenericDAO beanWithGenericDAO; + + @Rule + public ExpectedException ex = ExpectedException.none(); + + @Test + public void whenObjectCreated_thenObjectCreationIsSuccessful() { + final DataAccessFieldCallback dataAccessFieldCallback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO); + assertThat(dataAccessFieldCallback, is(notNullValue())); + } + + @Test + public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() throws NoSuchFieldException, SecurityException { + final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO); + final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType(); + final boolean result = callback.genericTypeIsValid(Person.class, fieldType); + assertThat(result, is(true)); + } + + @Test + public void whenMethodGetBeanInstanceCalled_thenReturnCorrectInstance() { + final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO); + final Object result = callback.getBeanInstance("personGenericDAO", GenericDAO.class, Person.class); + assertThat((result instanceof GenericDAO), is(true)); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/Person.java b/spring-core-3/src/test/java/com/baeldung/customannotation/Person.java new file mode 100644 index 0000000000..4fa70e51af --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/customannotation/Person.java @@ -0,0 +1,31 @@ +package com.baeldung.customannotation; + +import java.io.Serializable; + +public class Person implements Serializable { + + private static final long serialVersionUID = 9005331414216374586L; + + private Long id; + private String name; + + public Person() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-core-3/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java b/spring-core-3/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java new file mode 100644 index 0000000000..1cd7357a09 --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung.customscope; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Map; + +import org.junit.Test; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class TenantScopeIntegrationTest { + + @Test + public final void whenRegisterScopeAndBeans_thenContextContainsFooAndBar() { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + try { + ctx.register(TenantScopeConfig.class); + ctx.register(TenantBeansConfig.class); + ctx.refresh(); + + TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class); + foo.sayHello(); + TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class); + bar.sayHello(); + Map foos = ctx.getBeansOfType(TenantBean.class); + + assertThat(foo, not(equalTo(bar))); + assertThat(foos.size(), equalTo(2)); + assertTrue(foos.containsValue(foo)); + assertTrue(foos.containsValue(bar)); + + BeanDefinition fooDefinition = ctx.getBeanDefinition("foo"); + BeanDefinition barDefinition = ctx.getBeanDefinition("bar"); + + assertThat(fooDefinition.getScope(), equalTo("tenant")); + assertThat(barDefinition.getScope(), equalTo("tenant")); + } finally { + ctx.close(); + } + } + + @Test + public final void whenComponentScan_thenContextContainsFooAndBar() { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + try { + ctx.scan("com.baeldung.customscope"); + ctx.refresh(); + + TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class); + foo.sayHello(); + TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class); + bar.sayHello(); + Map foos = ctx.getBeansOfType(TenantBean.class); + + assertThat(foo, not(equalTo(bar))); + assertThat(foos.size(), equalTo(2)); + assertTrue(foos.containsValue(foo)); + assertTrue(foos.containsValue(bar)); + + BeanDefinition fooDefinition = ctx.getBeanDefinition("foo"); + BeanDefinition barDefinition = ctx.getBeanDefinition("bar"); + + assertThat(fooDefinition.getScope(), equalTo("tenant")); + assertThat(barDefinition.getScope(), equalTo("tenant")); + } finally { + ctx.close(); + } + } +} From 9ffb4d4d641d6e153b6f10729ddf084b7f575232 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 15 Jul 2020 17:29:08 +0530 Subject: [PATCH 029/132] JAVA-628: Moved 3 articles to spring-core-4 --- spring-core-4/README.md | 3 ++ spring-core-4/pom.xml | 5 +++ .../com/baeldung/lombok/ApologizeService.java | 22 ++++++++++ .../com/baeldung/lombok/FarewellService.java | 18 ++++++++ .../com/baeldung/lombok/GreetingService.java | 15 +++++++ .../com/baeldung/lombok/ThankingService.java | 15 +++++++ .../java/com/baeldung/lombok/Translator.java | 5 +++ .../baeldung/sampleabstract/BallService.java | 28 ++++++++++++ .../sampleabstract/BasketballService.java | 13 ++++++ .../com/baeldung/sampleabstract/DemoApp.java | 18 ++++++++ .../sampleabstract/LogRepository.java | 12 +++++ .../sampleabstract/RuleRepository.java | 12 +++++ .../startup/AllStrategiesExampleBean.java | 35 +++++++++++++++ .../startup/EventListenerExampleBean.java | 21 +++++++++ .../startup/InitMethodExampleBean.java | 24 ++++++++++ .../startup/InitializingBeanExampleBean.java | 26 +++++++++++ .../startup/InvalidInitExampleBean.java | 18 ++++++++ .../LogicInConstructorExampleBean.java | 22 ++++++++++ .../startup/PostConstructExampleBean.java | 27 ++++++++++++ .../baeldung/startup/SpringStartupConfig.java | 9 ++++ .../StartupApplicationListenerExample.java | 22 ++++++++++ .../src/main/resources/startupConfig.xml | 16 +++++++ ...ogizeServiceAutowiringIntegrationTest.java | 33 ++++++++++++++ .../ApologizeServiceIntegrationTest.java | 21 +++++++++ .../FarewellAutowiringIntegrationTest.java | 31 +++++++++++++ .../FarewellServiceIntegrationTest.java | 20 +++++++++ .../GreetingServiceIntegrationTest.java | 37 ++++++++++++++++ .../java/com/baeldung/lombok/TestConfig.java | 17 +++++++ ...nkingServiceAutowiringIntegrationTest.java | 31 +++++++++++++ .../ThankingServiceIntegrationTest.java | 20 +++++++++ .../startup/SpringStartupIntegrationTest.java | 44 +++++++++++++++++++ ...SpringStartupXMLConfigIntegrationTest.java | 26 +++++++++++ 32 files changed, 666 insertions(+) create mode 100644 spring-core-4/src/main/java/com/baeldung/lombok/ApologizeService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/lombok/FarewellService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/lombok/GreetingService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/lombok/ThankingService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/lombok/Translator.java create mode 100644 spring-core-4/src/main/java/com/baeldung/sampleabstract/BallService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/sampleabstract/BasketballService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/sampleabstract/DemoApp.java create mode 100644 spring-core-4/src/main/java/com/baeldung/sampleabstract/LogRepository.java create mode 100644 spring-core-4/src/main/java/com/baeldung/sampleabstract/RuleRepository.java create mode 100644 spring-core-4/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java create mode 100644 spring-core-4/src/main/java/com/baeldung/startup/EventListenerExampleBean.java create mode 100644 spring-core-4/src/main/java/com/baeldung/startup/InitMethodExampleBean.java create mode 100644 spring-core-4/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java create mode 100644 spring-core-4/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java create mode 100644 spring-core-4/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java create mode 100644 spring-core-4/src/main/java/com/baeldung/startup/PostConstructExampleBean.java create mode 100644 spring-core-4/src/main/java/com/baeldung/startup/SpringStartupConfig.java create mode 100644 spring-core-4/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java create mode 100644 spring-core-4/src/main/resources/startupConfig.xml create mode 100644 spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java create mode 100644 spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java create mode 100644 spring-core-4/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java create mode 100644 spring-core-4/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java create mode 100644 spring-core-4/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java create mode 100644 spring-core-4/src/test/java/com/baeldung/lombok/TestConfig.java create mode 100644 spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java create mode 100644 spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java create mode 100644 spring-core-4/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java create mode 100644 spring-core-4/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java diff --git a/spring-core-4/README.md b/spring-core-4/README.md index 9da90ac77a..706c330f39 100644 --- a/spring-core-4/README.md +++ b/spring-core-4/README.md @@ -8,4 +8,7 @@ This module contains articles about core Spring functionality - [How to dynamically Autowire a Bean in Spring](https://www.baeldung.com/spring-dynamic-autowire) - [Spring @Import Annotation](https://www.baeldung.com/spring-import-annotation) - [Spring BeanPostProcessor](https://www.baeldung.com/spring-beanpostprocessor) +- [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) +- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) +- [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok) - More articles: [[<-- prev]](/spring-core-3) diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml index 299debbc3c..e5aee1f81d 100644 --- a/spring-core-4/pom.xml +++ b/spring-core-4/pom.xml @@ -29,6 +29,11 @@ spring-expression ${spring.version} + + org.projectlombok + lombok + ${lombok.version} + com.google.guava guava diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/ApologizeService.java b/spring-core-4/src/main/java/com/baeldung/lombok/ApologizeService.java new file mode 100644 index 0000000000..76c3df8217 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/lombok/ApologizeService.java @@ -0,0 +1,22 @@ +package com.baeldung.lombok; + +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class ApologizeService { + + private final Translator translator; + private final String message; + + @Autowired + public ApologizeService(Translator translator) { + this(translator, "sorry"); + } + + public String apologize() { + return translator.translate(message); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/FarewellService.java b/spring-core-4/src/main/java/com/baeldung/lombok/FarewellService.java new file mode 100644 index 0000000000..4e8c4993cb --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/lombok/FarewellService.java @@ -0,0 +1,18 @@ +package com.baeldung.lombok; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class FarewellService { + + private final Translator translator; + + public FarewellService(Translator translator) { + this.translator = translator; + } + + public String farewell() { + return translator.translate("bye"); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/GreetingService.java b/spring-core-4/src/main/java/com/baeldung/lombok/GreetingService.java new file mode 100644 index 0000000000..0e03e177e1 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/lombok/GreetingService.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class GreetingService { + + @Autowired + private Translator translator; + + public String greet() { + return translator.translate("hello"); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/ThankingService.java b/spring-core-4/src/main/java/com/baeldung/lombok/ThankingService.java new file mode 100644 index 0000000000..2e0c398d2d --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/lombok/ThankingService.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class ThankingService { + + private final Translator translator; + + public String thank() { + return translator.translate("thank you"); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/Translator.java b/spring-core-4/src/main/java/com/baeldung/lombok/Translator.java new file mode 100644 index 0000000000..2dea20b726 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/lombok/Translator.java @@ -0,0 +1,5 @@ +package com.baeldung.lombok; + +public interface Translator { + String translate(String input); +} diff --git a/spring-core-4/src/main/java/com/baeldung/sampleabstract/BallService.java b/spring-core-4/src/main/java/com/baeldung/sampleabstract/BallService.java new file mode 100644 index 0000000000..0d951aac8b --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/sampleabstract/BallService.java @@ -0,0 +1,28 @@ +package com.baeldung.sampleabstract; + +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.PostConstruct; + +public abstract class BallService { + + private RuleRepository ruleRepository; + + private LogRepository logRepository; + + public BallService(RuleRepository ruleRepository) { + this.ruleRepository = ruleRepository; + } + + @Autowired + public final void setLogRepository(LogRepository logRepository) { + this.logRepository = logRepository; + } + + @PostConstruct + public void afterInitialize() { + + System.out.println(ruleRepository.toString()); + System.out.println(logRepository.toString()); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/sampleabstract/BasketballService.java b/spring-core-4/src/main/java/com/baeldung/sampleabstract/BasketballService.java new file mode 100644 index 0000000000..4d6345b069 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/sampleabstract/BasketballService.java @@ -0,0 +1,13 @@ +package com.baeldung.sampleabstract; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BasketballService extends BallService { + + @Autowired + public BasketballService(RuleRepository ruleRepository) { + super(ruleRepository); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/sampleabstract/DemoApp.java b/spring-core-4/src/main/java/com/baeldung/sampleabstract/DemoApp.java new file mode 100644 index 0000000000..5a308b2671 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/sampleabstract/DemoApp.java @@ -0,0 +1,18 @@ +package com.baeldung.sampleabstract; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.sampleabstract") +public class DemoApp { + + + public static void main(String[] args) { + + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApp.class); + } + +} diff --git a/spring-core-4/src/main/java/com/baeldung/sampleabstract/LogRepository.java b/spring-core-4/src/main/java/com/baeldung/sampleabstract/LogRepository.java new file mode 100644 index 0000000000..84979768b5 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/sampleabstract/LogRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.sampleabstract; + +import org.springframework.stereotype.Component; + +@Component +public class LogRepository { + + @Override + public String toString() { + return "logRepository"; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/sampleabstract/RuleRepository.java b/spring-core-4/src/main/java/com/baeldung/sampleabstract/RuleRepository.java new file mode 100644 index 0000000000..a1c5b5067f --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/sampleabstract/RuleRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.sampleabstract; + +import org.springframework.stereotype.Component; + +@Component +public class RuleRepository { + + @Override + public String toString() { + return "ruleRepository"; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java b/spring-core-4/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java new file mode 100644 index 0000000000..e08309d474 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java @@ -0,0 +1,35 @@ +package com.baeldung.startup; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +@Scope(value = "prototype") +public class AllStrategiesExampleBean implements InitializingBean { + + private static final Logger LOG = LoggerFactory.getLogger(AllStrategiesExampleBean.class); + + public AllStrategiesExampleBean() { + LOG.info("Constructor"); + } + + @Override + public void afterPropertiesSet() throws Exception { + LOG.info("InitializingBean"); + } + + @PostConstruct + public void postConstruct() { + LOG.info("PostConstruct"); + } + + public void init() { + LOG.info("init-method"); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/startup/EventListenerExampleBean.java b/spring-core-4/src/main/java/com/baeldung/startup/EventListenerExampleBean.java new file mode 100644 index 0000000000..a76fc6a2b2 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/startup/EventListenerExampleBean.java @@ -0,0 +1,21 @@ +package com.baeldung.startup; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +@Component +public class EventListenerExampleBean { + private static final Logger LOG = LoggerFactory.getLogger(EventListenerExampleBean.class); + + public static int counter; + + @EventListener + public void onApplicationEvent(ContextRefreshedEvent event) { + LOG.info("Increment counter"); + counter++; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/startup/InitMethodExampleBean.java b/spring-core-4/src/main/java/com/baeldung/startup/InitMethodExampleBean.java new file mode 100644 index 0000000000..a3b12028d1 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/startup/InitMethodExampleBean.java @@ -0,0 +1,24 @@ +package com.baeldung.startup; + +import java.util.Arrays; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = "prototype") +public class InitMethodExampleBean { + + private static final Logger LOG = LoggerFactory.getLogger(InitMethodExampleBean.class); + + @Autowired + private Environment environment; + + public void init() { + LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles())); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java b/spring-core-4/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java new file mode 100644 index 0000000000..c625a172fd --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java @@ -0,0 +1,26 @@ +package com.baeldung.startup; + +import java.util.Arrays; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = "prototype") +public class InitializingBeanExampleBean implements InitializingBean { + + private static final Logger LOG = LoggerFactory.getLogger(InitializingBeanExampleBean.class); + + @Autowired + private Environment environment; + + @Override + public void afterPropertiesSet() throws Exception { + LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles())); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java b/spring-core-4/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java new file mode 100644 index 0000000000..d31aee8acd --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java @@ -0,0 +1,18 @@ +package com.baeldung.startup; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Scope("prototype") +public class InvalidInitExampleBean { + + @Autowired + private Environment environment; + + public InvalidInitExampleBean() { + environment.getActiveProfiles(); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java b/spring-core-4/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java new file mode 100644 index 0000000000..ade7573bbe --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java @@ -0,0 +1,22 @@ +package com.baeldung.startup; + +import java.util.Arrays; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = "prototype") +public class LogicInConstructorExampleBean { + + private static final Logger LOG = LoggerFactory.getLogger(LogicInConstructorExampleBean.class); + + @Autowired + public LogicInConstructorExampleBean(Environment environment) { + LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles())); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/startup/PostConstructExampleBean.java b/spring-core-4/src/main/java/com/baeldung/startup/PostConstructExampleBean.java new file mode 100644 index 0000000000..1001043d86 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/startup/PostConstructExampleBean.java @@ -0,0 +1,27 @@ +package com.baeldung.startup; + +import java.util.Arrays; + +import javax.annotation.PostConstruct; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = "prototype") +public class PostConstructExampleBean { + + private static final Logger LOG = LoggerFactory.getLogger(PostConstructExampleBean.class); + + @Autowired + private Environment environment; + + @PostConstruct + public void init() { + LOG.info("Env Default Profiles", Arrays.asList(environment.getDefaultProfiles())); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/startup/SpringStartupConfig.java b/spring-core-4/src/main/java/com/baeldung/startup/SpringStartupConfig.java new file mode 100644 index 0000000000..ad6492dadc --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/startup/SpringStartupConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.startup; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.startup") +public class SpringStartupConfig { +} \ No newline at end of file diff --git a/spring-core-4/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java b/spring-core-4/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java new file mode 100644 index 0000000000..2cc5e6abcb --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java @@ -0,0 +1,22 @@ +package com.baeldung.startup; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.stereotype.Component; + +@Component +public class StartupApplicationListenerExample implements ApplicationListener { + + private static final Logger LOG = LoggerFactory.getLogger(StartupApplicationListenerExample.class); + + public static int counter; + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + LOG.info("Increment counter"); + counter++; + } +} diff --git a/spring-core-4/src/main/resources/startupConfig.xml b/spring-core-4/src/main/resources/startupConfig.xml new file mode 100644 index 0000000000..d42e0f6c2b --- /dev/null +++ b/spring-core-4/src/main/resources/startupConfig.xml @@ -0,0 +1,16 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java new file mode 100644 index 0000000000..a49dd84f11 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.lombok; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = TestConfig.class) +public class ApologizeServiceAutowiringIntegrationTest { + + private final static String TRANSLATED = "TRANSLATED"; + + @Autowired + private ApologizeService apologizeService; + + @Autowired + private Translator translator; + + @Test + public void apologizeWithTranslatedMessage() { + when(translator.translate("sorry")).thenReturn(TRANSLATED); + assertEquals(TRANSLATED, apologizeService.apologize()); + } + +} \ No newline at end of file diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java new file mode 100644 index 0000000000..77f0c94299 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung.lombok; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ApologizeServiceIntegrationTest { + + private final static String MESSAGE = "MESSAGE"; + private final static String TRANSLATED = "TRANSLATED"; + + @Test + public void apologizeWithCustomTranslatedMessage() { + Translator translator = mock(Translator.class); + ApologizeService apologizeService = new ApologizeService(translator, MESSAGE); + when(translator.translate(MESSAGE)).thenReturn(TRANSLATED); + assertEquals(TRANSLATED, apologizeService.apologize()); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java new file mode 100644 index 0000000000..ec0793bd2e --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.lombok; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = TestConfig.class) +public class FarewellAutowiringIntegrationTest { + + @Autowired + private FarewellService farewellService; + + @Autowired + private Translator translator; + + @Test + public void sayByeWithTranslatedMessage() { + String translated = "translated"; + when(translator.translate("bye")).thenReturn(translated); + assertEquals(translated, farewellService.farewell()); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java new file mode 100644 index 0000000000..38959a511f --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.lombok; + +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class FarewellServiceIntegrationTest { + + private final static String TRANSLATED = "TRANSLATED"; + + @Test + public void sayByeWithTranslatedMessage() { + Translator translator = mock(Translator.class); + when(translator.translate("bye")).thenReturn(TRANSLATED); + FarewellService farewellService = new FarewellService(translator); + assertEquals(TRANSLATED, farewellService.farewell()); + } +} \ No newline at end of file diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java new file mode 100644 index 0000000000..0516b5eb56 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java @@ -0,0 +1,37 @@ +package com.baeldung.lombok; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = TestConfig.class) +public class GreetingServiceIntegrationTest { + + @Autowired + private GreetingService greetingService; + + @Autowired + private Translator translator; + + @Test + public void greetWithTranslatedMessage() { + String translated = "translated"; + when(translator.translate("hello")).thenReturn(translated); + assertEquals(translated, greetingService.greet()); + } + + @Test(expected = NullPointerException.class) + public void throwWhenInstantiated() { + GreetingService greetingService = new GreetingService(); + greetingService.greet(); + } +} \ No newline at end of file diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/TestConfig.java b/spring-core-4/src/test/java/com/baeldung/lombok/TestConfig.java new file mode 100644 index 0000000000..3278a8188f --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/lombok/TestConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.lombok; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import static org.mockito.Mockito.mock; + +@Configuration +@ComponentScan("com.baeldung.lombok") +class TestConfig { + + @Bean + public Translator mockTranslator() { + return mock(Translator.class); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java new file mode 100644 index 0000000000..fb9abbad46 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.lombok; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = TestConfig.class) +public class ThankingServiceAutowiringIntegrationTest { + + @Autowired + private ThankingService thankingService; + + @Autowired + private Translator translator; + + @Test + public void thankWithTranslatedMessage() { + String translated = "translated"; + when(translator.translate("thank you")).thenReturn(translated); + assertEquals(translated, thankingService.thank()); + } +} \ No newline at end of file diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java new file mode 100644 index 0000000000..680f926717 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.lombok; + +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ThankingServiceIntegrationTest { + + private final static String TRANSLATED = "TRANSLATED"; + + @Test + public void thankWithTranslatedMessage() { + Translator translator = mock(Translator.class); + when(translator.translate("thank you")).thenReturn(TRANSLATED); + ThankingService thankingService = new ThankingService(translator); + assertEquals(TRANSLATED, thankingService.thank()); + } +} \ No newline at end of file diff --git a/spring-core-4/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java new file mode 100644 index 0000000000..b58c093c31 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.startup; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringStartupConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringStartupIntegrationTest { + + @Autowired + private ApplicationContext ctx; + + @Test(expected = BeanCreationException.class) + public void whenInstantiating_shouldThrowBCE() throws Exception { + ctx.getBean(InvalidInitExampleBean.class); + } + + @Test + public void whenPostConstruct_shouldLogEnv() throws Exception { + ctx.getBean(PostConstructExampleBean.class); + } + + @Test + public void whenConstructorInjection_shouldLogEnv() throws Exception { + ctx.getBean(LogicInConstructorExampleBean.class); + } + + @Test + public void whenInitializingBean_shouldLogEnv() throws Exception { + ctx.getBean(InitializingBeanExampleBean.class); + } + + @Test + public void whenApplicationListener_shouldRunOnce() throws Exception { + Assertions.assertThat(StartupApplicationListenerExample.counter).isEqualTo(1); + } +} \ No newline at end of file diff --git a/spring-core-4/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java new file mode 100644 index 0000000000..3dfd4835df --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.startup; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:startupConfig.xml") +public class SpringStartupXMLConfigIntegrationTest { + + @Autowired + private ApplicationContext ctx; + + @Test + public void whenPostConstruct_shouldLogEnv() throws Exception { + ctx.getBean(InitMethodExampleBean.class); + } + + @Test + public void whenAllStrategies_shouldLogOrder() throws Exception { + ctx.getBean(AllStrategiesExampleBean.class); + } +} From 013c4917d2b5df78d844b86d00b56379a046db48 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 15 Jul 2020 17:30:45 +0530 Subject: [PATCH 030/132] JAVA-628: Corrected README, moved article code to appropriate module --- spring-di/README.md | 2 + .../AnotherArbitraryDependency.java | 13 ------ .../dependency/ArbitraryDependency.java | 13 ------ .../YetAnotherArbitraryDependency.java | 13 ------ .../FieldAutowiredIntegrationTest.java | 29 ------------- .../FieldAutowiredNameIntegrationTest.java | 29 ------------- ...ieldQualifierAutowiredIntegrationTest.java | 41 ------------------- .../ApplicationContextTestAutowiredName.java | 9 ---- ...licationContextTestAutowiredQualifier.java | 24 ----------- .../ApplicationContextTestAutowiredType.java | 15 ------- .../ApplicationContextTestInjectName.java | 16 -------- ...ApplicationContextTestInjectQualifier.java | 22 ---------- .../ApplicationContextTestInjectType.java | 15 ------- .../FieldByNameInjectIntegrationTest.java | 32 --------------- .../inject/FieldInjectIntegrationTest.java | 30 -------------- .../FieldQualifierInjectIntegrationTest.java | 41 ------------------- 16 files changed, 2 insertions(+), 342 deletions(-) delete mode 100644 spring-di/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java delete mode 100644 spring-di/src/main/java/com/baeldung/dependency/ArbitraryDependency.java delete mode 100644 spring-di/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java delete mode 100644 spring-di/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java delete mode 100644 spring-di/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java delete mode 100644 spring-di/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java delete mode 100644 spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java delete mode 100644 spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java delete mode 100644 spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java delete mode 100644 spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectName.java delete mode 100644 spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java delete mode 100644 spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectType.java delete mode 100644 spring-di/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java delete mode 100644 spring-di/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java delete mode 100644 spring-di/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java diff --git a/spring-di/README.md b/spring-di/README.md index 7571b12916..d470768f16 100644 --- a/spring-di/README.md +++ b/spring-di/README.md @@ -13,3 +13,5 @@ This module contains articles about dependency injection with Spring - [Controlling Bean Creation Order with @DependsOn Annotation](https://www.baeldung.com/spring-depends-on) - [Unsatisfied Dependency in Spring](https://www.baeldung.com/spring-unsatisfied-dependency) - [Circular Dependencies in Spring](https://www.baeldung.com/circular-dependencies-in-spring) +- [XML-Based Injection in Spring](https://www.baeldung.com/spring-xml-injection) +- More articles: [[next -->]](/spring-di-2) diff --git a/spring-di/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java b/spring-di/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java deleted file mode 100644 index 0e19523b7e..0000000000 --- a/spring-di/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.dependency; - -import org.springframework.stereotype.Component; - -@Component -public class AnotherArbitraryDependency extends ArbitraryDependency { - - private final String label = "Another Arbitrary Dependency"; - - public String toString() { - return label; - } -} diff --git a/spring-di/src/main/java/com/baeldung/dependency/ArbitraryDependency.java b/spring-di/src/main/java/com/baeldung/dependency/ArbitraryDependency.java deleted file mode 100644 index 3c90492d2c..0000000000 --- a/spring-di/src/main/java/com/baeldung/dependency/ArbitraryDependency.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.dependency; - -import org.springframework.stereotype.Component; - -@Component(value = "autowiredFieldDependency") -public class ArbitraryDependency { - - private final String label = "Arbitrary Dependency"; - - public String toString() { - return label; - } -} diff --git a/spring-di/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java b/spring-di/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java deleted file mode 100644 index a88abd0924..0000000000 --- a/spring-di/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.dependency; - -import org.springframework.stereotype.Component; - -@Component -public class YetAnotherArbitraryDependency extends ArbitraryDependency { - - private final String label = "Yet Another Arbitrary Dependency"; - - public String toString() { - return label; - } -} diff --git a/spring-di/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java b/spring-di/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java deleted file mode 100644 index a78799f1d9..0000000000 --- a/spring-di/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.autowired; - -import com.baeldung.configuration.ApplicationContextTestAutowiredType; -import com.baeldung.dependency.ArbitraryDependency; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestAutowiredType.class) -public class FieldAutowiredIntegrationTest { - - @Autowired - private ArbitraryDependency fieldDependency; - - @Test - public void givenAutowired_WhenSetOnField_ThenDependencyResolved() { - assertNotNull(fieldDependency); - assertEquals("Arbitrary Dependency", fieldDependency.toString()); - } -} diff --git a/spring-di/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java b/spring-di/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java deleted file mode 100644 index 8f09e73c33..0000000000 --- a/spring-di/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.autowired; - -import com.baeldung.configuration.ApplicationContextTestAutowiredName; -import com.baeldung.dependency.ArbitraryDependency; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestAutowiredName.class) -public class FieldAutowiredNameIntegrationTest { - - @Autowired - private ArbitraryDependency autowiredFieldDependency; - - @Test - public void givenAutowiredAnnotation_WhenOnField_ThenDependencyValid() { - assertNotNull(autowiredFieldDependency); - assertEquals("Arbitrary Dependency", autowiredFieldDependency.toString()); - } -} diff --git a/spring-di/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java b/spring-di/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java deleted file mode 100644 index 01317aef6f..0000000000 --- a/spring-di/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.autowired; - -import com.baeldung.configuration.ApplicationContextTestAutowiredQualifier; -import com.baeldung.dependency.ArbitraryDependency; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestAutowiredQualifier.class) -public class FieldQualifierAutowiredIntegrationTest { - - @Autowired - @Qualifier("autowiredFieldDependency") - private ArbitraryDependency fieldDependency1; - - @Autowired - @Qualifier("anotherAutowiredFieldDependency") - private ArbitraryDependency fieldDependency2; - - @Test - public void givenAutowiredQualifier_WhenOnField_ThenDep1Valid() { - assertNotNull(fieldDependency1); - assertEquals("Arbitrary Dependency", fieldDependency1.toString()); - } - - @Test - public void givenAutowiredQualifier_WhenOnField_ThenDep2Valid() { - assertNotNull(fieldDependency2); - assertEquals("Another Arbitrary Dependency", fieldDependency2.toString()); - } -} diff --git a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java b/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java deleted file mode 100644 index 48c4495465..0000000000 --- a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.configuration; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages = {"com.baeldung.dependency"}) -public class ApplicationContextTestAutowiredName { -} diff --git a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java b/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java deleted file mode 100644 index ef6690ab4b..0000000000 --- a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.configuration; - -import com.baeldung.dependency.AnotherArbitraryDependency; -import com.baeldung.dependency.ArbitraryDependency; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ApplicationContextTestAutowiredQualifier { - - @Bean - public ArbitraryDependency autowiredFieldDependency() { - ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency(); - - return autowiredFieldDependency; - } - - @Bean - public ArbitraryDependency anotherAutowiredFieldDependency() { - ArbitraryDependency anotherAutowiredFieldDependency = new AnotherArbitraryDependency(); - - return anotherAutowiredFieldDependency; - } -} diff --git a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java b/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java deleted file mode 100644 index 240bc466b7..0000000000 --- a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.configuration; - -import com.baeldung.dependency.ArbitraryDependency; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ApplicationContextTestAutowiredType { - - @Bean - public ArbitraryDependency autowiredFieldDependency() { - ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency(); - return autowiredFieldDependency; - } -} diff --git a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectName.java b/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectName.java deleted file mode 100644 index 851aa0b8ee..0000000000 --- a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectName.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.configuration; - -import com.baeldung.dependency.ArbitraryDependency; -import com.baeldung.dependency.YetAnotherArbitraryDependency; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ApplicationContextTestInjectName { - - @Bean - public ArbitraryDependency yetAnotherFieldInjectDependency() { - ArbitraryDependency yetAnotherFieldInjectDependency = new YetAnotherArbitraryDependency(); - return yetAnotherFieldInjectDependency; - } -} diff --git a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java b/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java deleted file mode 100644 index 59af5a91bb..0000000000 --- a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.configuration; - -import com.baeldung.dependency.AnotherArbitraryDependency; -import com.baeldung.dependency.ArbitraryDependency; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ApplicationContextTestInjectQualifier { - - @Bean - public ArbitraryDependency defaultFile() { - ArbitraryDependency defaultFile = new ArbitraryDependency(); - return defaultFile; - } - - @Bean - public ArbitraryDependency namedFile() { - ArbitraryDependency namedFile = new AnotherArbitraryDependency(); - return namedFile; - } -} diff --git a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectType.java b/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectType.java deleted file mode 100644 index 1e1f01f269..0000000000 --- a/spring-di/src/test/java/com/baeldung/configuration/ApplicationContextTestInjectType.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.configuration; - -import com.baeldung.dependency.ArbitraryDependency; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ApplicationContextTestInjectType { - - @Bean - public ArbitraryDependency injectDependency() { - ArbitraryDependency injectDependency = new ArbitraryDependency(); - return injectDependency; - } -} diff --git a/spring-di/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java b/spring-di/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java deleted file mode 100644 index f5897febab..0000000000 --- a/spring-di/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.inject; - -import com.baeldung.configuration.ApplicationContextTestInjectName; -import com.baeldung.dependency.ArbitraryDependency; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.inject.Inject; -import javax.inject.Named; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestInjectName.class) -public class FieldByNameInjectIntegrationTest { - - @Inject - @Named("yetAnotherFieldInjectDependency") - private ArbitraryDependency yetAnotherFieldInjectDependency; - - @Test - public void givenInjectQualifier_WhenSetOnField_ThenDependencyValid() { - assertNotNull(yetAnotherFieldInjectDependency); - assertEquals("Yet Another Arbitrary Dependency", yetAnotherFieldInjectDependency.toString()); - } -} diff --git a/spring-di/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java b/spring-di/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java deleted file mode 100644 index 45b7c8015c..0000000000 --- a/spring-di/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.inject; - -import com.baeldung.configuration.ApplicationContextTestInjectType; -import com.baeldung.dependency.ArbitraryDependency; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.inject.Inject; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestInjectType.class) -public class FieldInjectIntegrationTest { - - @Inject - private ArbitraryDependency fieldInjectDependency; - - @Test - public void givenInjectAnnotation_WhenOnField_ThenValidDependency() { - assertNotNull(fieldInjectDependency); - assertEquals("Arbitrary Dependency", fieldInjectDependency.toString()); - } -} diff --git a/spring-di/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java b/spring-di/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java deleted file mode 100644 index 0fd6a0e4c1..0000000000 --- a/spring-di/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.inject; - -import com.baeldung.configuration.ApplicationContextTestInjectQualifier; -import com.baeldung.dependency.ArbitraryDependency; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import javax.inject.Inject; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader = AnnotationConfigContextLoader.class, - classes = ApplicationContextTestInjectQualifier.class) -public class FieldQualifierInjectIntegrationTest { - - @Inject - @Qualifier("defaultFile") - private ArbitraryDependency defaultDependency; - - @Inject - @Qualifier("namedFile") - private ArbitraryDependency namedDependency; - - @Test - public void givenInjectQualifier_WhenOnField_ThenDefaultFileValid() { - assertNotNull(defaultDependency); - assertEquals("Arbitrary Dependency", defaultDependency.toString()); - } - - @Test - public void givenInjectQualifier_WhenOnField_ThenNamedFileValid() { - assertNotNull(defaultDependency); - assertEquals("Another Arbitrary Dependency", namedDependency.toString()); - } -} From f3c3086b0793c88cc1c10dfae9a59f558fc1c831 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 15 Jul 2020 17:31:47 +0530 Subject: [PATCH 031/132] JAVA-628: Moved 3 articles to spring-di-2, added README --- spring-di-2/README.md | 11 ++++ spring-di-2/pom.xml | 16 +++++ .../com/baeldung/collection/BaeldungBean.java | 18 ++++++ .../baeldung/collection/CollectionConfig.java | 50 +++++++++++++++ .../collection/CollectionInjectionDemo.java | 21 +++++++ .../baeldung/collection/CollectionsBean.java | 62 +++++++++++++++++++ .../AnotherArbitraryDependency.java | 13 ++++ .../dependency/ArbitraryDependency.java | 13 ++++ .../YetAnotherArbitraryDependency.java | 13 ++++ .../staticvalue/injection/Application.java | 17 +++++ .../injection/PropertyController.java | 30 +++++++++ .../src/main/resources/application.properties | 1 + .../ApplicationContextTestAutowiredName.java | 9 +++ ...licationContextTestAutowiredQualifier.java | 25 ++++++++ .../ApplicationContextTestAutowiredType.java | 16 +++++ .../ApplicationContextTestInjectName.java | 17 +++++ ...ApplicationContextTestInjectQualifier.java | 23 +++++++ .../ApplicationContextTestInjectType.java | 16 +++++ ...pplicationContextTestResourceNameType.java | 16 +++++ ...plicationContextTestResourceQualifier.java | 22 +++++++ .../FieldAutowiredIntegrationTest.java | 30 +++++++++ .../FieldAutowiredNameIntegrationTest.java | 30 +++++++++ ...ieldQualifierAutowiredIntegrationTest.java | 42 +++++++++++++ .../FieldByNameInjectIntegrationTest.java | 33 ++++++++++ .../inject/FieldInjectIntegrationTest.java | 31 ++++++++++ .../FieldQualifierInjectIntegrationTest.java | 42 +++++++++++++ ...FieldResourceInjectionIntegrationTest.java | 32 ++++++++++ ...hodByQualifierResourceIntegrationTest.java | 46 ++++++++++++++ .../MethodByTypeResourceIntegrationTest.java | 35 +++++++++++ ...ethodResourceInjectionIntegrationTest.java | 35 +++++++++++ .../NamedResourceIntegrationTest.java | 30 +++++++++ ...ifierResourceInjectionIntegrationTest.java | 43 +++++++++++++ ...etterResourceInjectionIntegrationTest.java | 34 ++++++++++ 33 files changed, 872 insertions(+) create mode 100644 spring-di-2/README.md create mode 100644 spring-di-2/src/main/java/com/baeldung/collection/BaeldungBean.java create mode 100644 spring-di-2/src/main/java/com/baeldung/collection/CollectionConfig.java create mode 100644 spring-di-2/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java create mode 100644 spring-di-2/src/main/java/com/baeldung/collection/CollectionsBean.java create mode 100644 spring-di-2/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java create mode 100644 spring-di-2/src/main/java/com/baeldung/dependency/ArbitraryDependency.java create mode 100644 spring-di-2/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java create mode 100644 spring-di-2/src/main/java/com/baeldung/staticvalue/injection/Application.java create mode 100644 spring-di-2/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java create mode 100644 spring-di-2/src/main/resources/application.properties create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredName.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredQualifier.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredType.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectName.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectQualifier.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectType.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestResourceNameType.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestResourceQualifier.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldAutowiredIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldAutowiredNameIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldQualifierAutowiredIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldByNameInjectIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldInjectIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldQualifierInjectIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/FieldResourceInjectionIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByQualifierResourceIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByTypeResourceIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodResourceInjectionIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/NamedResourceIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/QualifierResourceInjectionIntegrationTest.java create mode 100644 spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/SetterResourceInjectionIntegrationTest.java diff --git a/spring-di-2/README.md b/spring-di-2/README.md new file mode 100644 index 0000000000..15249efa7c --- /dev/null +++ b/spring-di-2/README.md @@ -0,0 +1,11 @@ +## Spring Dependency Injection + +This module contains articles about dependency injection with Spring + +### Relevant Articles + +- [Injecting Spring Beans into Unmanaged Objects](https://www.baeldung.com/spring-inject-bean-into-unmanaged-objects) +- [Injecting a Value in a Static Field in Spring](https://www.baeldung.com/spring-inject-static-field) +- [Spring – Injecting Collections](https://www.baeldung.com/spring-injecting-collections) +- [Wiring in Spring: @Autowired, @Resource and @Inject](https://www.baeldung.com/spring-annotations-resource-inject-autowire) +- More articles: [[<-- prev]](/spring-di) \ No newline at end of file diff --git a/spring-di-2/pom.xml b/spring-di-2/pom.xml index 9b703d55d9..4dd92ca18c 100644 --- a/spring-di-2/pom.xml +++ b/spring-di-2/pom.xml @@ -25,11 +25,26 @@ spring-boot-starter-data-jpa ${spring-boot.version} + + org.springframework.boot + spring-boot-starter-web + ${spring-boot.version} + org.springframework spring-aspects ${spring.version} + + org.projectlombok + lombok + ${lombok.version} + + + javax.inject + javax.inject + ${javax.inject.version} + @@ -61,5 +76,6 @@ 2.3.1.RELEASE 1.11 + 1 \ No newline at end of file diff --git a/spring-di-2/src/main/java/com/baeldung/collection/BaeldungBean.java b/spring-di-2/src/main/java/com/baeldung/collection/BaeldungBean.java new file mode 100644 index 0000000000..6d7351df02 --- /dev/null +++ b/spring-di-2/src/main/java/com/baeldung/collection/BaeldungBean.java @@ -0,0 +1,18 @@ +package com.baeldung.collection; + +/** + * Created by Gebruiker on 5/22/2018. + */ +public class BaeldungBean { + + private String name; + + public BaeldungBean(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} diff --git a/spring-di-2/src/main/java/com/baeldung/collection/CollectionConfig.java b/spring-di-2/src/main/java/com/baeldung/collection/CollectionConfig.java new file mode 100644 index 0000000000..fbae2963e5 --- /dev/null +++ b/spring-di-2/src/main/java/com/baeldung/collection/CollectionConfig.java @@ -0,0 +1,50 @@ +package com.baeldung.collection; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; + +import java.util.*; + +@Configuration +public class CollectionConfig { + + @Bean + public CollectionsBean getCollectionsBean() { + return new CollectionsBean(new HashSet<>(Arrays.asList("John", "Adam", "Harry"))); + } + + @Bean + public List nameList(){ + return Arrays.asList("John", "Adam", "Harry", null); + } + + @Bean + public Map nameMap(){ + Map nameMap = new HashMap<>(); + nameMap.put(1, "John"); + nameMap.put(2, "Adam"); + nameMap.put(3, "Harry"); + return nameMap; + } + + @Bean + @Qualifier("CollectionsBean") + @Order(2) + public BaeldungBean getElement() { + return new BaeldungBean("John"); + } + + @Bean + @Order(3) + public BaeldungBean getAnotherElement() { + return new BaeldungBean("Adam"); + } + + @Bean + @Order(1) + public BaeldungBean getOneMoreElement() { + return new BaeldungBean("Harry"); + } +} diff --git a/spring-di-2/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java b/spring-di-2/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java new file mode 100644 index 0000000000..2ee265f134 --- /dev/null +++ b/spring-di-2/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java @@ -0,0 +1,21 @@ +package com.baeldung.collection; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +/** + * Created by Gebruiker on 5/18/2018. + */ +public class CollectionInjectionDemo { + + public static void main(String[] args) { + + ApplicationContext context = new AnnotationConfigApplicationContext(CollectionConfig.class); + CollectionsBean collectionsBean = context.getBean(CollectionsBean.class); + collectionsBean.printNameList(); + collectionsBean.printNameSet(); + collectionsBean.printNameMap(); + collectionsBean.printBeanList(); + collectionsBean.printNameListWithDefaults(); + } +} diff --git a/spring-di-2/src/main/java/com/baeldung/collection/CollectionsBean.java b/spring-di-2/src/main/java/com/baeldung/collection/CollectionsBean.java new file mode 100644 index 0000000000..fc90f2c6ff --- /dev/null +++ b/spring-di-2/src/main/java/com/baeldung/collection/CollectionsBean.java @@ -0,0 +1,62 @@ +package com.baeldung.collection; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; + +/** + * Created by Gebruiker on 5/18/2018. + */ +public class CollectionsBean { + + @Autowired + private List nameList; + + private Set nameSet; + + private Map nameMap; + + @Autowired(required = false) + @Qualifier("CollectionsBean") + private List beanList = new ArrayList<>(); + + @Value("${names.list:}#{T(java.util.Collections).emptyList()}") + private List nameListWithDefaultValue; + + public CollectionsBean() { + } + + public CollectionsBean(Set strings) { + this.nameSet = strings; + } + + @Autowired + public void setNameMap(Map nameMap) { + this.nameMap = nameMap; + } + + public void printNameList() { + System.out.println(nameList); + } + + public void printNameSet() { + System.out.println(nameSet); + } + + public void printNameMap() { + System.out.println(nameMap); + } + + public void printBeanList() { + System.out.println(beanList); + } + + public void printNameListWithDefaults() { + System.out.println(nameListWithDefaultValue); + } +} diff --git a/spring-di-2/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java b/spring-di-2/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java new file mode 100644 index 0000000000..0e19523b7e --- /dev/null +++ b/spring-di-2/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java @@ -0,0 +1,13 @@ +package com.baeldung.dependency; + +import org.springframework.stereotype.Component; + +@Component +public class AnotherArbitraryDependency extends ArbitraryDependency { + + private final String label = "Another Arbitrary Dependency"; + + public String toString() { + return label; + } +} diff --git a/spring-di-2/src/main/java/com/baeldung/dependency/ArbitraryDependency.java b/spring-di-2/src/main/java/com/baeldung/dependency/ArbitraryDependency.java new file mode 100644 index 0000000000..3c90492d2c --- /dev/null +++ b/spring-di-2/src/main/java/com/baeldung/dependency/ArbitraryDependency.java @@ -0,0 +1,13 @@ +package com.baeldung.dependency; + +import org.springframework.stereotype.Component; + +@Component(value = "autowiredFieldDependency") +public class ArbitraryDependency { + + private final String label = "Arbitrary Dependency"; + + public String toString() { + return label; + } +} diff --git a/spring-di-2/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java b/spring-di-2/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java new file mode 100644 index 0000000000..a88abd0924 --- /dev/null +++ b/spring-di-2/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java @@ -0,0 +1,13 @@ +package com.baeldung.dependency; + +import org.springframework.stereotype.Component; + +@Component +public class YetAnotherArbitraryDependency extends ArbitraryDependency { + + private final String label = "Yet Another Arbitrary Dependency"; + + public String toString() { + return label; + } +} diff --git a/spring-di-2/src/main/java/com/baeldung/staticvalue/injection/Application.java b/spring-di-2/src/main/java/com/baeldung/staticvalue/injection/Application.java new file mode 100644 index 0000000000..b4222ddcc9 --- /dev/null +++ b/spring-di-2/src/main/java/com/baeldung/staticvalue/injection/Application.java @@ -0,0 +1,17 @@ +package com.baeldung.staticvalue.injection; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) +@PropertySource("/application.properties") + +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-di-2/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java b/spring-di-2/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java new file mode 100644 index 0000000000..f5910ea4f8 --- /dev/null +++ b/spring-di-2/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java @@ -0,0 +1,30 @@ +package com.baeldung.staticvalue.injection; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Arrays; +import java.util.List; + +@RestController +public class PropertyController { + + @Value("${name}") + private String name; + + @Value("${name}") + private static String NAME_NULL; + + private static String NAME_STATIC; + + @Value("${name}") + public void setNameStatic(String name){ + PropertyController.NAME_STATIC = name; + } + + @GetMapping("/properties") + public List getProperties(){ + return Arrays.asList(this.name, NAME_STATIC, NAME_NULL) ; + } +} diff --git a/spring-di-2/src/main/resources/application.properties b/spring-di-2/src/main/resources/application.properties new file mode 100644 index 0000000000..828fa9cd2a --- /dev/null +++ b/spring-di-2/src/main/resources/application.properties @@ -0,0 +1 @@ +name = Inject a value to a static field diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredName.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredName.java new file mode 100644 index 0000000000..3046e68829 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredName.java @@ -0,0 +1,9 @@ +package com.baeldung.wiring.configuration; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = {"com.baeldung.dependency"}) +public class ApplicationContextTestAutowiredName { +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredQualifier.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredQualifier.java new file mode 100644 index 0000000000..33969ea69d --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredQualifier.java @@ -0,0 +1,25 @@ +package com.baeldung.wiring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.dependency.AnotherArbitraryDependency; +import com.baeldung.dependency.ArbitraryDependency; + +@Configuration +public class ApplicationContextTestAutowiredQualifier { + + @Bean + public ArbitraryDependency autowiredFieldDependency() { + ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency(); + + return autowiredFieldDependency; + } + + @Bean + public ArbitraryDependency anotherAutowiredFieldDependency() { + ArbitraryDependency anotherAutowiredFieldDependency = new AnotherArbitraryDependency(); + + return anotherAutowiredFieldDependency; + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredType.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredType.java new file mode 100644 index 0000000000..24cdd978e4 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestAutowiredType.java @@ -0,0 +1,16 @@ +package com.baeldung.wiring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.dependency.ArbitraryDependency; + +@Configuration +public class ApplicationContextTestAutowiredType { + + @Bean + public ArbitraryDependency autowiredFieldDependency() { + ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency(); + return autowiredFieldDependency; + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectName.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectName.java new file mode 100644 index 0000000000..cb465d0183 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectName.java @@ -0,0 +1,17 @@ +package com.baeldung.wiring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.dependency.ArbitraryDependency; +import com.baeldung.dependency.YetAnotherArbitraryDependency; + +@Configuration +public class ApplicationContextTestInjectName { + + @Bean + public ArbitraryDependency yetAnotherFieldInjectDependency() { + ArbitraryDependency yetAnotherFieldInjectDependency = new YetAnotherArbitraryDependency(); + return yetAnotherFieldInjectDependency; + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectQualifier.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectQualifier.java new file mode 100644 index 0000000000..c2a63dac9e --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectQualifier.java @@ -0,0 +1,23 @@ +package com.baeldung.wiring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.dependency.AnotherArbitraryDependency; +import com.baeldung.dependency.ArbitraryDependency; + +@Configuration +public class ApplicationContextTestInjectQualifier { + + @Bean + public ArbitraryDependency defaultFile() { + ArbitraryDependency defaultFile = new ArbitraryDependency(); + return defaultFile; + } + + @Bean + public ArbitraryDependency namedFile() { + ArbitraryDependency namedFile = new AnotherArbitraryDependency(); + return namedFile; + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectType.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectType.java new file mode 100644 index 0000000000..15a75b8f2d --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestInjectType.java @@ -0,0 +1,16 @@ +package com.baeldung.wiring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.dependency.ArbitraryDependency; + +@Configuration +public class ApplicationContextTestInjectType { + + @Bean + public ArbitraryDependency injectDependency() { + ArbitraryDependency injectDependency = new ArbitraryDependency(); + return injectDependency; + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestResourceNameType.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestResourceNameType.java new file mode 100644 index 0000000000..708ade7647 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestResourceNameType.java @@ -0,0 +1,16 @@ +package com.baeldung.wiring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.io.File; + +@Configuration +public class ApplicationContextTestResourceNameType { + + @Bean(name = "namedFile") + public File namedFile() { + File namedFile = new File("namedFile.txt"); + return namedFile; + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestResourceQualifier.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestResourceQualifier.java new file mode 100644 index 0000000000..87864b183e --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/ApplicationContextTestResourceQualifier.java @@ -0,0 +1,22 @@ +package com.baeldung.wiring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.io.File; + +@Configuration +public class ApplicationContextTestResourceQualifier { + + @Bean(name = "defaultFile") + public File defaultFile() { + File defaultFile = new File("defaultFile.txt"); + return defaultFile; + } + + @Bean(name = "namedFile") + public File namedFile() { + File namedFile = new File("namedFile.txt"); + return namedFile; + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldAutowiredIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldAutowiredIntegrationTest.java new file mode 100644 index 0000000000..f3f065ed4d --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldAutowiredIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.wiring.configuration.autowired; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.dependency.ArbitraryDependency; +import com.baeldung.wiring.configuration.ApplicationContextTestAutowiredType; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestAutowiredType.class) +public class FieldAutowiredIntegrationTest { + + @Autowired + private ArbitraryDependency fieldDependency; + + @Test + public void givenAutowired_WhenSetOnField_ThenDependencyResolved() { + assertNotNull(fieldDependency); + assertEquals("Arbitrary Dependency", fieldDependency.toString()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldAutowiredNameIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldAutowiredNameIntegrationTest.java new file mode 100644 index 0000000000..199241c7e2 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldAutowiredNameIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.wiring.configuration.autowired; + +import com.baeldung.dependency.ArbitraryDependency; +import com.baeldung.wiring.configuration.ApplicationContextTestAutowiredName; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestAutowiredName.class) +public class FieldAutowiredNameIntegrationTest { + + @Autowired + private ArbitraryDependency autowiredFieldDependency; + + @Test + public void givenAutowiredAnnotation_WhenOnField_ThenDependencyValid() { + assertNotNull(autowiredFieldDependency); + assertEquals("Arbitrary Dependency", autowiredFieldDependency.toString()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldQualifierAutowiredIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldQualifierAutowiredIntegrationTest.java new file mode 100644 index 0000000000..081fbf24ad --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/autowired/FieldQualifierAutowiredIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.wiring.configuration.autowired; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.dependency.ArbitraryDependency; +import com.baeldung.wiring.configuration.ApplicationContextTestAutowiredQualifier; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestAutowiredQualifier.class) +public class FieldQualifierAutowiredIntegrationTest { + + @Autowired + @Qualifier("autowiredFieldDependency") + private ArbitraryDependency fieldDependency1; + + @Autowired + @Qualifier("anotherAutowiredFieldDependency") + private ArbitraryDependency fieldDependency2; + + @Test + public void givenAutowiredQualifier_WhenOnField_ThenDep1Valid() { + assertNotNull(fieldDependency1); + assertEquals("Arbitrary Dependency", fieldDependency1.toString()); + } + + @Test + public void givenAutowiredQualifier_WhenOnField_ThenDep2Valid() { + assertNotNull(fieldDependency2); + assertEquals("Another Arbitrary Dependency", fieldDependency2.toString()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldByNameInjectIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldByNameInjectIntegrationTest.java new file mode 100644 index 0000000000..d1a75d73ea --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldByNameInjectIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.wiring.configuration.inject; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import javax.inject.Inject; +import javax.inject.Named; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.dependency.ArbitraryDependency; +import com.baeldung.wiring.configuration.ApplicationContextTestInjectName; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestInjectName.class) +public class FieldByNameInjectIntegrationTest { + + @Inject + @Named("yetAnotherFieldInjectDependency") + private ArbitraryDependency yetAnotherFieldInjectDependency; + + @Test + public void givenInjectQualifier_WhenSetOnField_ThenDependencyValid() { + assertNotNull(yetAnotherFieldInjectDependency); + assertEquals("Yet Another Arbitrary Dependency", yetAnotherFieldInjectDependency.toString()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldInjectIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldInjectIntegrationTest.java new file mode 100644 index 0000000000..995f560701 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldInjectIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.wiring.configuration.inject; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import javax.inject.Inject; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.dependency.ArbitraryDependency; +import com.baeldung.wiring.configuration.ApplicationContextTestInjectType; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestInjectType.class) +public class FieldInjectIntegrationTest { + + @Inject + private ArbitraryDependency fieldInjectDependency; + + @Test + public void givenInjectAnnotation_WhenOnField_ThenValidDependency() { + assertNotNull(fieldInjectDependency); + assertEquals("Arbitrary Dependency", fieldInjectDependency.toString()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldQualifierInjectIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldQualifierInjectIntegrationTest.java new file mode 100644 index 0000000000..67fa2bf3d4 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldQualifierInjectIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.wiring.configuration.inject; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import javax.inject.Inject; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.dependency.ArbitraryDependency; +import com.baeldung.wiring.configuration.ApplicationContextTestInjectQualifier; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestInjectQualifier.class) +public class FieldQualifierInjectIntegrationTest { + + @Inject + @Qualifier("defaultFile") + private ArbitraryDependency defaultDependency; + + @Inject + @Qualifier("namedFile") + private ArbitraryDependency namedDependency; + + @Test + public void givenInjectQualifier_WhenOnField_ThenDefaultFileValid() { + assertNotNull(defaultDependency); + assertEquals("Arbitrary Dependency", defaultDependency.toString()); + } + + @Test + public void givenInjectQualifier_WhenOnField_ThenNamedFileValid() { + assertNotNull(defaultDependency); + assertEquals("Another Arbitrary Dependency", namedDependency.toString()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/FieldResourceInjectionIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/FieldResourceInjectionIntegrationTest.java new file mode 100644 index 0000000000..938d557939 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/FieldResourceInjectionIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.wiring.configuration.resource; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.File; + +import javax.annotation.Resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.wiring.configuration.ApplicationContextTestResourceNameType; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceNameType.class) +public class FieldResourceInjectionIntegrationTest { + + @Resource(name = "namedFile") + private File defaultFile; + + @Test + public void givenResourceAnnotation_WhenOnField_ThenDependencyValid() { + assertNotNull(defaultFile); + assertEquals("namedFile.txt", defaultFile.getName()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByQualifierResourceIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByQualifierResourceIntegrationTest.java new file mode 100644 index 0000000000..f49bf70aba --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByQualifierResourceIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.wiring.configuration.resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.wiring.configuration.ApplicationContextTestResourceQualifier; + +import javax.annotation.Resource; +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceQualifier.class) +public class MethodByQualifierResourceIntegrationTest { + + private File arbDependency; + private File anotherArbDependency; + + @Test + public void givenResourceQualifier_WhenSetter_ThenValidDependencies() { + assertNotNull(arbDependency); + assertEquals("namedFile.txt", arbDependency.getName()); + assertNotNull(anotherArbDependency); + assertEquals("defaultFile.txt", anotherArbDependency.getName()); + } + + @Resource + @Qualifier("namedFile") + public void setArbDependency(File arbDependency) { + this.arbDependency = arbDependency; + } + + @Resource + @Qualifier("defaultFile") + public void setAnotherArbDependency(File anotherArbDependency) { + this.anotherArbDependency = anotherArbDependency; + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByTypeResourceIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByTypeResourceIntegrationTest.java new file mode 100644 index 0000000000..aecd02a1d5 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByTypeResourceIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.wiring.configuration.resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.wiring.configuration.ApplicationContextTestResourceNameType; + +import javax.annotation.Resource; +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceNameType.class) +public class MethodByTypeResourceIntegrationTest { + + private File defaultFile; + + @Resource + protected void setDefaultFile(File defaultFile) { + this.defaultFile = defaultFile; + } + + @Test + public void givenResourceAnnotation_WhenSetter_ThenValidDependency() { + assertNotNull(defaultFile); + assertEquals("namedFile.txt", defaultFile.getName()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodResourceInjectionIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodResourceInjectionIntegrationTest.java new file mode 100644 index 0000000000..4ef9368c28 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodResourceInjectionIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.wiring.configuration.resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.wiring.configuration.ApplicationContextTestResourceNameType; + +import javax.annotation.Resource; +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceNameType.class) +public class MethodResourceInjectionIntegrationTest { + + private File defaultFile; + + @Resource(name = "namedFile") + protected void setDefaultFile(File defaultFile) { + this.defaultFile = defaultFile; + } + + @Test + public void givenResourceAnnotation_WhenSetter_ThenDependencyValid() { + assertNotNull(defaultFile); + assertEquals("namedFile.txt", defaultFile.getName()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/NamedResourceIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/NamedResourceIntegrationTest.java new file mode 100644 index 0000000000..4339194f63 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/NamedResourceIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.wiring.configuration.resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.wiring.configuration.ApplicationContextTestResourceNameType; + +import javax.annotation.Resource; +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceNameType.class) +public class NamedResourceIntegrationTest { + + @Resource(name = "namedFile") + private File testFile; + + @Test + public void givenResourceAnnotation_WhenOnField_THEN_DEPENDENCY_Found() { + assertNotNull(testFile); + assertEquals("namedFile.txt", testFile.getName()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/QualifierResourceInjectionIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/QualifierResourceInjectionIntegrationTest.java new file mode 100644 index 0000000000..cc8c669757 --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/QualifierResourceInjectionIntegrationTest.java @@ -0,0 +1,43 @@ +package com.baeldung.wiring.configuration.resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.wiring.configuration.ApplicationContextTestResourceQualifier; + +import javax.annotation.Resource; +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceQualifier.class) +public class QualifierResourceInjectionIntegrationTest { + + @Resource + @Qualifier("defaultFile") + private File dependency1; + + @Resource + @Qualifier("namedFile") + private File dependency2; + + @Test + public void givenResourceAnnotation_WhenField_ThenDependency1Valid() { + assertNotNull(dependency1); + assertEquals("defaultFile.txt", dependency1.getName()); + } + + @Test + public void givenResourceQualifier_WhenField_ThenDependency2Valid() { + assertNotNull(dependency2); + assertEquals("namedFile.txt", dependency2.getName()); + } +} diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/SetterResourceInjectionIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/SetterResourceInjectionIntegrationTest.java new file mode 100644 index 0000000000..90c8677bff --- /dev/null +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/SetterResourceInjectionIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.wiring.configuration.resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.wiring.configuration.ApplicationContextTestResourceNameType; + +import javax.annotation.Resource; +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceNameType.class) +public class SetterResourceInjectionIntegrationTest { + + private File defaultFile; + + @Resource + protected void setDefaultFile(File defaultFile) { + this.defaultFile = defaultFile; + } + + @Test + public void givenResourceAnnotation_WhenOnSetter_THEN_MUST_INJECT_Dependency() { + assertNotNull(defaultFile); + assertEquals("namedFile.txt", defaultFile.getName()); + } +} From 7015c666912301c80cff0e181ad3f44bda117f72 Mon Sep 17 00:00:00 2001 From: mikr Date: Wed, 15 Jul 2020 22:12:07 +0200 Subject: [PATCH 032/132] JAVA-38 Move all Spring Cloud Modules to Boot 2 --- parent-boot-2/pom.xml | 1 + spring-cloud/pom.xml | 26 +++++++++---------- .../discovery/DiscoveryClientApplication.java | 4 ++- .../health/ServiceDiscoveryApplication.java | 5 +++- .../DistributedPropertiesApplication.java | 4 ++- .../feign-rest-consumer/pom.xml | 4 +++ .../hystrix/rest/consumer/GreetingClient.java | 2 +- .../RestConsumerFeignApplication.java | 2 +- ...putsServiceApplicationIntegrationTest.java | 6 ++--- ...sWithConditionsServiceIntegrationTest.java | 6 ++--- .../MyLoggerApplicationIntegrationTest.java | 2 +- .../spring-cloud-zookeeper/Greeting/pom.xml | 10 +++++-- .../cloud/greeting/HelloWorldClient.java | 4 +-- spring-cloud/spring-cloud-zookeeper/pom.xml | 3 +-- 14 files changed, 47 insertions(+), 32 deletions(-) diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index ab5424bfaf..ed0f327b8c 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -31,6 +31,7 @@ io.rest-assured rest-assured + ${rest-assured.version} org.springframework.boot diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 6fddb1693f..0e2cac1ff9 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -56,17 +56,15 @@ - 1.2.2.RELEASE - Brixton.SR7 - 1.2.2.RELEASE - 1.2.2.RELEASE - 2.0.2.RELEASE - 1.4.6.RELEASE - 1.2.3.RELEASE - 1.3.0.RELEASE - 1.4.2.RELEASE - 1.4.2.RELEASE - 1.2.3.RELEASE + Hoxton.SR4 + 2.2.3.RELEASE + 2.2.3.RELEASE + 1.4.7.RELEASE + 1.4.7.RELEASE + 1.4.7.RELEASE + 3.0.6.RELEASE + 2.3.1.RELEASE + 2.3.1.RELEASE diff --git a/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/discovery/DiscoveryClientApplication.java b/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/discovery/DiscoveryClientApplication.java index d013969ad3..e01799b8d9 100644 --- a/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/discovery/DiscoveryClientApplication.java +++ b/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/discovery/DiscoveryClientApplication.java @@ -4,12 +4,14 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import static org.springframework.boot.WebApplicationType.NONE; + @SpringBootApplication @EnableDiscoveryClient public class DiscoveryClientApplication { public static void main(String[] args) { - new SpringApplicationBuilder(DiscoveryClientApplication.class).web(true) + new SpringApplicationBuilder(DiscoveryClientApplication.class).web(NONE) .run(args); } diff --git a/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/health/ServiceDiscoveryApplication.java b/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/health/ServiceDiscoveryApplication.java index 020d7d017c..1ef3e34e08 100644 --- a/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/health/ServiceDiscoveryApplication.java +++ b/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/health/ServiceDiscoveryApplication.java @@ -1,13 +1,16 @@ package com.baeldung.spring.cloud.consul.health; +import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; +import static org.springframework.boot.WebApplicationType.NONE; + @SpringBootApplication public class ServiceDiscoveryApplication { public static void main(String[] args) { - new SpringApplicationBuilder(ServiceDiscoveryApplication.class).web(true) + new SpringApplicationBuilder(ServiceDiscoveryApplication.class).web(NONE) .run(args); } diff --git a/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/properties/DistributedPropertiesApplication.java b/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/properties/DistributedPropertiesApplication.java index c1d2b0acc5..d854b5aaba 100644 --- a/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/properties/DistributedPropertiesApplication.java +++ b/spring-cloud/spring-cloud-consul/src/main/java/com/baeldung/spring/cloud/consul/properties/DistributedPropertiesApplication.java @@ -4,12 +4,14 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.web.bind.annotation.RestController; +import static org.springframework.boot.WebApplicationType.NONE; + @SpringBootApplication @RestController public class DistributedPropertiesApplication { public static void main(String[] args) { - new SpringApplicationBuilder(DistributedPropertiesApplication.class).web(true) + new SpringApplicationBuilder(DistributedPropertiesApplication.class).web(NONE) .run(args); } diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml index 367b7c111e..acb9993881 100644 --- a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml @@ -36,18 +36,22 @@ org.springframework.cloud spring-cloud-starter-hystrix + ${spring-cloud-starter-hystrix.version} org.springframework.cloud spring-cloud-starter-hystrix-dashboard + ${spring-cloud-starter-hystrix.version} org.springframework.cloud spring-cloud-starter-feign + ${spring-cloud-starter-feign.version} org.springframework.boot spring-boot-starter-web + ${spring-boot-starter-web.version} org.springframework.boot diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java index 4fcfb0eeda..2a31917352 100644 --- a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java @@ -1,7 +1,7 @@ package com.baeldung.spring.cloud.hystrix.rest.consumer; import com.baeldung.spring.cloud.hystrix.rest.producer.GreetingController; -import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java index 2fc54216fe..044b0dbcb8 100644 --- a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java @@ -3,8 +3,8 @@ package com.baeldung.spring.cloud.hystrix.rest.consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; -import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; +import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableCircuitBreaker diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java index 898d06897f..c8b8c9f1a9 100644 --- a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java @@ -28,13 +28,13 @@ public class MultipleOutputsServiceApplicationIntegrationTest { @Test public void whenSendMessage_thenResponseIsInAOutput() { whenSendMessage(1); - thenPayloadInChannelIs(pipe.anOutput(), 1); + thenPayloadInChannelIs(pipe.anOutput(), "1"); } @Test public void whenSendMessage_thenResponseIsInAnotherOutput() { whenSendMessage(11); - thenPayloadInChannelIs(pipe.anotherOutput(), 11); + thenPayloadInChannelIs(pipe.anotherOutput(), "11"); } private void whenSendMessage(Integer val) { @@ -43,7 +43,7 @@ public class MultipleOutputsServiceApplicationIntegrationTest { .build()); } - private void thenPayloadInChannelIs(MessageChannel channel, Integer expectedValue) { + private void thenPayloadInChannelIs(MessageChannel channel, String expectedValue) { Object payload = messageCollector.forChannel(channel) .poll() .getPayload(); diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java index c3bf5a1205..1aa8d38aa1 100644 --- a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java @@ -28,13 +28,13 @@ public class MultipleOutputsWithConditionsServiceIntegrationTest { @Test public void whenSendMessage_thenResponseIsInAOutput() { whenSendMessage(1); - thenPayloadInChannelIs(pipe.anOutput(), 1); + thenPayloadInChannelIs(pipe.anOutput(), "1"); } @Test public void whenSendMessage_thenResponseIsInAnotherOutput() { whenSendMessage(11); - thenPayloadInChannelIs(pipe.anotherOutput(), 11); + thenPayloadInChannelIs(pipe.anotherOutput(), "11"); } private void whenSendMessage(Integer val) { @@ -43,7 +43,7 @@ public class MultipleOutputsWithConditionsServiceIntegrationTest { .build()); } - private void thenPayloadInChannelIs(MessageChannel channel, Integer expectedValue) { + private void thenPayloadInChannelIs(MessageChannel channel, String expectedValue) { Object payload = messageCollector.forChannel(channel) .poll() .getPayload(); diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java index 21d84e79e0..7e5f4fbec7 100644 --- a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java @@ -35,6 +35,6 @@ public class MyLoggerApplicationIntegrationTest { .poll() .getPayload(); - assertEquals("[1]: This is my message", payload.toString()); + assertEquals("{\"message\":\"[1]: This is my message\"}", payload.toString()); } } diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml index ac469d8bc4..871218e78c 100644 --- a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml @@ -30,6 +30,10 @@ spring-boot-starter ${spring-boot.version} + + org.springframework.boot + spring-boot-starter-web + org.springframework spring-web @@ -56,7 +60,10 @@ spring-cloud-starter-feign ${spring-cloud-starter-feign.version} - + + org.springframework.cloud + spring-cloud-starter-openfeign + org.springframework.boot spring-boot-starter-test @@ -71,7 +78,6 @@ - 1.2.5.RELEASE 1.3 diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/src/main/java/com/baeldung/spring/cloud/greeting/HelloWorldClient.java b/spring-cloud/spring-cloud-zookeeper/Greeting/src/main/java/com/baeldung/spring/cloud/greeting/HelloWorldClient.java index c56cb1907a..dc90576e08 100644 --- a/spring-cloud/spring-cloud-zookeeper/Greeting/src/main/java/com/baeldung/spring/cloud/greeting/HelloWorldClient.java +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/src/main/java/com/baeldung/spring/cloud/greeting/HelloWorldClient.java @@ -2,8 +2,8 @@ package com.baeldung.spring.cloud.greeting; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; diff --git a/spring-cloud/spring-cloud-zookeeper/pom.xml b/spring-cloud/spring-cloud-zookeeper/pom.xml index 64d30b19a6..244ccbd957 100644 --- a/spring-cloud/spring-cloud-zookeeper/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/pom.xml @@ -18,8 +18,7 @@ - 1.5.2.RELEASE - 4.3.7.RELEASE + 5.2.7.RELEASE 1.0.3.RELEASE From 03c92a6023f4f5a65a8a23ff11c1cf507f1e6f70 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Thu, 16 Jul 2020 10:31:54 +0430 Subject: [PATCH 033/132] Moved to Specific Package --- .../main/java/com/baeldung/{ => falsesharing}/FalseSharing.java | 2 +- .../main/java/com/baeldung/{ => falsesharing}/LongAdder.java | 2 +- .../main/java/com/baeldung/{ => falsesharing}/Striped64.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename jmh/src/main/java/com/baeldung/{ => falsesharing}/FalseSharing.java (93%) rename jmh/src/main/java/com/baeldung/{ => falsesharing}/LongAdder.java (99%) rename jmh/src/main/java/com/baeldung/{ => falsesharing}/Striped64.java (99%) diff --git a/jmh/src/main/java/com/baeldung/FalseSharing.java b/jmh/src/main/java/com/baeldung/falsesharing/FalseSharing.java similarity index 93% rename from jmh/src/main/java/com/baeldung/FalseSharing.java rename to jmh/src/main/java/com/baeldung/falsesharing/FalseSharing.java index 24ba0c0b6b..faad31066b 100644 --- a/jmh/src/main/java/com/baeldung/FalseSharing.java +++ b/jmh/src/main/java/com/baeldung/falsesharing/FalseSharing.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.falsesharing; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; diff --git a/jmh/src/main/java/com/baeldung/LongAdder.java b/jmh/src/main/java/com/baeldung/falsesharing/LongAdder.java similarity index 99% rename from jmh/src/main/java/com/baeldung/LongAdder.java rename to jmh/src/main/java/com/baeldung/falsesharing/LongAdder.java index 8fd2b85c4f..06365ee3d2 100644 --- a/jmh/src/main/java/com/baeldung/LongAdder.java +++ b/jmh/src/main/java/com/baeldung/falsesharing/LongAdder.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.falsesharing; import java.io.Serializable; import java.util.concurrent.atomic.AtomicLong; diff --git a/jmh/src/main/java/com/baeldung/Striped64.java b/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java similarity index 99% rename from jmh/src/main/java/com/baeldung/Striped64.java rename to jmh/src/main/java/com/baeldung/falsesharing/Striped64.java index d305c334e0..284e62bc65 100644 --- a/jmh/src/main/java/com/baeldung/Striped64.java +++ b/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.falsesharing; import sun.misc.Unsafe; From c597e8dc6afefb5dbbe700047c24612d69ae76b9 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Thu, 16 Jul 2020 10:35:04 +0430 Subject: [PATCH 034/132] Added Javadoc Hint --- jmh/src/main/java/com/baeldung/falsesharing/LongAdder.java | 2 ++ jmh/src/main/java/com/baeldung/falsesharing/Striped64.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/jmh/src/main/java/com/baeldung/falsesharing/LongAdder.java b/jmh/src/main/java/com/baeldung/falsesharing/LongAdder.java index 06365ee3d2..39f9f981ab 100644 --- a/jmh/src/main/java/com/baeldung/falsesharing/LongAdder.java +++ b/jmh/src/main/java/com/baeldung/falsesharing/LongAdder.java @@ -4,6 +4,8 @@ import java.io.Serializable; import java.util.concurrent.atomic.AtomicLong; /** + * Copy-pasted from {@link java.util.concurrent.atomic.LongAdder} + * * One or more variables that together maintain an initially zero * {@code long} sum. When updates (method {@link #add}) are contended * across threads, the set of variables may grow dynamically to reduce diff --git a/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java b/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java index 284e62bc65..71c34a9de3 100644 --- a/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java +++ b/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java @@ -8,6 +8,8 @@ import java.util.function.DoubleBinaryOperator; import java.util.concurrent.ThreadLocalRandom; /** + * Copy-pasted from {@code java.util.concurrent.atomic.Striped64} class. + * * A package-local class holding common representation and mechanics * for classes supporting dynamic striping on 64bit values. The class * extends Number so that concrete subclasses must publicly do so. From 3ccb59bf84c06e6c50757af8440ca9d2b16ace4a Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 16 Jul 2020 09:15:40 +0200 Subject: [PATCH 035/132] BAEL-3917: Fix the integrations tests in ddd (#9708) --- .../config/CustomMongoConfiguration.java | 46 +++++++++++++++++++ ...ionTest.java => PersistOrderLiveTest.java} | 17 ++++--- ...ationTest.java => OrderMongoLiveTest.java} | 7 ++- ...> CassandraDbOrderRepositoryLiveTest.java} | 7 ++- ...va => MongoDbOrderRepositoryLiveTest.java} | 7 ++- 5 files changed, 75 insertions(+), 9 deletions(-) create mode 100644 ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java rename ddd/src/test/java/com/baeldung/ddd/order/jpa/{PersistOrderIntegrationTest.java => PersistOrderLiveTest.java} (84%) rename ddd/src/test/java/com/baeldung/ddd/order/mongo/{OrderMongoIntegrationTest.java => OrderMongoLiveTest.java} (87%) rename ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/{CassandraDbOrderRepositoryIntegrationTest.java => CassandraDbOrderRepositoryLiveTest.java} (87%) rename ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/{MongoDbOrderRepositoryIntegrationTest.java => MongoDbOrderRepositoryLiveTest.java} (87%) diff --git a/ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java b/ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java new file mode 100644 index 0000000000..fcc6a50267 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java @@ -0,0 +1,46 @@ +package com.baeldung.ddd.order.config; + +import org.bson.Document; +import org.joda.money.CurrencyUnit; +import org.joda.money.Money; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.ReadingConverter; +import org.springframework.data.mongodb.core.convert.MongoCustomConversions; + +import java.math.BigDecimal; +import java.util.Collections; + +@Configuration +public class CustomMongoConfiguration { + + @Bean + public MongoCustomConversions customConversions() { + return new MongoCustomConversions(Collections.singletonList(DocumentToMoneyConverter.INSTANCE)); + } + + @ReadingConverter + enum DocumentToMoneyConverter implements Converter { + + INSTANCE; + + @Override + public Money convert(Document source) { + Document money = source.get("money", Document.class); + + return Money.of(getCurrency(money), getAmount(money)); + } + + private CurrencyUnit getCurrency(Document money) { + Document currency = money.get("currency", Document.class); + String currencyCode = currency.getString("code"); + return CurrencyUnit.of(currencyCode); + } + + private BigDecimal getAmount(Document money) { + String amount = money.getString("amount"); + return BigDecimal.valueOf(Double.parseDouble(amount)); + } + } +} diff --git a/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderIntegrationTest.java b/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java similarity index 84% rename from ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderIntegrationTest.java rename to ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java index c503c9960b..8f30bc14a7 100644 --- a/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderIntegrationTest.java +++ b/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java @@ -1,19 +1,24 @@ package com.baeldung.ddd.order.jpa; -import static org.assertj.core.api.Assertions.assertThat; - -import java.math.BigDecimal; -import java.util.Arrays; - import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; +import java.math.BigDecimal; +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; + +/* + To run this test we need to run the databases first. + A dedicated docker-compose.yml file is located under the resources directory. + We can run it by simple executing `docker-compose up`. + */ @SpringJUnitConfig @SpringBootTest -public class PersistOrderIntegrationTest { +public class PersistOrderLiveTest { @Autowired private JpaOrderRepository repository; diff --git a/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoIntegrationTest.java b/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java similarity index 87% rename from ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoIntegrationTest.java rename to ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java index ca4315c416..38e00be0b0 100644 --- a/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoIntegrationTest.java +++ b/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java @@ -17,9 +17,14 @@ import com.baeldung.ddd.order.Order; import com.baeldung.ddd.order.OrderLine; import com.baeldung.ddd.order.Product; +/* + To run this test we need to run the databases first. + A dedicated docker-compose.yml file is located under the resources directory. + We can run it by simple executing `docker-compose up`. + */ @SpringJUnitConfig @SpringBootTest -public class OrderMongoIntegrationTest { +public class OrderMongoLiveTest { @Autowired private OrderMongoRepository repo; diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryIntegrationTest.java b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java similarity index 87% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryIntegrationTest.java rename to ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java index 668d1e5e34..4b44e1d7b4 100644 --- a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryIntegrationTest.java +++ b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java @@ -18,10 +18,15 @@ import com.baeldung.dddhexagonalspring.domain.Product; import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository; import com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra.SpringDataCassandraOrderRepository; +/* + To run this test we need to run the databases first. + A dedicated docker-compose.yml file is located under the resources directory. + We can run it by simple executing `docker-compose up`. + */ @SpringJUnitConfig @SpringBootTest @TestPropertySource("classpath:ddd-layers-test.properties") -class CassandraDbOrderRepositoryIntegrationTest { +class CassandraDbOrderRepositoryLiveTest { @Autowired private SpringDataCassandraOrderRepository cassandraOrderRepository; diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryIntegrationTest.java b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java similarity index 87% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryIntegrationTest.java rename to ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java index 9a7736c419..3cb3528448 100644 --- a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryIntegrationTest.java +++ b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java @@ -18,10 +18,15 @@ import com.baeldung.dddhexagonalspring.domain.Product; import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository; import com.baeldung.dddhexagonalspring.infrastracture.repository.mongo.SpringDataMongoOrderRepository; +/* + To run this test we need to run the databases first. + A dedicated docker-compose.yml file is located under the resources directory. + We can run it by simple executing `docker-compose up`. + */ @SpringJUnitConfig @SpringBootTest @TestPropertySource("classpath:ddd-layers-test.properties") -class MongoDbOrderRepositoryIntegrationTest { +class MongoDbOrderRepositoryLiveTest { @Autowired private SpringDataMongoOrderRepository mongoOrderRepository; From 0b083391bb81bf49f72594e7c337bcc17fa1c6d3 Mon Sep 17 00:00:00 2001 From: mikr Date: Thu, 16 Jul 2020 10:45:06 +0200 Subject: [PATCH 036/132] JAVA-2096 Add dummy file to make sure the directory is versioned --- core-java-modules/core-java-io-3/src/test/resources/dummy.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 core-java-modules/core-java-io-3/src/test/resources/dummy.txt diff --git a/core-java-modules/core-java-io-3/src/test/resources/dummy.txt b/core-java-modules/core-java-io-3/src/test/resources/dummy.txt new file mode 100644 index 0000000000..e69de29bb2 From 60ef1c85512c0ae4b5462935b84e66e8b9c20640 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Fri, 17 Jul 2020 03:46:41 +0200 Subject: [PATCH 037/132] JAVA-2116: Split or move libraries-data-2 module (#9716) * JAVA-2116: Move Java-R Integration to libraries-6 module * JAVA-2116: Move Guide to JMapper to libraries-data module --- libraries-6/README.md | 1 + libraries-6/pom.xml | 45 +++++++++++++++ .../main/java/com/baeldung/r/FastRMean.java | 3 - .../main/java/com/baeldung/r/RCallerMean.java | 6 +- .../src/main/java/com/baeldung/r/RUtils.java | 0 .../main/java/com/baeldung/r/RenjinMean.java | 9 ++- .../main/java/com/baeldung/r/RserveMean.java | 0 .../com/baeldung/r/FastRMeanUnitTest.java | 0 .../r/RCallerMeanIntegrationTest.java | 9 ++- .../com/baeldung/r/RenjinMeanUnitTest.java | 10 ++-- .../baeldung/r/RserveMeanIntegrationTest.java | 0 .../src/test/resources/script.R | 0 libraries-data-2/README.md | 2 - libraries-data-2/pom.xml | 55 ++----------------- libraries-data/README.md | 1 + libraries-data/pom.xml | 6 ++ .../main/java/com/baeldung/jmapper/User.java | 0 .../java/com/baeldung/jmapper/UserDto.java | 0 .../java/com/baeldung/jmapper/UserDto1.java | 0 .../com/baeldung/jmapper/relational/User.java | 0 .../baeldung/jmapper/relational/UserDto1.java | 0 .../baeldung/jmapper/relational/UserDto2.java | 0 .../jmapper/JMapperIntegrationTest.java | 3 + .../JMapperRelationalIntegrationTest.java | 4 +- .../src/test/resources/user_jmapper.xml | 0 .../src/test/resources/user_jmapper1.xml | 0 .../src/test/resources/user_jmapper2.xml | 0 27 files changed, 79 insertions(+), 75 deletions(-) rename {libraries-data-2 => libraries-6}/src/main/java/com/baeldung/r/FastRMean.java (92%) rename {libraries-data-2 => libraries-6}/src/main/java/com/baeldung/r/RCallerMean.java (100%) rename {libraries-data-2 => libraries-6}/src/main/java/com/baeldung/r/RUtils.java (100%) rename {libraries-data-2 => libraries-6}/src/main/java/com/baeldung/r/RenjinMean.java (99%) rename {libraries-data-2 => libraries-6}/src/main/java/com/baeldung/r/RserveMean.java (100%) rename {libraries-data-2 => libraries-6}/src/test/java/com/baeldung/r/FastRMeanUnitTest.java (100%) rename {libraries-data-2 => libraries-6}/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java (99%) rename {libraries-data-2 => libraries-6}/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java (99%) rename {libraries-data-2 => libraries-6}/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java (100%) rename {libraries-data-2 => libraries-6}/src/test/resources/script.R (100%) rename {libraries-data-2 => libraries-data}/src/main/java/com/baeldung/jmapper/User.java (100%) rename {libraries-data-2 => libraries-data}/src/main/java/com/baeldung/jmapper/UserDto.java (100%) rename {libraries-data-2 => libraries-data}/src/main/java/com/baeldung/jmapper/UserDto1.java (100%) rename {libraries-data-2 => libraries-data}/src/main/java/com/baeldung/jmapper/relational/User.java (100%) rename {libraries-data-2 => libraries-data}/src/main/java/com/baeldung/jmapper/relational/UserDto1.java (100%) rename {libraries-data-2 => libraries-data}/src/main/java/com/baeldung/jmapper/relational/UserDto2.java (100%) rename {libraries-data-2 => libraries-data}/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java (95%) rename {libraries-data-2 => libraries-data}/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java (97%) rename {libraries-data-2 => libraries-data}/src/test/resources/user_jmapper.xml (100%) rename {libraries-data-2 => libraries-data}/src/test/resources/user_jmapper1.xml (100%) rename {libraries-data-2 => libraries-data}/src/test/resources/user_jmapper2.xml (100%) diff --git a/libraries-6/README.md b/libraries-6/README.md index 5f74517ab5..3748522b9d 100644 --- a/libraries-6/README.md +++ b/libraries-6/README.md @@ -15,4 +15,5 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library) - [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) - [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) +- [Java-R Integration](https://www.baeldung.com/java-r-integration) - More articles [[<-- prev]](/libraries-5) diff --git a/libraries-6/pom.xml b/libraries-6/pom.xml index 030e5aa77b..2f8cc385cb 100644 --- a/libraries-6/pom.xml +++ b/libraries-6/pom.xml @@ -92,8 +92,50 @@ ${commonsio.version} test + + org.rosuda.REngine + Rserve + ${rserve.version} + + + com.github.jbytecode + RCaller + ${rcaller.version} + + + org.renjin + renjin-script-engine + ${renjin.version} + + + + + bedatadriven + bedatadriven public repo + https://nexus.bedatadriven.com/content/groups/public/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + com/baeldung/r/FastRMean.java + + + com/baeldung/r/FastRMeanUnitTest.java + + + + + + 2.0.0 1.10.0 @@ -105,6 +147,9 @@ 3.6 3.6.2 2.6 + RELEASE + 3.0 + 1.8.1 diff --git a/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java b/libraries-6/src/main/java/com/baeldung/r/FastRMean.java similarity index 92% rename from libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java rename to libraries-6/src/main/java/com/baeldung/r/FastRMean.java index 8348bfa403..1202cfaa2a 100644 --- a/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java +++ b/libraries-6/src/main/java/com/baeldung/r/FastRMean.java @@ -1,8 +1,5 @@ package com.baeldung.r; -import java.io.IOException; -import java.net.URISyntaxException; - /** * FastR showcase. * diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java b/libraries-6/src/main/java/com/baeldung/r/RCallerMean.java similarity index 100% rename from libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java rename to libraries-6/src/main/java/com/baeldung/r/RCallerMean.java index 99edb8c043..d07a989444 100644 --- a/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java +++ b/libraries-6/src/main/java/com/baeldung/r/RCallerMean.java @@ -1,12 +1,12 @@ package com.baeldung.r; -import java.io.IOException; -import java.net.URISyntaxException; - import com.github.rcaller.rstuff.RCaller; import com.github.rcaller.rstuff.RCallerOptions; import com.github.rcaller.rstuff.RCode; +import java.io.IOException; +import java.net.URISyntaxException; + /** * RCaller showcase. * diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java b/libraries-6/src/main/java/com/baeldung/r/RUtils.java similarity index 100% rename from libraries-data-2/src/main/java/com/baeldung/r/RUtils.java rename to libraries-6/src/main/java/com/baeldung/r/RUtils.java diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java b/libraries-6/src/main/java/com/baeldung/r/RenjinMean.java similarity index 99% rename from libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java rename to libraries-6/src/main/java/com/baeldung/r/RenjinMean.java index 4576ec5fb4..22cfad3a6f 100644 --- a/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java +++ b/libraries-6/src/main/java/com/baeldung/r/RenjinMean.java @@ -1,13 +1,12 @@ package com.baeldung.r; -import java.io.IOException; -import java.net.URISyntaxException; - -import javax.script.ScriptException; - import org.renjin.script.RenjinScriptEngine; import org.renjin.sexp.DoubleArrayVector; +import javax.script.ScriptException; +import java.io.IOException; +import java.net.URISyntaxException; + /** * Renjin showcase. * diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java b/libraries-6/src/main/java/com/baeldung/r/RserveMean.java similarity index 100% rename from libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java rename to libraries-6/src/main/java/com/baeldung/r/RserveMean.java diff --git a/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java b/libraries-6/src/test/java/com/baeldung/r/FastRMeanUnitTest.java similarity index 100% rename from libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java rename to libraries-6/src/test/java/com/baeldung/r/FastRMeanUnitTest.java diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java b/libraries-6/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java similarity index 99% rename from libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java rename to libraries-6/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java index ce6b3a4332..94dd9b89e5 100644 --- a/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java +++ b/libraries-6/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java @@ -1,14 +1,13 @@ package com.baeldung.r; -import java.io.IOException; -import java.net.URISyntaxException; - -import javax.script.ScriptException; - import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; +import javax.script.ScriptException; +import java.io.IOException; +import java.net.URISyntaxException; + /** * Test for {@link RCallerMean}. * diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java b/libraries-6/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java similarity index 99% rename from libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java rename to libraries-6/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java index f52d37d614..49472aaee6 100644 --- a/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java +++ b/libraries-6/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java @@ -1,13 +1,11 @@ package com.baeldung.r; -import java.io.IOException; -import java.net.URISyntaxException; - -import javax.script.ScriptException; - +import org.junit.Assert; import org.junit.Test; -import org.junit.Assert; +import javax.script.ScriptException; +import java.io.IOException; +import java.net.URISyntaxException; /** * Test for {@link RenjinMean}. diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java b/libraries-6/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java similarity index 100% rename from libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java rename to libraries-6/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java diff --git a/libraries-data-2/src/test/resources/script.R b/libraries-6/src/test/resources/script.R similarity index 100% rename from libraries-data-2/src/test/resources/script.R rename to libraries-6/src/test/resources/script.R diff --git a/libraries-data-2/README.md b/libraries-data-2/README.md index 3fd9242d82..a8f2a0cb37 100644 --- a/libraries-data-2/README.md +++ b/libraries-data-2/README.md @@ -8,10 +8,8 @@ This module contains articles about libraries for data processing in Java. - [Introduction to Conflict-Free Replicated Data Types](https://www.baeldung.com/java-conflict-free-replicated-data-types) - [Introduction to javax.measure](https://www.baeldung.com/javax-measure) - [A Guide to Infinispan in Java](https://www.baeldung.com/infinispan) -- [Guide to JMapper](https://www.baeldung.com/jmapper) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) - [Intro to Derive4J](https://www.baeldung.com/derive4j) -- [Java-R Integration](https://www.baeldung.com/java-r-integration) - [Univocity Parsers](https://www.baeldung.com/java-univocity-parsers) - [Using Kafka MockConsumer](https://www.baeldung.com/kafka-mockconsumer) - [Using Kafka MockProducer](https://www.baeldung.com/kafka-mockproducer) diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index 93a2f28167..26d8651cdd 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -86,11 +86,6 @@ spring-web ${spring.version} - - com.googlecode.jmapper-framework - jmapper-core - ${jmapper.version} - com.numericalmethod suanshu @@ -126,6 +121,11 @@ kafka-clients ${kafka.version} + + com.google.guava + guava + ${guava.version} + org.awaitility awaitility @@ -138,21 +138,6 @@ ${awaitility.version} test - - org.rosuda.REngine - Rserve - ${rserve.version} - - - com.github.jbytecode - RCaller - ${rcaller.version} - - - org.renjin - renjin-script-engine - ${renjin.version} - net.bytebuddy byte-buddy @@ -175,33 +160,8 @@ http://repo.numericalmethod.com/maven/ default - - - - bedatadriven - bedatadriven public repo - https://nexus.bedatadriven.com/content/groups/public/ - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - com/baeldung/r/FastRMean.java - - - com/baeldung/r/FastRMeanUnitTest.java - - - - - - 1.5.0 1.6.0 @@ -210,17 +170,14 @@ 9.1.5.Final 2.9.8 4.3.8.RELEASE - 1.6.0.1 4.0.0 1.1.0 3.6.2 1.7.25 3.0.0 2.8.4 - RELEASE - 3.0 - 1.8.1 2.5.0 + 29.0-jre \ No newline at end of file diff --git a/libraries-data/README.md b/libraries-data/README.md index 7614d11b16..44fddfd90e 100644 --- a/libraries-data/README.md +++ b/libraries-data/README.md @@ -12,4 +12,5 @@ This module contains articles about libraries for data processing in Java. - [Introduction to Kafka Connectors](https://www.baeldung.com/kafka-connectors-guide) - [Kafka Connect Example with MQTT and MongoDB](https://www.baeldung.com/kafka-connect-mqtt-mongodb) - [Building a Data Pipeline with Flink and Kafka](https://www.baeldung.com/kafka-flink-data-pipeline) +- [Guide to JMapper](https://www.baeldung.com/jmapper) More articles: [[next -->]](/../libraries-data-2) \ No newline at end of file diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 1267982c49..95d771ce4e 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -126,6 +126,11 @@ + + com.googlecode.jmapper-framework + jmapper-core + ${jmapper.version} + @@ -172,6 +177,7 @@ 0.15.0 2.2.0 1.7.25 + 1.6.0.1 diff --git a/libraries-data-2/src/main/java/com/baeldung/jmapper/User.java b/libraries-data/src/main/java/com/baeldung/jmapper/User.java similarity index 100% rename from libraries-data-2/src/main/java/com/baeldung/jmapper/User.java rename to libraries-data/src/main/java/com/baeldung/jmapper/User.java diff --git a/libraries-data-2/src/main/java/com/baeldung/jmapper/UserDto.java b/libraries-data/src/main/java/com/baeldung/jmapper/UserDto.java similarity index 100% rename from libraries-data-2/src/main/java/com/baeldung/jmapper/UserDto.java rename to libraries-data/src/main/java/com/baeldung/jmapper/UserDto.java diff --git a/libraries-data-2/src/main/java/com/baeldung/jmapper/UserDto1.java b/libraries-data/src/main/java/com/baeldung/jmapper/UserDto1.java similarity index 100% rename from libraries-data-2/src/main/java/com/baeldung/jmapper/UserDto1.java rename to libraries-data/src/main/java/com/baeldung/jmapper/UserDto1.java diff --git a/libraries-data-2/src/main/java/com/baeldung/jmapper/relational/User.java b/libraries-data/src/main/java/com/baeldung/jmapper/relational/User.java similarity index 100% rename from libraries-data-2/src/main/java/com/baeldung/jmapper/relational/User.java rename to libraries-data/src/main/java/com/baeldung/jmapper/relational/User.java diff --git a/libraries-data-2/src/main/java/com/baeldung/jmapper/relational/UserDto1.java b/libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto1.java similarity index 100% rename from libraries-data-2/src/main/java/com/baeldung/jmapper/relational/UserDto1.java rename to libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto1.java diff --git a/libraries-data-2/src/main/java/com/baeldung/jmapper/relational/UserDto2.java b/libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto2.java similarity index 100% rename from libraries-data-2/src/main/java/com/baeldung/jmapper/relational/UserDto2.java rename to libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto2.java diff --git a/libraries-data-2/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java similarity index 95% rename from libraries-data-2/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java index 177ef08d41..0b7a7c95f4 100644 --- a/libraries-data-2/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java @@ -7,6 +7,9 @@ import org.junit.Test; import java.time.LocalDate; import static com.googlecode.jmapper.api.JMapperAPI.*; +import static com.googlecode.jmapper.api.JMapperAPI.attribute; +import static com.googlecode.jmapper.api.JMapperAPI.global; +import static com.googlecode.jmapper.api.JMapperAPI.mappedClass; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/libraries-data-2/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java similarity index 97% rename from libraries-data-2/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java index a44d608a0a..7a497c4a83 100644 --- a/libraries-data-2/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java @@ -55,8 +55,8 @@ public class JMapperRelationalIntegrationTest { public void givenUser_whenUseApi_thenConverted(){ JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(User.class) - .add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class)) - .add(attribute("email").targetAttributes("username","email").targetClasses(UserDto1.class,UserDto2.class)) ) + .add(attribute("id").value("id").targetClasses(UserDto1.class, UserDto2.class)) + .add(attribute("email").targetAttributes("username","email").targetClasses(UserDto1.class, UserDto2.class)) ) ; RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class,jmapperApi); diff --git a/libraries-data-2/src/test/resources/user_jmapper.xml b/libraries-data/src/test/resources/user_jmapper.xml similarity index 100% rename from libraries-data-2/src/test/resources/user_jmapper.xml rename to libraries-data/src/test/resources/user_jmapper.xml diff --git a/libraries-data-2/src/test/resources/user_jmapper1.xml b/libraries-data/src/test/resources/user_jmapper1.xml similarity index 100% rename from libraries-data-2/src/test/resources/user_jmapper1.xml rename to libraries-data/src/test/resources/user_jmapper1.xml diff --git a/libraries-data-2/src/test/resources/user_jmapper2.xml b/libraries-data/src/test/resources/user_jmapper2.xml similarity index 100% rename from libraries-data-2/src/test/resources/user_jmapper2.xml rename to libraries-data/src/test/resources/user_jmapper2.xml From dc06936a5d22cbb5a09ac5488af58d30b1c90ad3 Mon Sep 17 00:00:00 2001 From: SauDev Date: Fri, 17 Jul 2020 11:43:25 +0530 Subject: [PATCH 038/132] BAEL-4135 - When are static variables initialized? (#9607) * Hexagonal Architecture in Java A quick and practical example of Hexagonal Architecture in Java * Fixed code formatting issues * When are static variables initialized Sample class and test class. * Revert "When are static variables initialized" This reverts commit c781923093ccc88bc269bea276653169065cb17b. * Revert "Revert "When are static variables initialized"" This reverts commit 2bffdf401d4e7dc2cefd7eb16357b2d51271edad. * New java module for static variable Created a new core-java-lang-3 module for static variables. * PR review changes: Added more scenarios to the static variable test Covered the following cases: 1. Variable initialization in a static block 2. Variable initialization in a static nested class --- core-java-modules/core-java-lang-3/pom.xml | 2 +- .../staticvariables/StaticVariableDemo.java | 23 ++++ .../StaticVariableUnitTest.java | 113 ++++++++++++++++++ patterns/hexagonal-architecture/pom.xml | 59 +++++++++ .../hexagonal/HexArchApplicationDemo.java | 13 ++ .../pattern/hexagonal/config/AppConfig.java | 15 +++ .../pattern/hexagonal/config/MongoConfig.java | 10 ++ .../controller/EmployeeController.java | 25 ++++ .../hexagonal/domain/model/Employee.java | 51 ++++++++ .../domain/services/EmployeeService.java | 10 ++ .../domain/services/EmployeeServiceImpl.java | 34 ++++++ .../persistence/EmployeeRepository.java | 15 +++ .../persistence/MongoDBRepository.java | 24 ++++ .../hexagonal/persistence/MongoRepoEx.java | 9 ++ .../src/main/resources/application.properties | 1 + .../services/EmployeeServiceImplTest.java | 46 +++++++ 16 files changed, 449 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-lang-3/src/main/java/com/baeldung/staticvariables/StaticVariableDemo.java create mode 100644 core-java-modules/core-java-lang-3/src/test/java/com/baeldung/staticvariables/StaticVariableUnitTest.java create mode 100644 patterns/hexagonal-architecture/pom.xml create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/HexArchApplicationDemo.java create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/config/AppConfig.java create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/config/MongoConfig.java create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/controller/EmployeeController.java create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/model/Employee.java create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeService.java create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImpl.java create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/EmployeeRepository.java create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/MongoDBRepository.java create mode 100644 patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/MongoRepoEx.java create mode 100644 patterns/hexagonal-architecture/src/main/resources/application.properties create mode 100644 patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplTest.java diff --git a/core-java-modules/core-java-lang-3/pom.xml b/core-java-modules/core-java-lang-3/pom.xml index 2a2856a80a..de290717b1 100644 --- a/core-java-modules/core-java-lang-3/pom.xml +++ b/core-java-modules/core-java-lang-3/pom.xml @@ -39,4 +39,4 @@ 3.12.2 - + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/staticvariables/StaticVariableDemo.java b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/staticvariables/StaticVariableDemo.java new file mode 100644 index 0000000000..917e9b0953 --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/staticvariables/StaticVariableDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.staticvariables; + +public class StaticVariableDemo { + public static int i; + public static int j = 20; + public static int z; + + static { + z = 30; + a = 40; + } + + public static int a = 50; + + public static final int b = 100; + + public StaticVariableDemo() { + } + + static class Nested { + public static String nestedClassStaticVariable = "test"; + } +} diff --git a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/staticvariables/StaticVariableUnitTest.java b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/staticvariables/StaticVariableUnitTest.java new file mode 100644 index 0000000000..06711a888b --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/staticvariables/StaticVariableUnitTest.java @@ -0,0 +1,113 @@ +package com.baeldung.staticvariables; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.reflect.Field; + +import org.junit.jupiter.api.Test; + +public class StaticVariableUnitTest { + + @Test + public void initializeStaticVariable_checkAssignedValues() { + + try { + Class staticVariableDemo = this.getClass() + .getClassLoader() + .loadClass("com.baeldung.staticvariables.StaticVariableDemo"); + + Field field1 = staticVariableDemo.getField("i"); + + assertThat(field1.getInt(staticVariableDemo)).isEqualTo(0); + + Field field2 = staticVariableDemo.getField("j"); + + assertThat(field2.getInt(staticVariableDemo)).isEqualTo(20); + + } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + } + + @Test + public void initializeStaticVariable_checkStaticBlock() { + + try { + Class staticVariableDemo = this.getClass() + .getClassLoader() + .loadClass("com.baeldung.staticvariables.StaticVariableDemo"); + + Field field1 = staticVariableDemo.getField("z"); + + assertThat(field1.getInt(staticVariableDemo)).isEqualTo(30); + + Field field2 = staticVariableDemo.getField("a"); + + assertThat(field2.getInt(staticVariableDemo)).isEqualTo(50); + + } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + } + + @Test + public void initializeStaticVariable_checkFinalValues() { + + try { + Class staticVariableDemo = this.getClass() + .getClassLoader() + .loadClass("com.baeldung.staticvariables.StaticVariableDemo"); + + Field field1 = staticVariableDemo.getField("b"); + + assertThat(field1.getInt(staticVariableDemo)).isEqualTo(100); + + } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + } + + @Test + public void initializeStaticVariable_checkInnerClassValues() { + + try { + Class staticVariableDemo = this.getClass() + .getClassLoader() + .loadClass("com.baeldung.staticvariables.StaticVariableDemo"); + + Class[] nestedClasses = staticVariableDemo.getClasses(); + + for (Class nestedClass : nestedClasses) { + if (nestedClass.getName() + .equals("Nested")) { + + Field field1 = nestedClass.getField("nestedClassStaticVariable"); + assertThat(field1.get(nestedClass)).isEqualTo("test"); + } + } + + } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + } +} diff --git a/patterns/hexagonal-architecture/pom.xml b/patterns/hexagonal-architecture/pom.xml new file mode 100644 index 0000000000..9317a25e56 --- /dev/null +++ b/patterns/hexagonal-architecture/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.0.RELEASE + + + com.baeldung + hexagonal-architecture + 1.0 + hexagonal-architecture + Project for hexagonal architecture in java + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.mockito + mockito-core + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/HexArchApplicationDemo.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/HexArchApplicationDemo.java new file mode 100644 index 0000000000..52aaefaaf7 --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/HexArchApplicationDemo.java @@ -0,0 +1,13 @@ +package com.baeldung.pattern.hexagonal; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HexArchApplicationDemo { + + public static void main(String[] args) { + SpringApplication.run(HexArchApplicationDemo.class, args); + } + +} diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/config/AppConfig.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/config/AppConfig.java new file mode 100644 index 0000000000..ee8a01d0e2 --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/config/AppConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.pattern.hexagonal.config; + +import com.baeldung.pattern.hexagonal.domain.services.EmployeeService; +import com.baeldung.pattern.hexagonal.domain.services.EmployeeServiceImpl; +import com.baeldung.pattern.hexagonal.persistence.EmployeeRepository; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class AppConfig { + @Bean + public EmployeeService getEmployeeService(EmployeeRepository employeeRepository) { + return new EmployeeServiceImpl(employeeRepository); + } +} diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/config/MongoConfig.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/config/MongoConfig.java new file mode 100644 index 0000000000..fa6980824a --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/config/MongoConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.pattern.hexagonal.config; + +import com.baeldung.pattern.hexagonal.persistence.MongoRepoEx; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; + +@Configuration +@EnableMongoRepositories(basePackageClasses = MongoRepoEx.class) +public class MongoConfig { +} diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/controller/EmployeeController.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/controller/EmployeeController.java new file mode 100644 index 0000000000..077fc6fdea --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/controller/EmployeeController.java @@ -0,0 +1,25 @@ +package com.baeldung.pattern.hexagonal.controller; + +import com.baeldung.pattern.hexagonal.domain.model.Employee; +import com.baeldung.pattern.hexagonal.domain.services.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/employees") +public class EmployeeController { + @Autowired + EmployeeService employeeService; + + @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + public Employee addEmployee(@RequestBody Employee employee) { + return employeeService.addEmployee(employee); + } + + @GetMapping(path = "/{employeeId}") + public Employee getEmployee(@PathVariable("employeeId") String employeeId) { + return employeeService.getEmployee(employeeId); + } +} diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/model/Employee.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/model/Employee.java new file mode 100644 index 0000000000..de1f15cf53 --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/model/Employee.java @@ -0,0 +1,51 @@ +package com.baeldung.pattern.hexagonal.domain.model; + +import org.springframework.data.annotation.Id; + +import java.util.Objects; + +public class Employee { + @Id + private String empId; + private String empName; + private String empJobTitle; + + public String getEmpId() { + return empId; + } + + public void setEmpId(String empId) { + this.empId = empId; + } + + public String getEmpName() { + return empName; + } + + public void setEmpName(String empName) { + this.empName = empName; + } + + public String getEmpJobTitle() { + return empJobTitle; + } + + public void setEmpJobTitle(String empJobTitle) { + this.empJobTitle = empJobTitle; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Employee employee = (Employee) o; + return empId.equals(employee.empId); + } + + @Override + public int hashCode() { + return Objects.hash(empId); + } +} \ No newline at end of file diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeService.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeService.java new file mode 100644 index 0000000000..902abefabb --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeService.java @@ -0,0 +1,10 @@ +package com.baeldung.pattern.hexagonal.domain.services; + +import com.baeldung.pattern.hexagonal.domain.model.Employee; + +public interface EmployeeService { + + Employee addEmployee(Employee employee); + + Employee getEmployee(String employeeId); +} diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImpl.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImpl.java new file mode 100644 index 0000000000..cd7c30ff30 --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImpl.java @@ -0,0 +1,34 @@ +package com.baeldung.pattern.hexagonal.domain.services; + +import com.baeldung.pattern.hexagonal.domain.model.Employee; +import com.baeldung.pattern.hexagonal.persistence.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Optional; + +public class EmployeeServiceImpl implements EmployeeService { + + private EmployeeRepository employeeRepository; + + @Autowired + public EmployeeServiceImpl(EmployeeRepository employeeRepository) { + this.employeeRepository = employeeRepository; + } + + @Override + public Employee addEmployee(Employee employee) { + return employeeRepository.add(employee); + } + + @Override + public Employee getEmployee(String employeeId) { + Optional employee = employeeRepository.findById(employeeId); + + if (employee.isPresent()) { + return employee.get(); + } else { + // throw + } + return null; + } +} diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/EmployeeRepository.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/EmployeeRepository.java new file mode 100644 index 0000000000..53b4b6d276 --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/EmployeeRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.pattern.hexagonal.persistence; + +import com.baeldung.pattern.hexagonal.domain.model.Employee; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface EmployeeRepository { + + Employee add(Employee employee); + + Optional findById(String id); + +} diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/MongoDBRepository.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/MongoDBRepository.java new file mode 100644 index 0000000000..08f0c96ab0 --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/MongoDBRepository.java @@ -0,0 +1,24 @@ +package com.baeldung.pattern.hexagonal.persistence; + +import com.baeldung.pattern.hexagonal.domain.model.Employee; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public class MongoDBRepository implements EmployeeRepository { + + @Autowired + MongoRepoEx mongoRepository; + + @Override + public Employee add(Employee employee) { + return mongoRepository.insert(employee); + } + + @Override + public Optional findById(String id) { + return mongoRepository.findById(id); + } +} diff --git a/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/MongoRepoEx.java b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/MongoRepoEx.java new file mode 100644 index 0000000000..766444c22f --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/java/com/baeldung/pattern/hexagonal/persistence/MongoRepoEx.java @@ -0,0 +1,9 @@ +package com.baeldung.pattern.hexagonal.persistence; + +import com.baeldung.pattern.hexagonal.domain.model.Employee; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface MongoRepoEx extends MongoRepository { +} diff --git a/patterns/hexagonal-architecture/src/main/resources/application.properties b/patterns/hexagonal-architecture/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/patterns/hexagonal-architecture/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplTest.java b/patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplTest.java new file mode 100644 index 0000000000..cadb3b094b --- /dev/null +++ b/patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplTest.java @@ -0,0 +1,46 @@ +package com.baeldung.pattern.hexagonal.domain.services; + +import com.baeldung.pattern.hexagonal.domain.model.Employee; +import com.baeldung.pattern.hexagonal.persistence.EmployeeRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class EmployeeServiceImplTest { + + private EmployeeRepository employeeRepository; + private EmployeeService testService; + private Employee testModel; + + @BeforeEach + void setUp() { + employeeRepository = mock(EmployeeRepository.class); + + testService = new EmployeeServiceImpl(employeeRepository); + testModel = new Employee(); + testModel.setEmpId("2000"); + testModel.setEmpName("Test user 1"); + testModel.setEmpJobTitle("Software engineer"); + } + + @Test + void addEmployee() { + when(employeeRepository.add(any(Employee.class))).thenReturn(testModel); + + Employee testResponse = testService.addEmployee(testModel); + assertEquals(testModel, testResponse); + } + + @Test + void getEmployee() { + when(employeeRepository.findById("2000")).thenReturn(Optional.of(testModel)); + + Employee testResponse = testService.getEmployee("2000"); + assertEquals(testModel, testResponse); + } +} \ No newline at end of file From be1f906a9a9217a7eecf612c849eac4a851db135 Mon Sep 17 00:00:00 2001 From: Adrian Maghear Date: Fri, 17 Jul 2020 10:54:38 +0200 Subject: [PATCH 039/132] [BAEL4288] initial commit --- persistence-modules/flyway-repair/README.MD | 3 + .../flyway-repair/docker-compose/.env | 2 + .../docker-compose/docker-compose.yaml | 23 ++++ .../flyway-repair/docker-compose/mysql.env | 5 + .../flyway-repair/docker-compose/postgres.env | 3 + persistence-modules/flyway-repair/pom.xml | 105 ++++++++++++++++++ .../flywaycallbacks/FlywayApplication.java | 13 +++ .../application-callbacks.properties | 1 + .../main/resources/application-h2.properties | 3 + .../resources/application-mysql.properties | 3 + .../resources/application-postgres.properties | 3 + .../src/main/resources/application.properties | 6 + .../db/callbacks/afterMigrateError.sql | 1 + .../db/migration/V1_0__add_table_one.sql | 3 + .../db/migration/V1_1__add_table_two.sql | 3 + .../db/migration/V1_2__add_table_three.sql | 3 + .../db/migration/V1_3__add_table.sql | 3 + .../src/main/resources/logback.xml | 19 ++++ 18 files changed, 202 insertions(+) create mode 100644 persistence-modules/flyway-repair/README.MD create mode 100644 persistence-modules/flyway-repair/docker-compose/.env create mode 100644 persistence-modules/flyway-repair/docker-compose/docker-compose.yaml create mode 100644 persistence-modules/flyway-repair/docker-compose/mysql.env create mode 100644 persistence-modules/flyway-repair/docker-compose/postgres.env create mode 100644 persistence-modules/flyway-repair/pom.xml create mode 100644 persistence-modules/flyway-repair/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java create mode 100644 persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties create mode 100644 persistence-modules/flyway-repair/src/main/resources/application-h2.properties create mode 100644 persistence-modules/flyway-repair/src/main/resources/application-mysql.properties create mode 100644 persistence-modules/flyway-repair/src/main/resources/application-postgres.properties create mode 100644 persistence-modules/flyway-repair/src/main/resources/application.properties create mode 100644 persistence-modules/flyway-repair/src/main/resources/db/callbacks/afterMigrateError.sql create mode 100644 persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table_one.sql create mode 100644 persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table_two.sql create mode 100644 persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table_three.sql create mode 100644 persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql create mode 100644 persistence-modules/flyway-repair/src/main/resources/logback.xml diff --git a/persistence-modules/flyway-repair/README.MD b/persistence-modules/flyway-repair/README.MD new file mode 100644 index 0000000000..daeb9012b5 --- /dev/null +++ b/persistence-modules/flyway-repair/README.MD @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway) +- [A Guide to Flyway Callbacks](http://www.baeldung.com/flyway-callbacks) diff --git a/persistence-modules/flyway-repair/docker-compose/.env b/persistence-modules/flyway-repair/docker-compose/.env new file mode 100644 index 0000000000..52bd0d6510 --- /dev/null +++ b/persistence-modules/flyway-repair/docker-compose/.env @@ -0,0 +1,2 @@ +MYSQL_PORT=3316 +POSTGRES_PORT=5431 \ No newline at end of file diff --git a/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml b/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml new file mode 100644 index 0000000000..23270c043d --- /dev/null +++ b/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml @@ -0,0 +1,23 @@ +version: '3.0' + +services: + mysql-test: + image: mysql:8.0.17 + ports: + - ${MYSQL_PORT}:3306 + env_file: + - mysql.env + networks: + - baeldung + + postgres-test: + image: postgres:11.5 + ports: + - ${POSTGRES_PORT}:5432 + env_file: postgres.env + networks: + - baeldung + +networks: + baeldung: + driver: bridge \ No newline at end of file diff --git a/persistence-modules/flyway-repair/docker-compose/mysql.env b/persistence-modules/flyway-repair/docker-compose/mysql.env new file mode 100644 index 0000000000..597344d88c --- /dev/null +++ b/persistence-modules/flyway-repair/docker-compose/mysql.env @@ -0,0 +1,5 @@ +MYSQL_ROOT_PASSWORD=password +MYSQL_RANDOM_ROOT_PASSWORD=yes +MYSQL_USER=testuser +MYSQL_PASSWORD=password +MYSQL_DATABASE=testdb \ No newline at end of file diff --git a/persistence-modules/flyway-repair/docker-compose/postgres.env b/persistence-modules/flyway-repair/docker-compose/postgres.env new file mode 100644 index 0000000000..1e7373fdf0 --- /dev/null +++ b/persistence-modules/flyway-repair/docker-compose/postgres.env @@ -0,0 +1,3 @@ +POSTGRES_USER=testuser +POSTGRES_PASSWORD=password +POSTGRES_DB=testdb diff --git a/persistence-modules/flyway-repair/pom.xml b/persistence-modules/flyway-repair/pom.xml new file mode 100644 index 0000000000..f9d62d5dad --- /dev/null +++ b/persistence-modules/flyway-repair/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + flyway + flyway-repair + jar + Flyway Repair Demo + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.flywaydb + flyway-core + ${flyway-core.version} + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + + + org.flywaydb + flyway-maven-plugin + ${flyway-maven-plugin.version} + + + org.springframework.boot + spring-boot-maven-plugin + + + + + true + src/main/resources + + *.properties + db/**/*.sql + + + + + + + 6.5.0 + 6.5.0 + src/main/resources/application-${db.engine}.properties + + + + + + h2 + + h2 + + + + com.h2database + h2 + runtime + + + + + + mysql + + mysql + + + + mysql + mysql-connector-java + runtime + + + + + + postgres + + postgres + + + + org.postgresql + postgresql + runtime + + + + + + + diff --git a/persistence-modules/flyway-repair/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java b/persistence-modules/flyway-repair/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java new file mode 100644 index 0000000000..34d794f7d1 --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.flywaycallbacks; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FlywayApplication { + + public static void main(String[] args) { + SpringApplication.run(FlywayApplication.class, args); + } + +} diff --git a/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties b/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties new file mode 100644 index 0000000000..2c10fc711f --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties @@ -0,0 +1 @@ +flyway.locations=db/migration,db/callbacks \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/application-h2.properties b/persistence-modules/flyway-repair/src/main/resources/application-h2.properties new file mode 100644 index 0000000000..15bd482adf --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/application-h2.properties @@ -0,0 +1,3 @@ +flyway.url=jdbc:h2:file:./testdb;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE;MODE=MySQL;DATABASE_TO_UPPER=false; +flyway.user=testuser +flyway.password=password \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/application-mysql.properties b/persistence-modules/flyway-repair/src/main/resources/application-mysql.properties new file mode 100644 index 0000000000..341f978068 --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/application-mysql.properties @@ -0,0 +1,3 @@ +flyway.url=jdbc:mysql://127.0.0.1:3316/testdb +flyway.user=testuser +flyway.password=password \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/application-postgres.properties b/persistence-modules/flyway-repair/src/main/resources/application-postgres.properties new file mode 100644 index 0000000000..5afaca96b5 --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/application-postgres.properties @@ -0,0 +1,3 @@ +flyway.url=jdbc:postgresql://127.0.0.1:5431/testdb +flyway.user=testuser +flyway.password=password \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/application.properties b/persistence-modules/flyway-repair/src/main/resources/application.properties new file mode 100644 index 0000000000..3fae835eb1 --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring.profiles.include=@db.engine@ + +spring.datasource.url=${flyway.url} +spring.datasource.username=${flyway.user} +spring.datasource.password=${flyway.password} +spring.flyway.locations=${flyway.locations:db/migration} \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/db/callbacks/afterMigrateError.sql b/persistence-modules/flyway-repair/src/main/resources/db/callbacks/afterMigrateError.sql new file mode 100644 index 0000000000..c975e85056 --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/db/callbacks/afterMigrateError.sql @@ -0,0 +1 @@ +DELETE FROM flyway_schema_history WHERE success=false; \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table_one.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table_one.sql new file mode 100644 index 0000000000..ec434dd5b2 --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table_one.sql @@ -0,0 +1,3 @@ +create table table_one ( + id numeric primary key +); \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table_two.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table_two.sql new file mode 100644 index 0000000000..48720d59d6 --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table_two.sql @@ -0,0 +1,3 @@ +create table table_two ( + id numeric primary key +); \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table_three.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table_three.sql new file mode 100644 index 0000000000..1917c88b9b --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table_three.sql @@ -0,0 +1,3 @@ +create table table_three ( + id numeric primary key +); \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql new file mode 100644 index 0000000000..ec434dd5b2 --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql @@ -0,0 +1,3 @@ +create table table_one ( + id numeric primary key +); \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/logback.xml b/persistence-modules/flyway-repair/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/persistence-modules/flyway-repair/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file From 8a98cce3db70202418486de4962e32eaaf5c6ed9 Mon Sep 17 00:00:00 2001 From: Adrian Maghear Date: Fri, 17 Jul 2020 15:13:57 +0200 Subject: [PATCH 040/132] [BAEL4288] remove mysql flow --- .../flyway-repair/docker-compose/.env | 1 - .../docker-compose/docker-compose.yaml | 8 ---- .../flyway-repair/docker-compose/mysql.env | 5 --- persistence-modules/flyway-repair/pom.xml | 43 ++++--------------- .../application-callbacks.properties | 2 +- .../resources/application-mysql.properties | 3 -- .../src/main/resources/application.properties | 3 -- .../afterMigrateError__repair.sql} | 0 ..._add_table_one.sql => V1_0__add_table.sql} | 0 ..._add_table_two.sql => V1_1__add_table.sql} | 0 ...dd_table_three.sql => V1_2__add_table.sql} | 0 .../db/migration/V1_3__add_table.sql | 2 +- 12 files changed, 11 insertions(+), 56 deletions(-) delete mode 100644 persistence-modules/flyway-repair/docker-compose/mysql.env delete mode 100644 persistence-modules/flyway-repair/src/main/resources/application-mysql.properties rename persistence-modules/flyway-repair/src/main/resources/db/{callbacks/afterMigrateError.sql => callback/afterMigrateError__repair.sql} (100%) rename persistence-modules/flyway-repair/src/main/resources/db/migration/{V1_0__add_table_one.sql => V1_0__add_table.sql} (100%) rename persistence-modules/flyway-repair/src/main/resources/db/migration/{V1_1__add_table_two.sql => V1_1__add_table.sql} (100%) rename persistence-modules/flyway-repair/src/main/resources/db/migration/{V1_2__add_table_three.sql => V1_2__add_table.sql} (100%) diff --git a/persistence-modules/flyway-repair/docker-compose/.env b/persistence-modules/flyway-repair/docker-compose/.env index 52bd0d6510..69785c6e5c 100644 --- a/persistence-modules/flyway-repair/docker-compose/.env +++ b/persistence-modules/flyway-repair/docker-compose/.env @@ -1,2 +1 @@ -MYSQL_PORT=3316 POSTGRES_PORT=5431 \ No newline at end of file diff --git a/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml b/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml index 23270c043d..b3502f8775 100644 --- a/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml +++ b/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml @@ -1,14 +1,6 @@ version: '3.0' services: - mysql-test: - image: mysql:8.0.17 - ports: - - ${MYSQL_PORT}:3306 - env_file: - - mysql.env - networks: - - baeldung postgres-test: image: postgres:11.5 diff --git a/persistence-modules/flyway-repair/docker-compose/mysql.env b/persistence-modules/flyway-repair/docker-compose/mysql.env deleted file mode 100644 index 597344d88c..0000000000 --- a/persistence-modules/flyway-repair/docker-compose/mysql.env +++ /dev/null @@ -1,5 +0,0 @@ -MYSQL_ROOT_PASSWORD=password -MYSQL_RANDOM_ROOT_PASSWORD=yes -MYSQL_USER=testuser -MYSQL_PASSWORD=password -MYSQL_DATABASE=testdb \ No newline at end of file diff --git a/persistence-modules/flyway-repair/pom.xml b/persistence-modules/flyway-repair/pom.xml index f9d62d5dad..4d61bd5c0e 100644 --- a/persistence-modules/flyway-repair/pom.xml +++ b/persistence-modules/flyway-repair/pom.xml @@ -18,7 +18,6 @@ org.flywaydb flyway-core - ${flyway-core.version} org.springframework.boot @@ -31,37 +30,23 @@ org.flywaydb flyway-maven-plugin - ${flyway-maven-plugin.version} org.springframework.boot spring-boot-maven-plugin - - - true - src/main/resources - - *.properties - db/**/*.sql - - - - - 6.5.0 - 6.5.0 - src/main/resources/application-${db.engine}.properties - - h2 + + true + - h2 + h2 @@ -72,24 +57,10 @@ - - mysql - - mysql - - - - mysql - mysql-connector-java - runtime - - - - postgres - postgres + postgres @@ -102,4 +73,8 @@ + + src/main/resources/application-${spring-boot.run.profiles}.properties + + diff --git a/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties b/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties index 2c10fc711f..7fb3124764 100644 --- a/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties +++ b/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties @@ -1 +1 @@ -flyway.locations=db/migration,db/callbacks \ No newline at end of file +spring.flyway.locations=classpath:db/migration,classpath:db/callback \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/application-mysql.properties b/persistence-modules/flyway-repair/src/main/resources/application-mysql.properties deleted file mode 100644 index 341f978068..0000000000 --- a/persistence-modules/flyway-repair/src/main/resources/application-mysql.properties +++ /dev/null @@ -1,3 +0,0 @@ -flyway.url=jdbc:mysql://127.0.0.1:3316/testdb -flyway.user=testuser -flyway.password=password \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/application.properties b/persistence-modules/flyway-repair/src/main/resources/application.properties index 3fae835eb1..da666d3cc2 100644 --- a/persistence-modules/flyway-repair/src/main/resources/application.properties +++ b/persistence-modules/flyway-repair/src/main/resources/application.properties @@ -1,6 +1,3 @@ -spring.profiles.include=@db.engine@ - spring.datasource.url=${flyway.url} spring.datasource.username=${flyway.user} spring.datasource.password=${flyway.password} -spring.flyway.locations=${flyway.locations:db/migration} \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/main/resources/db/callbacks/afterMigrateError.sql b/persistence-modules/flyway-repair/src/main/resources/db/callback/afterMigrateError__repair.sql similarity index 100% rename from persistence-modules/flyway-repair/src/main/resources/db/callbacks/afterMigrateError.sql rename to persistence-modules/flyway-repair/src/main/resources/db/callback/afterMigrateError__repair.sql diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table_one.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table.sql similarity index 100% rename from persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table_one.sql rename to persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table.sql diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table_two.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table.sql similarity index 100% rename from persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table_two.sql rename to persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table.sql diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table_three.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table.sql similarity index 100% rename from persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table_three.sql rename to persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table.sql diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql index ec434dd5b2..cf89d5f308 100644 --- a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql +++ b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql @@ -1,3 +1,3 @@ -create table table_one ( +create table table_four ( id numeric primary key ); \ No newline at end of file From c53f498e12cced788e23abe6f0d373563551aa0e Mon Sep 17 00:00:00 2001 From: Adrian Maghear Date: Fri, 17 Jul 2020 15:32:41 +0200 Subject: [PATCH 041/132] [BAEL4288] small fixes --- persistence-modules/flyway-repair/README.MD | 3 +-- persistence-modules/flyway-repair/docker-compose/.env | 2 +- .../flyway-repair/docker-compose/docker-compose.yaml | 2 +- .../src/main/resources/application-callbacks.properties | 2 +- .../flyway-repair/src/main/resources/application-h2.properties | 2 +- .../src/main/resources/application-postgres.properties | 2 +- .../main/resources/db/callback/afterMigrateError__repair.sql | 2 +- .../src/main/resources/db/migration/V1_0__add_table.sql | 2 +- .../src/main/resources/db/migration/V1_1__add_table.sql | 2 +- .../src/main/resources/db/migration/V1_2__add_table.sql | 2 +- .../src/main/resources/db/migration/V1_3__add_table.sql | 2 +- 11 files changed, 11 insertions(+), 12 deletions(-) diff --git a/persistence-modules/flyway-repair/README.MD b/persistence-modules/flyway-repair/README.MD index daeb9012b5..ca029e8299 100644 --- a/persistence-modules/flyway-repair/README.MD +++ b/persistence-modules/flyway-repair/README.MD @@ -1,3 +1,2 @@ ### Relevant Articles: -- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway) -- [A Guide to Flyway Callbacks](http://www.baeldung.com/flyway-callbacks) +- [Flyway Repair With Spring Boot](http://www.baeldung.com/flyway-repair-with-spring-boot) diff --git a/persistence-modules/flyway-repair/docker-compose/.env b/persistence-modules/flyway-repair/docker-compose/.env index 69785c6e5c..8a9d0e7954 100644 --- a/persistence-modules/flyway-repair/docker-compose/.env +++ b/persistence-modules/flyway-repair/docker-compose/.env @@ -1 +1 @@ -POSTGRES_PORT=5431 \ No newline at end of file +POSTGRES_PORT=5431 diff --git a/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml b/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml index b3502f8775..b32b48d1cf 100644 --- a/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml +++ b/persistence-modules/flyway-repair/docker-compose/docker-compose.yaml @@ -12,4 +12,4 @@ services: networks: baeldung: - driver: bridge \ No newline at end of file + driver: bridge diff --git a/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties b/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties index 7fb3124764..46ad86afee 100644 --- a/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties +++ b/persistence-modules/flyway-repair/src/main/resources/application-callbacks.properties @@ -1 +1 @@ -spring.flyway.locations=classpath:db/migration,classpath:db/callback \ No newline at end of file +spring.flyway.locations=classpath:db/migration,classpath:db/callback diff --git a/persistence-modules/flyway-repair/src/main/resources/application-h2.properties b/persistence-modules/flyway-repair/src/main/resources/application-h2.properties index 15bd482adf..64e485244e 100644 --- a/persistence-modules/flyway-repair/src/main/resources/application-h2.properties +++ b/persistence-modules/flyway-repair/src/main/resources/application-h2.properties @@ -1,3 +1,3 @@ flyway.url=jdbc:h2:file:./testdb;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE;MODE=MySQL;DATABASE_TO_UPPER=false; flyway.user=testuser -flyway.password=password \ No newline at end of file +flyway.password=password diff --git a/persistence-modules/flyway-repair/src/main/resources/application-postgres.properties b/persistence-modules/flyway-repair/src/main/resources/application-postgres.properties index 5afaca96b5..951f8f583d 100644 --- a/persistence-modules/flyway-repair/src/main/resources/application-postgres.properties +++ b/persistence-modules/flyway-repair/src/main/resources/application-postgres.properties @@ -1,3 +1,3 @@ flyway.url=jdbc:postgresql://127.0.0.1:5431/testdb flyway.user=testuser -flyway.password=password \ No newline at end of file +flyway.password=password diff --git a/persistence-modules/flyway-repair/src/main/resources/db/callback/afterMigrateError__repair.sql b/persistence-modules/flyway-repair/src/main/resources/db/callback/afterMigrateError__repair.sql index c975e85056..ee0cbb6cee 100644 --- a/persistence-modules/flyway-repair/src/main/resources/db/callback/afterMigrateError__repair.sql +++ b/persistence-modules/flyway-repair/src/main/resources/db/callback/afterMigrateError__repair.sql @@ -1 +1 @@ -DELETE FROM flyway_schema_history WHERE success=false; \ No newline at end of file +DELETE FROM flyway_schema_history WHERE success=false; diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table.sql index ec434dd5b2..1774e837b7 100644 --- a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table.sql +++ b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_0__add_table.sql @@ -1,3 +1,3 @@ create table table_one ( id numeric primary key -); \ No newline at end of file +); diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table.sql index 48720d59d6..76f2ee7ba1 100644 --- a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table.sql +++ b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_1__add_table.sql @@ -1,3 +1,3 @@ create table table_two ( id numeric primary key -); \ No newline at end of file +); diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table.sql index 1917c88b9b..dd5cf34059 100644 --- a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table.sql +++ b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_2__add_table.sql @@ -1,3 +1,3 @@ create table table_three ( id numeric primary key -); \ No newline at end of file +); diff --git a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql index cf89d5f308..4a126ffe33 100644 --- a/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql +++ b/persistence-modules/flyway-repair/src/main/resources/db/migration/V1_3__add_table.sql @@ -1,3 +1,3 @@ create table table_four ( id numeric primary key -); \ No newline at end of file +); From 9cf9cf91a2454a0a3e20df17ae3d222575e80138 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Fri, 17 Jul 2020 17:06:50 +0200 Subject: [PATCH 042/132] BAEL-3275: Convert RedisMessageListenerIntegrationTest to a SpringBootTest (#9717) --- .../data/redis/SpringRedisApplication.java | 13 +++++++ .../RedisMessageListenerIntegrationTest.java | 34 ++++++++----------- 2 files changed, 28 insertions(+), 19 deletions(-) create mode 100644 persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/SpringRedisApplication.java diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/SpringRedisApplication.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/SpringRedisApplication.java new file mode 100644 index 0000000000..82c06f803b --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/SpringRedisApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.data.redis; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringRedisApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringRedisApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java index 6f9e6a8757..6501f3f9f0 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java @@ -1,44 +1,40 @@ package com.baeldung.spring.data.redis; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.UUID; - +import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; import org.junit.AfterClass; import org.junit.BeforeClass; 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.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.spring.data.redis.config.RedisConfig; -import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; -import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; - +import org.springframework.test.context.junit4.SpringRunner; import redis.embedded.RedisServerBuilder; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = RedisConfig.class) +import java.util.UUID; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisApplication.class) @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class RedisMessageListenerIntegrationTest { private static redis.embedded.RedisServer redisServer; - + @Autowired private RedisMessagePublisher redisMessagePublisher; - + @BeforeClass - public static void startRedisServer() throws IOException { + public static void startRedisServer() { redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); redisServer.start(); } - + @AfterClass - public static void stopRedisServer() throws IOException { + public static void stopRedisServer() { redisServer.stop(); } From d752f841ff0dad8e5028d7b3c0d9dd4d61390a5e Mon Sep 17 00:00:00 2001 From: Maiklins Date: Sat, 18 Jul 2020 14:57:09 +0200 Subject: [PATCH 043/132] JAVA-2114 Split or move hibernate JPA module (#9713) Co-authored-by: mikr --- persistence-modules/hibernate-exceptions/README.md | 2 ++ persistence-modules/hibernate-jpa/README.md | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/hibernate-exceptions/README.md b/persistence-modules/hibernate-exceptions/README.md index c2014a3c91..616800a63d 100644 --- a/persistence-modules/hibernate-exceptions/README.md +++ b/persistence-modules/hibernate-exceptions/README.md @@ -1,3 +1,5 @@ ### Relevant Articles: - [Hibernate could not initialize proxy – no Session](https://www.baeldung.com/hibernate-initialize-proxy-exception) +- [Hibernate Error “No Persistence Provider for EntityManager”](https://www.baeldung.com/hibernate-no-persistence-provider) +- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/README.md b/persistence-modules/hibernate-jpa/README.md index 514fcedb8a..64ec9dcae3 100644 --- a/persistence-modules/hibernate-jpa/README.md +++ b/persistence-modules/hibernate-jpa/README.md @@ -11,7 +11,5 @@ This module contains articles specific to use of Hibernate as a JPA implementati - [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) - [Quick Guide to EntityManager#getReference()](https://www.baeldung.com/jpa-entity-manager-get-reference) -- [Hibernate Error “No Persistence Provider for EntityManager”](https://www.baeldung.com/hibernate-no-persistence-provider) From 1ac7e203216efaf31147ae4820f086145836470f Mon Sep 17 00:00:00 2001 From: Nguyen Nam Thai Date: Sat, 18 Jul 2020 21:56:20 +0700 Subject: [PATCH 044/132] BAEL-4113 Measure exception performance --- .../java/com/baeldung/ExceptionBenchmark.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 jmh/src/main/java/com/baeldung/ExceptionBenchmark.java diff --git a/jmh/src/main/java/com/baeldung/ExceptionBenchmark.java b/jmh/src/main/java/com/baeldung/ExceptionBenchmark.java new file mode 100644 index 0000000000..9a166fe2ce --- /dev/null +++ b/jmh/src/main/java/com/baeldung/ExceptionBenchmark.java @@ -0,0 +1,69 @@ +package com.baeldung; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +import java.util.concurrent.TimeUnit; + +@Fork(1) +@Warmup(iterations = 2) +@Measurement(iterations = 10) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +public class ExceptionBenchmark { + private static final int LIMIT = 10_000; + + @Benchmark + public void doNotThrowException(Blackhole blackhole) { + for (int i = 0; i < LIMIT; i++) { + blackhole.consume(new Object()); + } + } + + @Benchmark + public void throwAndCatchException(Blackhole blackhole) { + for (int i = 0; i < LIMIT; i++) { + try { + throw new Exception(); + } catch (Exception e) { + blackhole.consume(e); + } + } + } + + @Benchmark + public void createExceptionWithoutThrowingIt(Blackhole blackhole) { + for (int i = 0; i < LIMIT; i++) { + blackhole.consume(new Exception()); + } + } + + @Benchmark + @Fork(value = 1, jvmArgs = "-XX:-StackTraceInThrowable") + public void throwExceptionWithoutAddingStackTrace(Blackhole blackhole) { + for (int i = 0; i < LIMIT; i++) { + try { + throw new Exception(); + } catch (Exception e) { + blackhole.consume(e); + } + } + } + + @Benchmark + public void throwExceptionAndUnwindStackTrace(Blackhole blackhole) { + for (int i = 0; i < LIMIT; i++) { + try { + throw new Exception(); + } catch (Exception e) { + blackhole.consume(e.getStackTrace()); + } + } + } +} From 2e118afd7433023d59f6b02b30b19e1df2c14ba1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Dupire?= Date: Sun, 19 Jul 2020 14:38:02 +0200 Subject: [PATCH 045/132] [JAVA-1670] Follow-up fixes (#9725) * Removed junit-platform version overriding from spring-boot-client * Removed junit version overriding from spring-boot-with-starter-parent --- spring-boot-modules/spring-boot-client/pom.xml | 1 - .../spring-boot-parent/spring-boot-with-starter-parent/pom.xml | 2 -- 2 files changed, 3 deletions(-) diff --git a/spring-boot-modules/spring-boot-client/pom.xml b/spring-boot-modules/spring-boot-client/pom.xml index a7737be106..aa832497e9 100644 --- a/spring-boot-modules/spring-boot-client/pom.xml +++ b/spring-boot-modules/spring-boot-client/pom.xml @@ -116,7 +116,6 @@ 18.0 - 1.2.0 2.2.4 diff --git a/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml b/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml index 7413492d7f..108e66b68e 100644 --- a/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml +++ b/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml @@ -41,7 +41,5 @@ 1.8 2.2.5.RELEASE - 4.11 - From ca8eee9359d4b5f1a9e16c3ad009aa889a45faaf Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Sun, 19 Jul 2020 18:32:17 +0530 Subject: [PATCH 046/132] JAVA-2160 Add modules in main pom build (#9726) * add modules in main pom build * add modules in main pom build --- pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pom.xml b/pom.xml index f5409d60c4..9d9c448887 100644 --- a/pom.xml +++ b/pom.xml @@ -386,6 +386,7 @@ core-java-modules core-kotlin-modules + core-scala couchbase custom-pmd @@ -559,6 +560,7 @@ atomikos reactive-systems + slack @@ -707,6 +709,7 @@ spring-rest-shell spring-rest-simple spring-resttemplate + spring-resttemplate-2 spring-rest-testing spring-roo @@ -901,6 +904,7 @@ core-java-modules core-kotlin-modules + core-scala couchbase custom-pmd @@ -1071,6 +1075,7 @@ atomikos reactive-systems + slack @@ -1211,6 +1216,7 @@ spring-rest-shell spring-rest-simple spring-resttemplate + spring-resttemplate-2 spring-rest-testing spring-roo From cbdebb76adb9a2efe3280285dac971c41c983eac Mon Sep 17 00:00:00 2001 From: Kamlesh Kumar Date: Sun, 19 Jul 2020 20:13:14 +0530 Subject: [PATCH 047/132] BAEL-4094: Code example for Spring ApplicationContext article (#9656) --- spring-core-4/pom.xml | 16 +++++ .../applicationcontext/AccountConfig.java | 28 ++++++++ .../applicationcontext/AccountRepository.java | 5 ++ .../applicationcontext/AccountService.java | 32 +++++++++ .../MyWebApplicationInitializer.java | 24 +++++++ .../MyXmlWebApplicationInitializer.java | 24 +++++++ .../applicationcontext/UserService.java | 10 +++ .../ApplicationContextUnitTest.java | 71 +++++++++++++++++++ .../account-bean-config.xml | 13 ++++ .../applicationcontext/user-bean-config.xml | 15 ++++ .../test/resources/config/messages.properties | 1 + 11 files changed, 239 insertions(+) create mode 100644 spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountConfig.java create mode 100644 spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountRepository.java create mode 100644 spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/applicationcontext/MyWebApplicationInitializer.java create mode 100644 spring-core-4/src/main/java/com/baeldung/applicationcontext/MyXmlWebApplicationInitializer.java create mode 100644 spring-core-4/src/main/java/com/baeldung/applicationcontext/UserService.java create mode 100644 spring-core-4/src/test/java/com/baeldung/applicationcontext/ApplicationContextUnitTest.java create mode 100644 spring-core-4/src/test/resources/applicationcontext/account-bean-config.xml create mode 100644 spring-core-4/src/test/resources/applicationcontext/user-bean-config.xml create mode 100644 spring-core-4/src/test/resources/config/messages.properties diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml index e5aee1f81d..df0b90fef2 100644 --- a/spring-core-4/pom.xml +++ b/spring-core-4/pom.xml @@ -24,6 +24,16 @@ spring-core ${spring.version} + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + org.springframework spring-expression @@ -69,6 +79,12 @@ ${assertj-core.version} test + + javax.servlet + javax.servlet-api + 4.0.0 + + diff --git a/spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountConfig.java b/spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountConfig.java new file mode 100644 index 0000000000..d4c960bd68 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountConfig.java @@ -0,0 +1,28 @@ +package com.baeldung.applicationcontext; + +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ResourceBundleMessageSource; + +@Configuration +public class AccountConfig { + + @Bean + public AccountService accountService() { + return new AccountService(accountRepository()); + } + + @Bean + public AccountRepository accountRepository() { + return new AccountRepository(); + } + + @Bean + public MessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("config/messages"); + return messageSource; + } + +} diff --git a/spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountRepository.java b/spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountRepository.java new file mode 100644 index 0000000000..f15475acf3 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountRepository.java @@ -0,0 +1,5 @@ +package com.baeldung.applicationcontext; + +public class AccountRepository { + +} diff --git a/spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountService.java b/spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountService.java new file mode 100644 index 0000000000..c8b58915a8 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/applicationcontext/AccountService.java @@ -0,0 +1,32 @@ +package com.baeldung.applicationcontext; + +import java.util.Locale; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; + +public class AccountService { + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private MessageSource messageSource; + + public void setAccountRepository(AccountRepository accountRepository) { + this.accountRepository = accountRepository; + } + + public AccountRepository getAccountRepository() { + return accountRepository; + } + + public AccountService(AccountRepository accountRepository) { + this.accountRepository = accountRepository; + } + + public String getAccountName() { + return messageSource.getMessage("account.name", null, Locale.ENGLISH); + } + +} diff --git a/spring-core-4/src/main/java/com/baeldung/applicationcontext/MyWebApplicationInitializer.java b/spring-core-4/src/main/java/com/baeldung/applicationcontext/MyWebApplicationInitializer.java new file mode 100644 index 0000000000..0296910311 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/applicationcontext/MyWebApplicationInitializer.java @@ -0,0 +1,24 @@ +package com.baeldung.applicationcontext; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class MyWebApplicationInitializer implements WebApplicationInitializer { + + public void onStartup(ServletContext container) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.register(AccountConfig.class); + context.setServletContext(container); + + ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(context)); + servlet.setLoadOnStartup(1); + + servlet.addMapping("/"); + } + +} diff --git a/spring-core-4/src/main/java/com/baeldung/applicationcontext/MyXmlWebApplicationInitializer.java b/spring-core-4/src/main/java/com/baeldung/applicationcontext/MyXmlWebApplicationInitializer.java new file mode 100644 index 0000000000..fe681f1784 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/applicationcontext/MyXmlWebApplicationInitializer.java @@ -0,0 +1,24 @@ +package com.baeldung.applicationcontext; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.XmlWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class MyXmlWebApplicationInitializer implements WebApplicationInitializer { + + public void onStartup(ServletContext container) throws ServletException { + XmlWebApplicationContext context = new XmlWebApplicationContext(); + context.setConfigLocation("/WEB-INF/spring/applicationContext.xml"); + context.setServletContext(container); + + ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(context)); + servlet.setLoadOnStartup(1); + + servlet.addMapping("/"); + } + +} diff --git a/spring-core-4/src/main/java/com/baeldung/applicationcontext/UserService.java b/spring-core-4/src/main/java/com/baeldung/applicationcontext/UserService.java new file mode 100644 index 0000000000..b63d6828a7 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/applicationcontext/UserService.java @@ -0,0 +1,10 @@ +package com.baeldung.applicationcontext; + +import org.springframework.stereotype.Component; + +@Component +public class UserService { + + // user service code + +} diff --git a/spring-core-4/src/test/java/com/baeldung/applicationcontext/ApplicationContextUnitTest.java b/spring-core-4/src/test/java/com/baeldung/applicationcontext/ApplicationContextUnitTest.java new file mode 100644 index 0000000000..491d5dd9d0 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/applicationcontext/ApplicationContextUnitTest.java @@ -0,0 +1,71 @@ +package com.baeldung.applicationcontext; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; + +public class ApplicationContextUnitTest { + + @Test + public void givenAnnotationConfigAppContext_whenSpringConfig_thenMappingSuccess() { + ApplicationContext context = new AnnotationConfigApplicationContext(AccountConfig.class); + AccountService accountService = context.getBean(AccountService.class); + + assertNotNull(accountService); + assertNotNull(accountService.getAccountRepository()); + + ((AnnotationConfigApplicationContext) context).close(); + } + + @Test + public void givenClasspathXmlAppContext_whenAnnotationConfig_thenMappingSuccess() { + ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext/user-bean-config.xml"); + UserService userService = context.getBean(UserService.class); + + assertNotNull(userService); + + ((ClassPathXmlApplicationContext) context).close(); + } + + @Test + @Ignore + public void givenFileXmlAppContext_whenXMLConfig_thenMappingSuccess() { + String path = "D:/workspaces/Baeldung/tutorials/spring-core-4/src/test/resources/applicationcontext/account-bean-config.xml"; + + ApplicationContext context = new FileSystemXmlApplicationContext(path); + AccountService accountService = context.getBean("accountService", AccountService.class); + + assertNotNull(accountService); + assertNotNull(accountService.getAccountRepository()); + + ((FileSystemXmlApplicationContext) context).close(); + } + + @Test + public void givenClasspathXmlAppContext_whenXMLConfig_thenMappingSuccess() { + ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext/account-bean-config.xml"); + AccountService accountService = context.getBean("accountService", AccountService.class); + + assertNotNull(accountService); + assertNotNull(accountService.getAccountRepository()); + + ((ClassPathXmlApplicationContext) context).close(); + } + + @Test + public void givenMessagesInFile_whenMessageResourceUsed_thenReadMessage() { + ApplicationContext context = new AnnotationConfigApplicationContext(AccountConfig.class); + AccountService accountService = context.getBean(AccountService.class); + + assertEquals("TestAccount", accountService.getAccountName()); + + ((AnnotationConfigApplicationContext) context).close(); + } + +} diff --git a/spring-core-4/src/test/resources/applicationcontext/account-bean-config.xml b/spring-core-4/src/test/resources/applicationcontext/account-bean-config.xml new file mode 100644 index 0000000000..eef434928f --- /dev/null +++ b/spring-core-4/src/test/resources/applicationcontext/account-bean-config.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/spring-core-4/src/test/resources/applicationcontext/user-bean-config.xml b/spring-core-4/src/test/resources/applicationcontext/user-bean-config.xml new file mode 100644 index 0000000000..9779d64270 --- /dev/null +++ b/spring-core-4/src/test/resources/applicationcontext/user-bean-config.xml @@ -0,0 +1,15 @@ + + + + + + + diff --git a/spring-core-4/src/test/resources/config/messages.properties b/spring-core-4/src/test/resources/config/messages.properties new file mode 100644 index 0000000000..7d5a4baa73 --- /dev/null +++ b/spring-core-4/src/test/resources/config/messages.properties @@ -0,0 +1 @@ +account.name=TestAccount From 76b1717953685a4dfb72153084b4f5645527a015 Mon Sep 17 00:00:00 2001 From: Nguyen Nam Thai Date: Sun, 19 Jul 2020 22:07:57 +0700 Subject: [PATCH 048/132] BAEL-4113 Relocate the ExceptionBenchmark class --- performance-tests/pom.xml | 13 +++++++++++++ .../exception}/ExceptionBenchmark.java | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) rename {jmh/src/main/java/com/baeldung => performance-tests/src/main/java/com/baeldung/performancetests/exception}/ExceptionBenchmark.java (97%) diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index 0dc38e56a4..c790dbbb16 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -120,6 +120,18 @@ + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + com.baeldung.performancetests.MappingFrameworksPerformance + + + + @@ -178,6 +190,7 @@ 1.21 1.21 3.7.0 + 3.2.0 ]](/core-groovy-2) From 709a18ecfee5b4ea852145afb1e1f0720f48017e Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 21 Jul 2020 21:54:23 +0800 Subject: [PATCH 089/132] Update README.md --- algorithms-miscellaneous-6/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms-miscellaneous-6/README.md b/algorithms-miscellaneous-6/README.md index 22ee51530f..6e435e3741 100644 --- a/algorithms-miscellaneous-6/README.md +++ b/algorithms-miscellaneous-6/README.md @@ -7,4 +7,5 @@ - [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences) - [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms) - [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher) +- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver) - More articles: [[<-- prev]](/../algorithms-miscellaneous-5) From 095291998d859b5a9f9bb1c7e02aca447136c806 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 21 Jul 2020 21:55:39 +0800 Subject: [PATCH 090/132] Update README.md --- spring-thymeleaf-3/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-thymeleaf-3/README.md b/spring-thymeleaf-3/README.md index 66e64e7094..34bd1b4b35 100644 --- a/spring-thymeleaf-3/README.md +++ b/spring-thymeleaf-3/README.md @@ -3,6 +3,8 @@ This module contains articles about Spring with Thymeleaf ## Relevant Articles: + - [Add CSS and JS to Thymeleaf](https://www.baeldung.com/spring-thymeleaf-css-js) - [Formatting Currencies in Spring Using Thymeleaf](https://www.baeldung.com/spring-thymeleaf-currencies) - [Working with Select and Option in Thymeleaf](https://www.baeldung.com/thymeleaf-select-option) +- [Conditional CSS Classes in Thymeleaf](https://www.baeldung.com/spring-mvc-thymeleaf-conditional-css-classes) From a1a10ad0083dd796f13a9bc9c1c1a021af012bbf Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 21 Jul 2020 21:57:20 +0800 Subject: [PATCH 091/132] Update README.md --- linux-bash/text/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/linux-bash/text/README.md b/linux-bash/text/README.md index 20df2a33ec..1c27abc8c6 100644 --- a/linux-bash/text/README.md +++ b/linux-bash/text/README.md @@ -1,4 +1,4 @@ ### Relevant Articles: -- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/tr-manipulate-strings) +- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/remove-text-after-x-in-file) - [Linux Commands for Appending Multiple Lines to a File](https://www.baeldung.com/linux/appending-multiple-lines-to-file2) From 3abe375ad2d000b568a0b81a5c9bd7d2a41b4db4 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 21 Jul 2020 22:15:03 +0800 Subject: [PATCH 092/132] Update README.md --- maven-modules/maven-exec-plugin/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/maven-modules/maven-exec-plugin/README.md b/maven-modules/maven-exec-plugin/README.md index 411639aae1..60035b27c4 100644 --- a/maven-modules/maven-exec-plugin/README.md +++ b/maven-modules/maven-exec-plugin/README.md @@ -3,3 +3,5 @@ This module contains articles about the Maven Exec Plugin. ### Relevant Articles + +- [Run a Java Main Method in Maven](https://www.baeldung.com/maven-java-main-method) From 119c8f323fa11597299284820c52ddf404ba060c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 21 Jul 2020 22:16:18 +0800 Subject: [PATCH 093/132] Create README.md --- core-java-modules/core-java-string-operations-3/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-3/README.md diff --git a/core-java-modules/core-java-string-operations-3/README.md b/core-java-modules/core-java-string-operations-3/README.md new file mode 100644 index 0000000000..4e46849c11 --- /dev/null +++ b/core-java-modules/core-java-string-operations-3/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Version Comparison in Java](https://www.baeldung.com/java-comparing-versions) From 77a82e3cccf12c3bf54be8324a3246d12578665a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 21 Jul 2020 22:19:17 +0800 Subject: [PATCH 094/132] Update README.md --- core-java-modules/core-java-lang-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-3/README.md b/core-java-modules/core-java-lang-3/README.md index f496b74bfb..d735937a02 100644 --- a/core-java-modules/core-java-lang-3/README.md +++ b/core-java-modules/core-java-lang-3/README.md @@ -2,4 +2,5 @@ This module contains articles about core features in the Java language +- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom) - [[<-- Prev]](/core-java-modules/core-java-lang-2) From 5d0249634011ead16bd668e9c698c7d27bc200fe Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 21 Jul 2020 22:21:37 +0800 Subject: [PATCH 095/132] Create README.md --- core-java-modules/core-java-reflection-2/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-reflection-2/README.md diff --git a/core-java-modules/core-java-reflection-2/README.md b/core-java-modules/core-java-reflection-2/README.md new file mode 100644 index 0000000000..342fbd73bd --- /dev/null +++ b/core-java-modules/core-java-reflection-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Reading the Value of ‘private’ Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value) From f79593c2667c45627d99aa12aecb1d87c1e18437 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 21 Jul 2020 22:25:59 +0800 Subject: [PATCH 096/132] Create README.md --- maven-modules/maven-plugins/maven-enforcer/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 maven-modules/maven-plugins/maven-enforcer/README.md diff --git a/maven-modules/maven-plugins/maven-enforcer/README.md b/maven-modules/maven-plugins/maven-enforcer/README.md new file mode 100644 index 0000000000..44d43050e7 --- /dev/null +++ b/maven-modules/maven-plugins/maven-enforcer/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin) From de2ad1bc40cd3546f35d1271a9029a30595e38e9 Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Tue, 21 Jul 2020 19:24:20 +0430 Subject: [PATCH 097/132] How to get the current index in for each Kotlin (#9710) --- .../com/baeldung/index/IndexedIteration.kt | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/index/IndexedIteration.kt diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/index/IndexedIteration.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/index/IndexedIteration.kt new file mode 100644 index 0000000000..07fb595ede --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/index/IndexedIteration.kt @@ -0,0 +1,33 @@ +package com.baeldung.index + +fun main() { + + // Index only + val colors = listOf("Red", "Green", "Blue") + for (i in colors.indices) { + println(colors[i]) + } + + val colorArray = arrayOf("Red", "Green", "Blue") + for (i in colorArray.indices) { + println(colorArray[i]) + } + + (0 until colors.size).forEach { println(colors[it]) } + for (i in 0 until colors.size) { + println(colors[i]) + } + + // Index and Value + colors.forEachIndexed { i, v -> println("The value for index $i is $v") } + for (indexedValue in colors.withIndex()) { + println("The value for index ${indexedValue.index} is ${indexedValue.value}") + } + + for ((i, v) in colors.withIndex()) { + println("The value for index $i is $v") + } + + colors.filterIndexed { i, _ -> i % 2 == 0 } + colors.filterIndexed { _, v -> v == "RED" } +} From f673723619daeb0c4184d7b6a6af991c0e819525 Mon Sep 17 00:00:00 2001 From: Adrian Maghear Date: Tue, 21 Jul 2020 17:08:30 +0200 Subject: [PATCH 098/132] [BAEL-4288] address comments after review --- persistence-modules/flyway-repair/README.MD | 1 - 1 file changed, 1 deletion(-) diff --git a/persistence-modules/flyway-repair/README.MD b/persistence-modules/flyway-repair/README.MD index ca029e8299..7d843af9ea 100644 --- a/persistence-modules/flyway-repair/README.MD +++ b/persistence-modules/flyway-repair/README.MD @@ -1,2 +1 @@ ### Relevant Articles: -- [Flyway Repair With Spring Boot](http://www.baeldung.com/flyway-repair-with-spring-boot) From 38ccd9faaf5ab8129e9890ac46326e253698dd0d Mon Sep 17 00:00:00 2001 From: Maciej Glowka Date: Tue, 21 Jul 2020 20:46:44 +0200 Subject: [PATCH 099/132] BAEL-3347: moved version collision submodule from maven-all to maven-modules --- maven-all/version-collision/pom.xml | 54 ---------------- .../version-collision/child-module/pom.xml | 21 ------ maven-modules/version-collision/pom.xml | 64 +++++++++++-------- .../version-collision/project-a/pom.xml | 0 .../version-collision/project-b/pom.xml | 0 .../project-collision/pom.xml | 0 .../collision/VersionCollisionUnitTest.java | 0 7 files changed, 37 insertions(+), 102 deletions(-) delete mode 100644 maven-all/version-collision/pom.xml delete mode 100644 maven-modules/version-collision/child-module/pom.xml rename {maven-all => maven-modules}/version-collision/project-a/pom.xml (100%) rename {maven-all => maven-modules}/version-collision/project-b/pom.xml (100%) rename {maven-all => maven-modules}/version-collision/project-collision/pom.xml (100%) rename {maven-all => maven-modules}/version-collision/project-collision/src/test/java/com/baeldung/version/collision/VersionCollisionUnitTest.java (100%) diff --git a/maven-all/version-collision/pom.xml b/maven-all/version-collision/pom.xml deleted file mode 100644 index 7bbd17a789..0000000000 --- a/maven-all/version-collision/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - maven-all - com.baeldung - 0.0.1-SNAPSHOT - - 4.0.0 - - version-collision - pom - - project-a - project-b - project-collision - - - - - - - com.google.guava - guava - 29.0-jre - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/maven-modules/version-collision/child-module/pom.xml b/maven-modules/version-collision/child-module/pom.xml deleted file mode 100644 index 7784bc5953..0000000000 --- a/maven-modules/version-collision/child-module/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - version-collision - com.baeldung - 0.0.1-SNAPSHOT - - 4.0.0 - - child-module - - - - org.apache.maven - maven-core - 3.3.9 - - - \ No newline at end of file diff --git a/maven-modules/version-collision/pom.xml b/maven-modules/version-collision/pom.xml index 9a38fd0edb..6d8441aa7b 100644 --- a/maven-modules/version-collision/pom.xml +++ b/maven-modules/version-collision/pom.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - maven-all + maven-modules com.baeldung 0.0.1-SNAPSHOT @@ -11,34 +11,44 @@ version-collision pom - - child-module + project-a + project-b + project-collision - - - org.apache.commons - commons-configuration2 - 2.7 - - - - - - - - - + + + + + com.google.guava + guava + 29.0-jre + + + - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/maven-all/version-collision/project-a/pom.xml b/maven-modules/version-collision/project-a/pom.xml similarity index 100% rename from maven-all/version-collision/project-a/pom.xml rename to maven-modules/version-collision/project-a/pom.xml diff --git a/maven-all/version-collision/project-b/pom.xml b/maven-modules/version-collision/project-b/pom.xml similarity index 100% rename from maven-all/version-collision/project-b/pom.xml rename to maven-modules/version-collision/project-b/pom.xml diff --git a/maven-all/version-collision/project-collision/pom.xml b/maven-modules/version-collision/project-collision/pom.xml similarity index 100% rename from maven-all/version-collision/project-collision/pom.xml rename to maven-modules/version-collision/project-collision/pom.xml diff --git a/maven-all/version-collision/project-collision/src/test/java/com/baeldung/version/collision/VersionCollisionUnitTest.java b/maven-modules/version-collision/project-collision/src/test/java/com/baeldung/version/collision/VersionCollisionUnitTest.java similarity index 100% rename from maven-all/version-collision/project-collision/src/test/java/com/baeldung/version/collision/VersionCollisionUnitTest.java rename to maven-modules/version-collision/project-collision/src/test/java/com/baeldung/version/collision/VersionCollisionUnitTest.java From a1e32f74888daf855f55c2b9ffc9f2362c7e12e6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 22 Jul 2020 14:44:35 +0800 Subject: [PATCH 100/132] Update README.md --- core-java-modules/core-java-arrays-guides/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-arrays-guides/README.md b/core-java-modules/core-java-arrays-guides/README.md index 56c0c716d8..621443e4a9 100644 --- a/core-java-modules/core-java-arrays-guides/README.md +++ b/core-java-modules/core-java-arrays-guides/README.md @@ -5,4 +5,4 @@ This module contains complete guides about arrays in Java ### Relevant Articles: - [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) - [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) -- [What is [Ljava.lang.Object;?]](https://www.baeldung.com/java-tostring-array) +- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array) From feb45774c3da9022f58f1cb09f0522013cbb34bb Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 22 Jul 2020 15:21:43 +0530 Subject: [PATCH 101/132] JAVA-2155: Updated keycloak version to 10.0.2, and changed parent to parent-boot-2 --- .../spring-boot-keycloak/pom.xml | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index 6208fbe305..5049cc3651 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -2,22 +2,20 @@ 4.0.0 - - - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT - ../ - - com.baeldung.keycloak spring-boot-keycloak 0.0.1 - jar - spring-boot-keycloak + jar This is a simple application demonstrating integration between Keycloak and Spring Boot. + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + @@ -78,7 +76,7 @@ - 10.0.1 + 10.0.2 From 6689cbd783b6682b2e88c51e2361a06b9683ca57 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 22 Jul 2020 15:22:26 +0530 Subject: [PATCH 102/132] JAVA-2155: added properties alternative to spring security --- .../src/main/resources/application.properties | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties b/spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties index 6e7da2cb90..9dfd3ea720 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties @@ -6,4 +6,6 @@ keycloak.auth-server-url=http://localhost:8180/auth keycloak.realm=SpringBootKeycloak keycloak.resource=login-app keycloak.public-client=true +#keycloak.security-constraints[0].authRoles[0]=user +#keycloak.security-constraints[0].securityCollections[0].patterns[0]=/customers/* keycloak.principal-attribute=preferred_username \ No newline at end of file From debf5ce3e861f623626456fc1255a63298d3ab9c Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 22 Jul 2020 15:23:01 +0530 Subject: [PATCH 103/132] JAVA-2155: changed package from org.baledung to com.baeldung --- .../src/test/java/{org => com}/baeldung/SpringContextTest.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename spring-boot-modules/spring-boot-keycloak/src/test/java/{org => com}/baeldung/SpringContextTest.java (100%) diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/SpringContextTest.java From 3af64ac7d40149ea7d8071219927c11aef952f91 Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Wed, 22 Jul 2020 19:07:29 +0430 Subject: [PATCH 104/132] KTLN-162: Create anonymous inner class in Kotlin (#9718) * Create anonymous inner class in Kotlin * Moved to the New Module --- .../com/baeldung/anonymous/Anonymous.kt | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/anonymous/Anonymous.kt diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/anonymous/Anonymous.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/anonymous/Anonymous.kt new file mode 100644 index 0000000000..ea471f5d00 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/anonymous/Anonymous.kt @@ -0,0 +1,41 @@ +package com.baeldung.anonymous + +import java.io.Serializable +import java.nio.channels.Channel + +fun main() { + val channel = object : Channel { + override fun isOpen() = false + + override fun close() { + } + } + + val maxEntries = 10 + val lruCache = object : LinkedHashMap(10, 0.75f) { + + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): Boolean { + return size > maxEntries + } + } + + val map = object : LinkedHashMap() { + // omitted + } + + val serializableChannel = object : Channel, Serializable { + override fun isOpen(): Boolean { + TODO("Not yet implemented") + } + + override fun close() { + TODO("Not yet implemented") + } + } + + val obj = object { + val question = "answer" + val answer = 42 + } + println("The ${obj.question} is ${obj.answer}") +} \ No newline at end of file From 11501b461c5e0a752b26768822173b8079020f10 Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Wed, 22 Jul 2020 19:11:08 +0430 Subject: [PATCH 105/132] Moving to a new module (#9681) --- .../emptiness/DirectoryEmptinessUnitTest.java | 63 +++++++++++++++++++ .../src/test/resources/notDir.txt | 0 2 files changed, 63 insertions(+) create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/emptiness/DirectoryEmptinessUnitTest.java create mode 100644 core-java-modules/core-java-io-3/src/test/resources/notDir.txt diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/emptiness/DirectoryEmptinessUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/emptiness/DirectoryEmptinessUnitTest.java new file mode 100644 index 0000000000..a44aea1383 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/emptiness/DirectoryEmptinessUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.emptiness; + +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DirectoryEmptinessUnitTest { + + @Test + public void givenPath_whenInvalid_thenReturnsFalse() throws IOException { + assertThat(isEmpty(Paths.get("invalid-addr"))).isFalse(); + } + + @Test + public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException { + Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath()); + assertThat(isEmpty(aFile)).isFalse(); + } + + @Test + public void givenPath_whenNotEmptyDir_thenReturnsFalse() throws IOException { + Path currentDir = new File("").toPath().toAbsolutePath(); + assertThat(isEmpty(currentDir)).isFalse(); + } + + @Test + public void givenPath_whenIsEmpty_thenReturnsTrue() throws Exception { + Path path = Files.createTempDirectory("baeldung-empty"); + assertThat(isEmpty(path)).isTrue(); + } + + private static boolean isEmpty(Path path) throws IOException { + if (Files.isDirectory(path)) { + try (DirectoryStream directory = Files.newDirectoryStream(path)) { + return !directory.iterator().hasNext(); + } + } + + return false; + } + + private static boolean isEmpty2(Path path) throws IOException { + if (Files.isDirectory(path)) { + try (Stream entries = Files.list(path)) { + return !entries.findFirst().isPresent(); + } + } + + return false; + } + + private static boolean isEmptyInefficient(Path path) { + return path.toFile().listFiles().length == 0; + } +} diff --git a/core-java-modules/core-java-io-3/src/test/resources/notDir.txt b/core-java-modules/core-java-io-3/src/test/resources/notDir.txt new file mode 100644 index 0000000000..e69de29bb2 From 0df52dda7ca2109906fcbc49390be76275e825c0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:03:11 +0800 Subject: [PATCH 106/132] Update README.md --- core-java-modules/core-java-exceptions-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-exceptions-2/README.md b/core-java-modules/core-java-exceptions-2/README.md index 7c5db06a55..e6441c2c12 100644 --- a/core-java-modules/core-java-exceptions-2/README.md +++ b/core-java-modules/core-java-exceptions-2/README.md @@ -13,3 +13,4 @@ This module contains articles about core java exceptions - [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler) - [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) - [Java IOException “Too many open files”](https://www.baeldung.com/java-too-many-open-files) +- [When Does Java Throw the ExceptionInInitializerError?](https://www.baeldung.com/java-exceptionininitializererror) From 2bc4c93e7b29c96eb91d8d66a0026949a3509fff Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:06:51 +0800 Subject: [PATCH 107/132] Update README.md --- testing-modules/selenium-junit-testng/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/selenium-junit-testng/README.md b/testing-modules/selenium-junit-testng/README.md index 8baddd3449..aa3f0e8005 100644 --- a/testing-modules/selenium-junit-testng/README.md +++ b/testing-modules/selenium-junit-testng/README.md @@ -4,3 +4,4 @@ - [Testing with Selenium/WebDriver and the Page Object Pattern](http://www.baeldung.com/selenium-webdriver-page-object) - [Using Cookies With Selenium WebDriver in Java](https://www.baeldung.com/java-selenium-webdriver-cookies) - [Clicking Elements in Selenium using JavaScript](https://www.baeldung.com/java-selenium-javascript) +- [Taking Screenshots With Selenium WebDriver](https://www.baeldung.com/java-selenium-screenshots) From 9bee8e34ec397aa6bdff9366c9ac9a44d01e2943 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:09:08 +0800 Subject: [PATCH 108/132] Update README.md --- java-numbers-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-numbers-3/README.md b/java-numbers-3/README.md index 9c323a6c6a..ab0bbd995d 100644 --- a/java-numbers-3/README.md +++ b/java-numbers-3/README.md @@ -13,4 +13,5 @@ This module contains articles about numbers in Java. - [Guide to the Number Class in Java](https://www.baeldung.com/java-number-class) - [Print an Integer in Binary Format in Java](https://www.baeldung.com/java-print-integer-binary) - [Number Formatting in Java](https://www.baeldung.com/java-number-formatting) +- [Division by Zero in Java: Exception, Infinity, or Not a Number](https://www.baeldung.com/java-division-by-zero) - More articles: [[<-- prev]](/java-numbers-2) From 5be7937077fb270bb812cafa1edfb734c0799197 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:12:46 +0800 Subject: [PATCH 109/132] Update README.md --- image-processing/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/image-processing/README.md b/image-processing/README.md index 50129bb994..afe92466c1 100644 --- a/image-processing/README.md +++ b/image-processing/README.md @@ -6,3 +6,4 @@ This module contains articles about image processing. - [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) +- [How Can I Resize an Image Using Java?](https://www.baeldung.com/java-resize-image) From 8d04aa3205dc308dd58e745c55057054d3be3438 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:18:07 +0800 Subject: [PATCH 110/132] Create README.md --- maven-modules/version-collision/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 maven-modules/version-collision/README.md diff --git a/maven-modules/version-collision/README.md b/maven-modules/version-collision/README.md new file mode 100644 index 0000000000..a71cfdb0b4 --- /dev/null +++ b/maven-modules/version-collision/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Resolve a Version Collision of Artifacts in Maven](https://www.baeldung.com/maven-version-collision) From 38af7ca655a60b80aaaea15facefc2ddc2490ec9 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:21:28 +0800 Subject: [PATCH 111/132] Update README.md --- core-java-modules/core-java-lang-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-3/README.md b/core-java-modules/core-java-lang-3/README.md index d735937a02..9ce49da868 100644 --- a/core-java-modules/core-java-lang-3/README.md +++ b/core-java-modules/core-java-lang-3/README.md @@ -3,4 +3,5 @@ This module contains articles about core features in the Java language - [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom) +- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean) - [[<-- Prev]](/core-java-modules/core-java-lang-2) From 0423acd0d2a231bb6bc6f1f7522c3906f6e46816 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:24:48 +0800 Subject: [PATCH 112/132] Update README.md --- core-java-modules/core-java-concurrency-basic-2/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-java-modules/core-java-concurrency-basic-2/README.md b/core-java-modules/core-java-concurrency-basic-2/README.md index c7143baf36..a8daf14ea9 100644 --- a/core-java-modules/core-java-concurrency-basic-2/README.md +++ b/core-java-modules/core-java-concurrency-basic-2/README.md @@ -3,10 +3,12 @@ This module contains articles about basic Java concurrency ### Relevant Articles: + - [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) - [wait and notify() Methods in Java](https://www.baeldung.com/java-wait-notify) - [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep) - [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized) - [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle) - [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference) +- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe) - [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) From 5b354924745fdbf2a011f6f3791cff27dc27e9a6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:28:59 +0800 Subject: [PATCH 113/132] Update README.md --- image-processing/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/image-processing/README.md b/image-processing/README.md index afe92466c1..eba23f83eb 100644 --- a/image-processing/README.md +++ b/image-processing/README.md @@ -7,3 +7,4 @@ This module contains articles about image processing. - [Intro to OpenCV with Java](https://www.baeldung.com/java-opencv) - [Optical Character Recognition with Tesseract](https://www.baeldung.com/java-ocr-tesseract) - [How Can I Resize an Image Using Java?](https://www.baeldung.com/java-resize-image) +- [Adding Text to an Image in Java](https://www.baeldung.com/java-add-text-to-image) From 60ca1bc31b28c5a33c8e7d2eb7d541bf4340dda1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:31:26 +0800 Subject: [PATCH 114/132] Update README.md --- spring-boot-modules/spring-boot-properties-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-properties-2/README.md b/spring-boot-modules/spring-boot-properties-2/README.md index 4e03a4125c..c81ad50e40 100644 --- a/spring-boot-modules/spring-boot-properties-2/README.md +++ b/spring-boot-modules/spring-boot-properties-2/README.md @@ -10,4 +10,5 @@ This module contains articles about Properties in Spring Boot. - [@PropertySource with YAML Files in Spring Boot](https://www.baeldung.com/spring-yaml-propertysource) - [Inject Arrays and Lists From Spring Properties Files](https://www.baeldung.com/spring-inject-arrays-lists) - [Inject a Map from a YAML File with Spring](https://www.baeldung.com/spring-yaml-inject-map) +- [YAML to List of Objects in Spring Boot](https://www.baeldung.com/spring-boot-yaml-list) - More articles: [[<-- prev]](../spring-boot-properties) From 88b1d2661a29a448abadf27c60b8ffc25d0a1e07 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:33:56 +0800 Subject: [PATCH 115/132] Update README.md --- persistence-modules/core-java-persistence/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/core-java-persistence/README.md b/persistence-modules/core-java-persistence/README.md index f5d3f12d7a..88442a94c8 100644 --- a/persistence-modules/core-java-persistence/README.md +++ b/persistence-modules/core-java-persistence/README.md @@ -10,3 +10,4 @@ - [Guide to the JDBC ResultSet Interface](https://www.baeldung.com/jdbc-resultset) - [Types of SQL Joins](https://www.baeldung.com/sql-joins) - [Returning the Generated Keys in JDBC](https://www.baeldung.com/jdbc-returning-generated-keys) +- [Loading JDBC Drivers](https://www.baeldung.com/java-jdbc-loading-drivers) From 09441449d7997956a22feadff459b761c96f495e Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:36:52 +0800 Subject: [PATCH 116/132] Update README.md --- apache-shiro/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-shiro/README.md b/apache-shiro/README.md index ed63c569da..3a0088072f 100644 --- a/apache-shiro/README.md +++ b/apache-shiro/README.md @@ -6,4 +6,4 @@ This module contains articles about Apache Shiro - [Introduction to Apache Shiro](https://www.baeldung.com/apache-shiro) - [Permissions-Based Access Control with Apache Shiro](https://www.baeldung.com/apache-shiro-access-control) - +- [Spring Security vs Apache Shiro](https://www.baeldung.com/spring-security-vs-apache-shiro) From bf922cb955eedc299360667fef4d2e23ce018bd6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:39:16 +0800 Subject: [PATCH 117/132] Update README.md --- core-java-modules/core-java-collections-3/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-java-modules/core-java-collections-3/README.md b/core-java-modules/core-java-collections-3/README.md index fb983d9abc..4349ef6be3 100644 --- a/core-java-modules/core-java-collections-3/README.md +++ b/core-java-modules/core-java-collections-3/README.md @@ -3,6 +3,7 @@ ## Core Java Collections Cookbooks and Examples ### Relevant Articles: + - [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint) - [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector) - [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences) @@ -10,3 +11,4 @@ - [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance) - [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) - [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack) +- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list) From 19a50da589b381ed9311c4d2980fe94b77967367 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:48:24 +0800 Subject: [PATCH 118/132] Update README.md --- core-java-modules/core-java-jvm-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-jvm-2/README.md b/core-java-modules/core-java-jvm-2/README.md index 7a189ceec5..7206a9eef7 100644 --- a/core-java-modules/core-java-jvm-2/README.md +++ b/core-java-modules/core-java-jvm-2/README.md @@ -9,4 +9,5 @@ This module contains articles about working with the Java Virtual Machine (JVM). - [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks) - [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout) - [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length) +- [Memory Address of Objects in Java](https://www.baeldung.com/java-object-memory-address) - More articles: [[<-- prev]](/core-java-modules/core-java-jvm) From 95c6b906211f862c762810eb72ee4719373ddf42 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 21:57:49 +0800 Subject: [PATCH 119/132] Update README.md --- algorithms-miscellaneous-6/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms-miscellaneous-6/README.md b/algorithms-miscellaneous-6/README.md index 6e435e3741..6ddae75f43 100644 --- a/algorithms-miscellaneous-6/README.md +++ b/algorithms-miscellaneous-6/README.md @@ -8,4 +8,5 @@ - [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms) - [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher) - [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver) +- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements) - More articles: [[<-- prev]](/../algorithms-miscellaneous-5) From af79698c0bc19d157d7d0c69f4f35182e0554af3 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 22:02:12 +0800 Subject: [PATCH 120/132] Update README.md --- patterns/solid/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/patterns/solid/README.md b/patterns/solid/README.md index f5146732a0..41e986f544 100644 --- a/patterns/solid/README.md +++ b/patterns/solid/README.md @@ -3,3 +3,4 @@ - [A Solid Guide to Solid Principles](https://www.baeldung.com/solid-principles) - [Single Responsibility Principle in Java](https://www.baeldung.com/java-single-responsibility-principle) - [Open/Closed Principle in Java](https://www.baeldung.com/java-open-closed-principle) +- [Interface Segregation Principle in Java](https://www.baeldung.com/java-interface-segregation) From 66ac0239bd165bfdacd7da1ff7d3b0264701e393 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 22:04:14 +0800 Subject: [PATCH 121/132] Update README.md --- persistence-modules/core-java-persistence/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/persistence-modules/core-java-persistence/README.md b/persistence-modules/core-java-persistence/README.md index 88442a94c8..a760489480 100644 --- a/persistence-modules/core-java-persistence/README.md +++ b/persistence-modules/core-java-persistence/README.md @@ -3,6 +3,7 @@ ## Core Java Persistence Examples ### Relevant Articles: + - [Introduction to JDBC](http://www.baeldung.com/java-jdbc) - [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing) - [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset) @@ -11,3 +12,4 @@ - [Types of SQL Joins](https://www.baeldung.com/sql-joins) - [Returning the Generated Keys in JDBC](https://www.baeldung.com/jdbc-returning-generated-keys) - [Loading JDBC Drivers](https://www.baeldung.com/java-jdbc-loading-drivers) +- [Difference Between Statement and PreparedStatement](https://www.baeldung.com/java-statement-preparedstatement) From daae6b63eecca1b7929fcf5ebd7f295bc36245fc Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 22:06:39 +0800 Subject: [PATCH 122/132] Update README.md --- spring-core-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-4/README.md b/spring-core-4/README.md index 706c330f39..83b5c4933d 100644 --- a/spring-core-4/README.md +++ b/spring-core-4/README.md @@ -11,4 +11,5 @@ This module contains articles about core Spring functionality - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) - [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok) +- [The Spring ApplicationContext](https://www.baeldung.com/spring-application-context) - More articles: [[<-- prev]](/spring-core-3) From 6427ac176edd94377058d01d97283917e3f88289 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 22:10:10 +0800 Subject: [PATCH 123/132] Update README.md --- jmh/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmh/README.md b/jmh/README.md index 3a5370c9f2..41bf16d6bb 100644 --- a/jmh/README.md +++ b/jmh/README.md @@ -5,4 +5,4 @@ This module contains articles about the Java Microbenchmark Harness (JMH). ### Relevant articles: - [Microbenchmarking with Java](https://www.baeldung.com/java-microbenchmark-harness) - +- [A Guide to False Sharing and @Contended](https://www.baeldung.com/java-false-sharing-contended) From cb9e7920a0651cd7c0dc3f5a6e0f92b4ce0fb17a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 22:11:49 +0800 Subject: [PATCH 124/132] Update README.md --- testing-modules/testing-libraries/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/testing-libraries/README.md b/testing-modules/testing-libraries/README.md index b1e1575e63..4db7fb8e7a 100644 --- a/testing-modules/testing-libraries/README.md +++ b/testing-modules/testing-libraries/README.md @@ -10,3 +10,4 @@ - [Cucumber Data Tables](https://www.baeldung.com/cucumber-data-tables) - [Cucumber Background](https://www.baeldung.com/java-cucumber-background) - [Cucumber Hooks](https://www.baeldung.com/java-cucumber-hooks) +- [Unit Testing of System.out.println() with JUnit](https://www.baeldung.com/java-testing-system-out-println) From 77f89e8b5b9f49bc4e9acbd4cbf8a6306d123aa8 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 22:17:28 +0800 Subject: [PATCH 125/132] Update README.md --- maven-modules/maven-properties/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maven-modules/maven-properties/README.md b/maven-modules/maven-properties/README.md index 65d976189c..52ac8506b3 100644 --- a/maven-modules/maven-properties/README.md +++ b/maven-modules/maven-properties/README.md @@ -5,4 +5,4 @@ have their own dedicated modules. ### Relevant Articles -- [Accessing Maven Properties in Java] \ No newline at end of file +- [Accessing Maven Properties in Java](https://www.baeldung.com/java-accessing-maven-properties) From 43d6584d8bb50d6937fdf9e0cb27fca9bab963a6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 22:19:29 +0800 Subject: [PATCH 126/132] Update README.md --- core-java-modules/core-java-io-3/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-java-modules/core-java-io-3/README.md b/core-java-modules/core-java-io-3/README.md index 39752346d3..61a040c1ce 100644 --- a/core-java-modules/core-java-io-3/README.md +++ b/core-java-modules/core-java-io-3/README.md @@ -3,5 +3,7 @@ This module contains articles about core Java input and output (IO) ### Relevant Articles: + - [Java – Create a File](https://www.baeldung.com/java-how-to-create-a-file) +- [Check If a Directory Is Empty in Java](https://www.baeldung.com/java-check-empty-directory) - [[<-- Prev]](/core-java-modules/core-java-io-2) From 9af44b328372b1d33474feaa2a46dc6092500f19 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 22:41:33 +0800 Subject: [PATCH 127/132] Update README.md --- core-kotlin-modules/core-kotlin-collections/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-kotlin-modules/core-kotlin-collections/README.md b/core-kotlin-modules/core-kotlin-collections/README.md index dcf2743577..2ebb748cba 100644 --- a/core-kotlin-modules/core-kotlin-collections/README.md +++ b/core-kotlin-modules/core-kotlin-collections/README.md @@ -3,6 +3,7 @@ This module contains articles about core Kotlin collections. ### Relevant articles: + - [Split a List Into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) - [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list) - [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api) @@ -12,3 +13,4 @@ This module contains articles about core Kotlin collections. - [Difference between fold and reduce in Kotlin](https://www.baeldung.com/kotlin/fold-vs-reduce) - [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort) - [Working With Lists in Kotlin](https://www.baeldung.com/kotlin/lists) +- [Iterating Collections by Index in Kotlin](https://www.baeldung.com/kotlin/iterating-collections-by-index) From 04d72f9b0bbc064f69cf95a065c5c442d4578a94 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 23 Jul 2020 22:42:52 +0800 Subject: [PATCH 128/132] Update README.md --- core-kotlin-modules/core-kotlin-lang-oop-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/README.md b/core-kotlin-modules/core-kotlin-lang-oop-2/README.md index 27536273dc..a62a25c01d 100644 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/README.md +++ b/core-kotlin-modules/core-kotlin-lang-oop-2/README.md @@ -7,4 +7,5 @@ This module contains articles about Object-Oriented Programming in Kotlin - [Generics in Kotlin](https://www.baeldung.com/kotlin-generics) - [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties) - [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern) +- [Anonymous Inner Classes in Kotlin](https://www.baeldung.com/kotlin/anonymous-inner-classes) - [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang-oop) From 9057d216f25eeee3dccf7c839ba212bd480136f0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 24 Jul 2020 13:24:43 +0800 Subject: [PATCH 129/132] Update README.md --- core-java-modules/core-java-security-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-security-2/README.md b/core-java-modules/core-java-security-2/README.md index 24a821bd4d..ba8cce46a0 100644 --- a/core-java-modules/core-java-security-2/README.md +++ b/core-java-modules/core-java-security-2/README.md @@ -9,4 +9,5 @@ This module contains articles about core Java Security - [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) - [Checksums in Java](https://www.baeldung.com/java-checksums) +- [How to Read PEM File to Get Public and Private Keys](https://www.baeldung.com/java-read-pem-file-keys) - More articles: [[<-- prev]](/core-java-modules/core-java-security) From b1a9ee6282ff3f4661b415325880568d293d67c0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 24 Jul 2020 13:26:05 +0800 Subject: [PATCH 130/132] Update README.md --- libraries-security/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-security/README.md b/libraries-security/README.md index 580ebdeab0..5ec85a15e9 100644 --- a/libraries-security/README.md +++ b/libraries-security/README.md @@ -10,3 +10,4 @@ This module contains articles about security libraries. - [Introduction to BouncyCastle with Java](https://www.baeldung.com/java-bouncy-castle) - [Intro to Jasypt](https://www.baeldung.com/jasypt) - [Digital Signatures in Java](https://www.baeldung.com/java-digital-signature) +- [How to Read PEM File to Get Public and Private Keys](https://www.baeldung.com/java-read-pem-file-keys) From 41c8fa83ef69a11fa8d5ba63d03e1cd6e0a6e825 Mon Sep 17 00:00:00 2001 From: rdevarakonda Date: Sat, 25 Jul 2020 10:43:52 +0100 Subject: [PATCH 131/132] BAEL-4006 | Liskov Substitution Principle in Java (#9431) * BAEL-4006 | Liskov Substitution Principle in Java * BAEL-4006 | UNDO unintentional commit to pom.xml * BAEL-4006 | Code review feedback implementation * BAEL-4006 | Changes made to support the article review feedback implementation * BAEL-4006 | Minor change to a comment --- .../java/com/baeldung/l/advanced/Account.java | 17 +++++++++++ .../advanced/BankingAppWithdrawalService.java | 15 ++++++++++ .../java/com/baeldung/l/advanced/Bar.java | 27 ++++++++++++++++++ .../java/com/baeldung/l/advanced/Car.java | 26 +++++++++++++++++ .../baeldung/l/advanced/CurrentAccount.java | 15 ++++++++++ .../com/baeldung/l/advanced/ElectricCar.java | 23 +++++++++++++++ .../baeldung/l/advanced/FilePurgingJob.java | 18 ++++++++++++ .../com/baeldung/l/advanced/FileSystem.java | 10 +++++++ .../l/advanced/FixedTermDepositAccount.java | 15 ++++++++++ .../java/com/baeldung/l/advanced/Foo.java | 22 +++++++++++++++ .../com/baeldung/l/advanced/HybridCar.java | 28 +++++++++++++++++++ .../com/baeldung/l/advanced/MotorCar.java | 25 +++++++++++++++++ .../l/advanced/ReadOnlyFileSystem.java | 16 +++++++++++ .../baeldung/l/advanced/SavingsAccount.java | 15 ++++++++++ .../java/com/baeldung/l/advanced/ToyCar.java | 24 ++++++++++++++++ .../l/advanced/refactored/Account.java | 7 +++++ .../BankingAppWithdrawalService.java | 17 +++++++++++ .../l/advanced/refactored/CurrentAccount.java | 13 +++++++++ .../refactored/FixedTermDepositAccount.java | 9 ++++++ .../l/advanced/refactored/SavingsAccount.java | 13 +++++++++ .../refactored/WithdrawableAccount.java | 14 ++++++++++ 21 files changed, 369 insertions(+) create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/Account.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/BankingAppWithdrawalService.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/Bar.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/Car.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/CurrentAccount.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/ElectricCar.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/FilePurgingJob.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/FileSystem.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/FixedTermDepositAccount.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/Foo.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/HybridCar.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/MotorCar.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/ReadOnlyFileSystem.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/SavingsAccount.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/ToyCar.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/Account.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/BankingAppWithdrawalService.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/CurrentAccount.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/FixedTermDepositAccount.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/SavingsAccount.java create mode 100644 patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/WithdrawableAccount.java diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/Account.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/Account.java new file mode 100644 index 0000000000..3a8260924b --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/Account.java @@ -0,0 +1,17 @@ +package com.baeldung.l.advanced; + +import java.math.BigDecimal; + +public abstract class Account { + protected abstract void deposit(BigDecimal amount); + + /** + * Reduces the account balance by the specified amount + * provided given amount > 0 and account meets minimum available + * balance criteria. + * + * @param amount + */ + protected abstract void withdraw(BigDecimal amount); + +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/BankingAppWithdrawalService.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/BankingAppWithdrawalService.java new file mode 100644 index 0000000000..6689b1dc8c --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/BankingAppWithdrawalService.java @@ -0,0 +1,15 @@ +package com.baeldung.l.advanced; + +import java.math.BigDecimal; + +public class BankingAppWithdrawalService { + private Account account; + + public BankingAppWithdrawalService(Account account) { + this.account = account; + } + + public void withdraw(BigDecimal amount) { + account.withdraw(amount); + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/Bar.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/Bar.java new file mode 100644 index 0000000000..8f421cebaa --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/Bar.java @@ -0,0 +1,27 @@ +package com.baeldung.l.advanced; + +public class Bar extends Foo { + + @Override + // precondition: 0 < num <= 10 + public void doStuff(int num) { + if (num <= 0 || num > 10) { + throw new IllegalArgumentException("Input out of range 1-10"); + } + // some logic here... + } + + @Override + // precondition: 0 < num <= 3 + public void doOtherStuff(int num) { + if (num <= 0 || num > 3) { + throw new IllegalArgumentException("Input out of range 1-3"); + } + // some logic here... + } + + @Override + public Integer generateNumber() { + return new Integer(10); + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/Car.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/Car.java new file mode 100644 index 0000000000..48688d9a45 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/Car.java @@ -0,0 +1,26 @@ +package com.baeldung.l.advanced; + +public abstract class Car { + protected int limit; + + // invariant: speed < limit; + protected int speed; + + // Allowed to be set once at the time of creation. + // Value can only increment thereafter. + // Value cannot be reset. + protected int mileage; + + public Car(int mileage) { + this.mileage = mileage; + } + + protected abstract void turnOnEngine(); + + // postcondition: speed < limit + protected abstract void accelerate(); + + // postcondition: speed must reduce + protected abstract void brake(); + +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/CurrentAccount.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/CurrentAccount.java new file mode 100644 index 0000000000..7187582126 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/CurrentAccount.java @@ -0,0 +1,15 @@ +package com.baeldung.l.advanced; + +import java.math.BigDecimal; + +public class CurrentAccount extends Account { + @Override + protected void deposit(BigDecimal amount) { + // Deposit into CurrentAccount + } + + @Override + protected void withdraw(BigDecimal amount) { + // Withdraw from CurrentAccount + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/ElectricCar.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/ElectricCar.java new file mode 100644 index 0000000000..ca78af633f --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/ElectricCar.java @@ -0,0 +1,23 @@ +package com.baeldung.l.advanced; + +public class ElectricCar extends Car { + + public ElectricCar(int mileage) { + super(mileage); + } + + @Override + protected void turnOnEngine() { + throw new AssertionError("I am an Electric Car. I don't have an engine!"); + } + + @Override + protected void accelerate() { + // this acceleration is crazy! + } + + @Override + protected void brake() { + // Apply ElectricCar brake + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/FilePurgingJob.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/FilePurgingJob.java new file mode 100644 index 0000000000..57334696b0 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/FilePurgingJob.java @@ -0,0 +1,18 @@ +package com.baeldung.l.advanced; + +import java.io.IOException; + +public class FilePurgingJob { + private FileSystem fileSystem; + + public FilePurgingJob(FileSystem fileSystem) { + this.fileSystem = fileSystem; + } + + public void purgeOldestFile(String path) throws IOException { + if (!(fileSystem instanceof ReadOnlyFileSystem)) { + // code to detect oldest file + fileSystem.deleteFile(path); + } + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/FileSystem.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/FileSystem.java new file mode 100644 index 0000000000..00a8fb8ec7 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/FileSystem.java @@ -0,0 +1,10 @@ +package com.baeldung.l.advanced; + +import java.io.File; +import java.io.IOException; + +public interface FileSystem { + File[] listFiles(String path); + + void deleteFile(String path) throws IOException; +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/FixedTermDepositAccount.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/FixedTermDepositAccount.java new file mode 100644 index 0000000000..50dd4f3d17 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/FixedTermDepositAccount.java @@ -0,0 +1,15 @@ +package com.baeldung.l.advanced; + +import java.math.BigDecimal; + +public class FixedTermDepositAccount extends Account { + @Override + protected void deposit(BigDecimal amount) { + // Deposit into this account + } + + @Override + protected void withdraw(BigDecimal amount) { + throw new UnsupportedOperationException("Withdrawals are not supported by FixedTermDepositAccount!!"); + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/Foo.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/Foo.java new file mode 100644 index 0000000000..f61577c18f --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/Foo.java @@ -0,0 +1,22 @@ +package com.baeldung.l.advanced; + +public abstract class Foo { + + // precondition: 0 < num <=5 + public void doStuff(int num) { + if (num <= 0 || num > 5) { + throw new IllegalArgumentException("Input out of range 1-5"); + } + // some logic here... + } + + // precondition: 0 < num <=5 + public void doOtherStuff(int num) { + if (num <= 0 || num > 5) { + throw new IllegalArgumentException("Input out of range 1-5"); + } + // some logic here... + } + + public abstract Number generateNumber(); +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/HybridCar.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/HybridCar.java new file mode 100644 index 0000000000..ea643a7419 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/HybridCar.java @@ -0,0 +1,28 @@ +package com.baeldung.l.advanced; + +public class HybridCar extends Car { + // invariant: charge >= 0; + private int charge; + + public HybridCar(int mileage) { + super(mileage); + } + + @Override + protected void turnOnEngine() { + // Start HybridCar + } + + @Override + // postcondition: speed < limit + protected void accelerate() { + // Accelerate HybridCar speed < limit + } + + @Override + // postcondition: speed must reduce + // postcondition: charge must increase + protected void brake() { + // Apply HybridCar brake + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/MotorCar.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/MotorCar.java new file mode 100644 index 0000000000..68a54966cc --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/MotorCar.java @@ -0,0 +1,25 @@ +package com.baeldung.l.advanced; + +public class MotorCar extends Car { + + public MotorCar(int mileage) { + super(mileage); + } + + @Override + protected void turnOnEngine() { + // Start MotorCar + } + + @Override + // postcondition: speed < limit + protected void accelerate() { + // Accelerate MotorCar + } + + @Override + // postcondition: speed must reduce + protected void brake() { + // Apply MotorCar brake + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/ReadOnlyFileSystem.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/ReadOnlyFileSystem.java new file mode 100644 index 0000000000..6ba3d9770d --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/ReadOnlyFileSystem.java @@ -0,0 +1,16 @@ +package com.baeldung.l.advanced; + +import java.io.File; +import java.io.IOException; + +public class ReadOnlyFileSystem implements FileSystem { + public File[] listFiles(String path) { + // code to list files + return new File[0]; + } + + public void deleteFile(String path) throws IOException { + // Do nothing. + // deleteFile operation is not supported on a read-only file system + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/SavingsAccount.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/SavingsAccount.java new file mode 100644 index 0000000000..8dbb5eb4d4 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/SavingsAccount.java @@ -0,0 +1,15 @@ +package com.baeldung.l.advanced; + +import java.math.BigDecimal; + +public class SavingsAccount extends Account { + @Override + protected void deposit(BigDecimal amount) { + // Deposit into SavingsAccount + } + + @Override + protected void withdraw(BigDecimal amount) { + // Withdraw from SavingsAccount + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/ToyCar.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/ToyCar.java new file mode 100644 index 0000000000..a41694deef --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/ToyCar.java @@ -0,0 +1,24 @@ +package com.baeldung.l.advanced; + +public class ToyCar extends Car { + + public ToyCar(int mileage) { + super(mileage); + } + + protected void turnOnEngine() { + + } + + protected void accelerate() { + + } + + protected void brake() { + + } + + public void reset() { + mileage = 0; + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/Account.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/Account.java new file mode 100644 index 0000000000..cb950df164 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/Account.java @@ -0,0 +1,7 @@ +package com.baeldung.l.advanced.refactored; + +import java.math.BigDecimal; + +public abstract class Account { + protected abstract void deposit(BigDecimal amount); +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/BankingAppWithdrawalService.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/BankingAppWithdrawalService.java new file mode 100644 index 0000000000..cbb375dd52 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/BankingAppWithdrawalService.java @@ -0,0 +1,17 @@ +package com.baeldung.l.advanced.refactored; + +import com.baeldung.l.advanced.Account; + +import java.math.BigDecimal; + +public class BankingAppWithdrawalService { + private WithdrawableAccount withdrawableAccount; + + public BankingAppWithdrawalService(WithdrawableAccount withdrawableAccount) { + this.withdrawableAccount = withdrawableAccount; + } + + public void withdraw(BigDecimal amount) { + withdrawableAccount.withdraw(amount); + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/CurrentAccount.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/CurrentAccount.java new file mode 100644 index 0000000000..5b5b9efe04 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/CurrentAccount.java @@ -0,0 +1,13 @@ +package com.baeldung.l.advanced.refactored; + +import java.math.BigDecimal; + +public class CurrentAccount extends WithdrawableAccount { + protected void deposit(BigDecimal amount) { + // Deposit into CurrentAccount + } + + protected void withdraw(BigDecimal amount) { + // Withdraw from CurrentAccount + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/FixedTermDepositAccount.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/FixedTermDepositAccount.java new file mode 100644 index 0000000000..14461b85a3 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/FixedTermDepositAccount.java @@ -0,0 +1,9 @@ +package com.baeldung.l.advanced.refactored; + +import java.math.BigDecimal; + +public class FixedTermDepositAccount extends Account { + protected void deposit(BigDecimal amount) { + // Deposit into this account + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/SavingsAccount.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/SavingsAccount.java new file mode 100644 index 0000000000..45c50079bf --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/SavingsAccount.java @@ -0,0 +1,13 @@ +package com.baeldung.l.advanced.refactored; + +import java.math.BigDecimal; + +public class SavingsAccount extends WithdrawableAccount { + protected void deposit(BigDecimal amount) { + // Deposit into SavingsAccount + } + + protected void withdraw(BigDecimal amount) { + // Withdraw from SavingsAccount + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/WithdrawableAccount.java b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/WithdrawableAccount.java new file mode 100644 index 0000000000..b3c7606cb7 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/l/advanced/refactored/WithdrawableAccount.java @@ -0,0 +1,14 @@ +package com.baeldung.l.advanced.refactored; + +import java.math.BigDecimal; + +public abstract class WithdrawableAccount extends Account { + /** + * Reduces the account balance by the specified amount + * provided given amount > 0 and account meets minimum available + * balance criteria. + * + * @param amount + */ + protected abstract void withdraw(BigDecimal amount); +} From 4128525f001c44f716d67971e3a6ff746a6cd7b0 Mon Sep 17 00:00:00 2001 From: Roger <587230+rojyates@users.noreply.github.com> Date: Sat, 25 Jul 2020 23:45:41 +1000 Subject: [PATCH 132/132] BAEL-1258 Added example code for Jess and JSR94 (#9693) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * BAEL-1258 Added example code for Jess and JSR94 * BAEL-1258 Relocate to rule-modules * BAEL-1258 Remove README as per PR review * šBAEL-1258 Declared exceptions and replace System.out.println with log statements * BAEL-1258 Removed Lombok * BAEL-1258 Removed Lombok * BAEL-1258 Rename artifactId to match directory name --- rule-engines/jess/pom.xml | 25 +++++ .../com/baeldung/rules/jess/JessHello.java | 17 ++++ .../com/baeldung/rules/jess/JessWithData.java | 42 ++++++++ .../baeldung/rules/jess/JessWithJsr94.java | 98 +++++++++++++++++++ .../com/baeldung/rules/jess/model/Answer.java | 31 ++++++ .../baeldung/rules/jess/model/Question.java | 32 ++++++ .../jess/src/main/resources/bonus.clp | 8 ++ .../jess/src/main/resources/helloJess.clp | 3 + 8 files changed, 256 insertions(+) create mode 100644 rule-engines/jess/pom.xml create mode 100644 rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessHello.java create mode 100644 rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessWithData.java create mode 100644 rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessWithJsr94.java create mode 100644 rule-engines/jess/src/main/java/com/baeldung/rules/jess/model/Answer.java create mode 100644 rule-engines/jess/src/main/java/com/baeldung/rules/jess/model/Question.java create mode 100644 rule-engines/jess/src/main/resources/bonus.clp create mode 100644 rule-engines/jess/src/main/resources/helloJess.clp diff --git a/rule-engines/jess/pom.xml b/rule-engines/jess/pom.xml new file mode 100644 index 0000000000..40d50fae70 --- /dev/null +++ b/rule-engines/jess/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + + com.baeldung.rules.jess + jess + 1.0-SNAPSHOT + + + + + jsr94 + jsr94 + 1.1 + + + gov.sandia + jess + 7.1p2 + + + + \ No newline at end of file diff --git a/rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessHello.java b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessHello.java new file mode 100644 index 0000000000..1462996a4c --- /dev/null +++ b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessHello.java @@ -0,0 +1,17 @@ +package com.baeldung.rules.jess; + +import jess.JessException; +import jess.Rete; + +public class JessHello { + public static final String RULES_FILE = "helloJess.clp"; + + public static void main(String[] args) throws JessException { + Rete engine = new Rete(); + engine.reset(); + + engine.batch(RULES_FILE); + + engine.run(); + } +} diff --git a/rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessWithData.java b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessWithData.java new file mode 100644 index 0000000000..5d5dc9b983 --- /dev/null +++ b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessWithData.java @@ -0,0 +1,42 @@ +package com.baeldung.rules.jess; + +import com.baeldung.rules.jess.model.Answer; +import com.baeldung.rules.jess.model.Question; +import jess.Filter; +import jess.JessException; +import jess.Rete; + +import java.util.Iterator; +import java.util.logging.Logger; + +public class JessWithData { + public static final String RULES_BONUS_FILE = "bonus.clp"; + private static Logger log = Logger.getLogger("JessWithData"); + + public static void main(String[] args) throws JessException { + Rete engine = new Rete(); + engine.reset(); + + engine.batch(RULES_BONUS_FILE); + + prepareData(engine); + + engine.run(); + + checkResults(engine); + } + + private static void checkResults(Rete engine) { + Iterator results = engine.getObjects(new Filter.ByClass(Answer.class)); + while (results.hasNext()) { + Answer answer = (Answer) results.next(); + log.info(answer.toString()); + } + } + + private static void prepareData(Rete engine) throws JessException { + Question question = new Question("Can I have a bonus?", -5); + log.info(question.toString()); + engine.add(question); + } +} diff --git a/rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessWithJsr94.java b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessWithJsr94.java new file mode 100644 index 0000000000..f07bf10a7a --- /dev/null +++ b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/JessWithJsr94.java @@ -0,0 +1,98 @@ +package com.baeldung.rules.jess; + +import com.baeldung.rules.jess.model.Answer; +import com.baeldung.rules.jess.model.Question; + +import javax.rules.*; +import javax.rules.admin.RuleAdministrator; +import javax.rules.admin.RuleExecutionSet; +import javax.rules.admin.RuleExecutionSetCreateException; +import javax.rules.admin.RuleExecutionSetRegisterException; +import java.io.IOException; +import java.io.InputStream; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.logging.Logger; + +public class JessWithJsr94 { + public static final String RULES_BONUS_FILE = "/bonus.clp"; + public static final String RULES_URI = "com/baeldung/rules/bonus"; + private static final String RULE_SERVICE_PROVIDER = "jess.jsr94"; + private static Logger log = Logger.getLogger("JessWithData"); + + public static void main(String[] args) throws Exception { + RuleServiceProvider ruleServiceProvider = instantiateJessInstance(); + + // load our rules and register them with the rules provider + registerRules(RULES_BONUS_FILE, RULES_URI, ruleServiceProvider); + + runRules(RULES_URI, ruleServiceProvider); + } + + private static RuleServiceProvider instantiateJessInstance() throws ClassNotFoundException, ConfigurationException { + // Load the rule service provider of the reference implementation. + // Loading this class will automatically register this provider with the provider manager. + Class.forName(RULE_SERVICE_PROVIDER + ".RuleServiceProviderImpl"); + + // Get the rule service provider from the provider manager. + return RuleServiceProviderManager.getRuleServiceProvider(RULE_SERVICE_PROVIDER); + } + + private static void runRules(String rulesURI, RuleServiceProvider ruleServiceProvider) + throws ConfigurationException, RuleSessionTypeUnsupportedException, RuleSessionCreateException, RuleExecutionSetNotFoundException, RemoteException, InvalidRuleSessionException { + // Get a RuleRuntime and invoke the rule engine. + RuleRuntime ruleRuntime = ruleServiceProvider.getRuleRuntime(); + + //Create a statelessRuleSession. + StatelessRuleSession statelessRuleSession = (StatelessRuleSession) ruleRuntime.createRuleSession(rulesURI, new HashMap(), RuleRuntime.STATELESS_SESSION_TYPE); + + calculateResults(statelessRuleSession); + + statelessRuleSession.release(); + } + + private static void calculateResults(StatelessRuleSession statelessRuleSession) throws InvalidRuleSessionException, RemoteException { + List data = prepareData(); + + // execute the rules + List results = statelessRuleSession.executeRules(data); + + checkResults(results); + } + + private static List prepareData() { + List data = new ArrayList(); + data.add(new Question("Can I have a bonus?", -5)); + return data; + } + + private static void checkResults(List results) { + Iterator itr = results.iterator(); + while (itr.hasNext()) { + Object obj = itr.next(); + if (obj instanceof Answer) { + log.info(obj.toString()); + } + } + } + + private static void registerRules(String rulesFile, String rulesURI, RuleServiceProvider serviceProvider) throws ConfigurationException, RuleExecutionSetCreateException, IOException, RuleExecutionSetRegisterException { + // Get the rule administrator. + RuleAdministrator ruleAdministrator = serviceProvider.getRuleAdministrator(); + + // load the rules + InputStream ruleInput = JessWithJsr94.class.getResourceAsStream(rulesFile); + HashMap vendorProperties = new HashMap(); + + // Create the RuleExecutionSet + RuleExecutionSet ruleExecutionSet = ruleAdministrator + .getLocalRuleExecutionSetProvider(vendorProperties) + .createRuleExecutionSet(ruleInput, vendorProperties); + + // Register the rule execution set. + ruleAdministrator.registerRuleExecutionSet(rulesURI, ruleExecutionSet, vendorProperties); + } +} \ No newline at end of file diff --git a/rule-engines/jess/src/main/java/com/baeldung/rules/jess/model/Answer.java b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/model/Answer.java new file mode 100644 index 0000000000..d690d04e13 --- /dev/null +++ b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/model/Answer.java @@ -0,0 +1,31 @@ +package com.baeldung.rules.jess.model; + +public class Answer { + private String answer; + private int newBalance; + + public Answer(String answer, int newBalance) { + this.answer = answer; + this.newBalance = newBalance; + } + + public int getNewBalance() { + return newBalance; + } + + public void setNewBalance(int newBalance) { + this.newBalance = newBalance; + } + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + public String toString() { + return "Answer(answer=" + answer + ", newBalance=" + newBalance + ")"; + } +} diff --git a/rule-engines/jess/src/main/java/com/baeldung/rules/jess/model/Question.java b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/model/Question.java new file mode 100644 index 0000000000..499113d0fc --- /dev/null +++ b/rule-engines/jess/src/main/java/com/baeldung/rules/jess/model/Question.java @@ -0,0 +1,32 @@ +package com.baeldung.rules.jess.model; + +public class Question { + private String question; + private int balance; + + public Question(String question, int balance) { + this.question = question; + this.balance = balance; + } + + public String getQuestion() { + return question; + } + + public void setQuestion(String question) { + this.question = question; + } + + public int getBalance() { + return balance; + } + + public void setBalance(int balance) { + this.balance = balance; + } + + public String toString() { + return "Question(question=" + question + ", balance=" + balance + ")"; + } + +} diff --git a/rule-engines/jess/src/main/resources/bonus.clp b/rule-engines/jess/src/main/resources/bonus.clp new file mode 100644 index 0000000000..7f430bc43f --- /dev/null +++ b/rule-engines/jess/src/main/resources/bonus.clp @@ -0,0 +1,8 @@ +(import com.baeldung.rules.jess.model.*) +(deftemplate Question (declare (from-class Question))) +(deftemplate Answer (declare (from-class Answer))) + +(defrule avoid-overdraft "Give $50 to anyone overdrawn" + ?q <- (Question { balance < 0 }) + => + (add (new Answer "Overdrawn bonus" (+ ?q.balance 50)))) diff --git a/rule-engines/jess/src/main/resources/helloJess.clp b/rule-engines/jess/src/main/resources/helloJess.clp new file mode 100644 index 0000000000..547294eca6 --- /dev/null +++ b/rule-engines/jess/src/main/resources/helloJess.clp @@ -0,0 +1,3 @@ +;; Hello, world in Jess! + +(printout t "Hello from Jess!" crlf)