diff --git a/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy b/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy new file mode 100644 index 0000000000..3ac88b7952 --- /dev/null +++ b/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy @@ -0,0 +1,14 @@ +package com.baeldung.determinedatatype + +class Person { + + private int ageAsInt + private Double ageAsDouble + private String ageAsString + + Person() {} + Person(int ageAsInt) { this.ageAsInt = ageAsInt} + Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble} + Person(String ageAsString) { this.ageAsString = ageAsString} +} +class Student extends Person {} diff --git a/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy new file mode 100644 index 0000000000..4c6589f207 --- /dev/null +++ b/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy @@ -0,0 +1,56 @@ +package com.baeldung.determinedatatype + +import org.junit.Assert +import org.junit.Test +import com.baeldung.determinedatatype.Person + +public class PersonTest { + + @Test + public void givenWhenParameterTypeIsInteger_thenReturnTrue() { + Person personObj = new Person(10) + Assert.assertTrue(personObj.ageAsInt instanceof Integer) + } + + @Test + public void givenWhenParameterTypeIsDouble_thenReturnTrue() { + Person personObj = new Person(10.0) + Assert.assertTrue((personObj.ageAsDouble).getClass() == Double) + } + + @Test + public void givenWhenParameterTypeIsString_thenReturnTrue() { + Person personObj = new Person("10 years") + Assert.assertTrue(personObj.ageAsString.class == String) + } + + @Test + public void givenClassName_WhenParameterIsInteger_thenReturnTrue() { + Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class) + } + + @Test + public void givenWhenObjectIsInstanceOfType_thenReturnTrue() { + Person personObj = new Person() + Assert.assertTrue(personObj instanceof Person) + } + + @Test + public void givenWhenInstanceIsOfSubtype_thenReturnTrue() { + Student studentObj = new Student() + Assert.assertTrue(studentObj in Person) + } + + @Test + public void givenGroovyList_WhenFindClassName_thenReturnTrue() { + def ageList = ['ageAsString','ageAsDouble', 10] + Assert.assertTrue(ageList.class == ArrayList) + Assert.assertTrue(ageList.getClass() == ArrayList) + } + + @Test + public void givenGrooyMap_WhenFindClassName_thenReturnTrue() { + def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0] + Assert.assertFalse(ageMap.class == LinkedHashMap) + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java index 33243c4ecf..7ae2af0857 100644 --- a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java @@ -4,19 +4,19 @@ import java.util.Objects; public record Person (String name, String address) { - public static String UNKWOWN_ADDRESS = "Unknown"; - public static String UNNAMED = "Unnamed"; + public static String UNKNOWN_ADDRESS = "Unknown"; + public static String UNNAMED = "Unnamed"; - public Person { - Objects.requireNonNull(name); - Objects.requireNonNull(address); - } + public Person { + Objects.requireNonNull(name); + Objects.requireNonNull(address); + } - public Person(String name) { - this(name, UNKWOWN_ADDRESS); - } + public Person(String name) { + this(name, UNKNOWN_ADDRESS); + } - public static Person unnamed(String address) { - return new Person(UNNAMED, address); - } -} + public static Person unnamed(String address) { + return new Person(UNNAMED, address); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/record/PersonTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/record/PersonTest.java index 4a7d4ede5f..9bed3dab8f 100644 --- a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/record/PersonTest.java +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/record/PersonTest.java @@ -134,7 +134,7 @@ public class PersonTest { Person person = new Person(name); assertEquals(name, person.name()); - assertEquals(Person.UNKWOWN_ADDRESS, person.address()); + assertEquals(Person.UNKNOWN_ADDRESS, person.address()); } @Test @@ -147,4 +147,4 @@ public class PersonTest { assertEquals(Person.UNNAMED, person.name()); assertEquals(address, person.address()); } -} +} \ No newline at end of file diff --git a/core-java-modules/core-java-8-datetime-2/pom.xml b/core-java-modules/core-java-8-datetime-2/pom.xml index 629ce5234d..f66a89ca55 100644 --- a/core-java-modules/core-java-8-datetime-2/pom.xml +++ b/core-java-modules/core-java-8-datetime-2/pom.xml @@ -4,7 +4,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - core-java-8-datetime + core-java-8-datetime-2 ${project.parent.version} core-java-8-datetime jar @@ -41,7 +41,6 @@ - core-java-datetime-java8 src/main/resources diff --git a/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/varhandles/VariableHandlesUnitTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/varhandles/VariableHandlesUnitTest.java index 56e34f06a0..a7263f0bb2 100644 --- a/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/varhandles/VariableHandlesUnitTest.java +++ b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/varhandles/VariableHandlesUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; -import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; public class VariableHandlesUnitTest { @@ -18,25 +18,23 @@ public class VariableHandlesUnitTest { @Test public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles + VarHandle PUBLIC_TEST_VARIABLE = MethodHandles .lookup() .in(VariableHandlesUnitTest.class) .findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class); - assertThat(publicIntHandle.coordinateTypes().size() == 1); - assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandlesUnitTest.class); - + assertEquals(1, PUBLIC_TEST_VARIABLE.coordinateTypes().size()); + assertEquals(VariableHandlesUnitTest.class, PUBLIC_TEST_VARIABLE.coordinateTypes().get(0)); } @Test public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException { - VarHandle privateIntHandle = MethodHandles + VarHandle PRIVATE_TEST_VARIABLE = MethodHandles .privateLookupIn(VariableHandlesUnitTest.class, MethodHandles.lookup()) .findVarHandle(VariableHandlesUnitTest.class, "privateTestVariable", int.class); - assertThat(privateIntHandle.coordinateTypes().size() == 1); - assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesUnitTest.class); - + assertEquals(1, PRIVATE_TEST_VARIABLE.coordinateTypes().size()); + assertEquals(VariableHandlesUnitTest.class, PRIVATE_TEST_VARIABLE.coordinateTypes().get(0)); } @Test @@ -44,63 +42,64 @@ public class VariableHandlesUnitTest { VarHandle arrayVarHandle = MethodHandles .arrayElementVarHandle(int[].class); - assertThat(arrayVarHandle.coordinateTypes().size() == 2); - assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class); + assertEquals(2, arrayVarHandle.coordinateTypes().size()); + assertEquals(int[].class, arrayVarHandle.coordinateTypes().get(0)); } @Test public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles + VarHandle PUBLIC_TEST_VARIABLE = MethodHandles .lookup() .in(VariableHandlesUnitTest.class) .findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class); - assertThat((int) publicIntHandle.get(this) == 1); + assertEquals(1, (int) PUBLIC_TEST_VARIABLE.get(this)); } @Test public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles + VarHandle VARIABLE_TO_SET = MethodHandles .lookup() .in(VariableHandlesUnitTest.class) .findVarHandle(VariableHandlesUnitTest.class, "variableToSet", int.class); - publicIntHandle.set(this, 15); - assertThat((int) publicIntHandle.get(this) == 15); + VARIABLE_TO_SET.set(this, 15); + assertEquals(15, (int) VARIABLE_TO_SET.get(this)); } @Test public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles + VarHandle VARIABLE_TO_COMPARE_AND_SET = MethodHandles .lookup() .in(VariableHandlesUnitTest.class) .findVarHandle(VariableHandlesUnitTest.class, "variableToCompareAndSet", int.class); - publicIntHandle.compareAndSet(this, 1, 100); - assertThat((int) publicIntHandle.get(this) == 100); + VARIABLE_TO_COMPARE_AND_SET.compareAndSet(this, 1, 100); + assertEquals(100, (int) VARIABLE_TO_COMPARE_AND_SET.get(this)); } @Test public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles + VarHandle VARIABLE_TO_GET_AND_ADD = MethodHandles .lookup() .in(VariableHandlesUnitTest.class) .findVarHandle(VariableHandlesUnitTest.class, "variableToGetAndAdd", int.class); - int before = (int) publicIntHandle.getAndAdd(this, 200); - assertThat(before == 0); - assertThat((int) publicIntHandle.get(this) == 200); + int before = (int) VARIABLE_TO_GET_AND_ADD.getAndAdd(this, 200); + + assertEquals(0, before); + assertEquals(200, (int) VARIABLE_TO_GET_AND_ADD.get(this)); } @Test public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles + VarHandle VARIABLE_TO_BITWISE_OR = MethodHandles .lookup() .in(VariableHandlesUnitTest.class) .findVarHandle(VariableHandlesUnitTest.class, "variableToBitwiseOr", byte.class); - byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127); + byte before = (byte) VARIABLE_TO_BITWISE_OR.getAndBitwiseOr(this, (byte) 127); - assertThat(before == 0); - assertThat(variableToBitwiseOr == 127); + assertEquals(0, before); + assertEquals(127, (byte) VARIABLE_TO_BITWISE_OR.get(this)); } } diff --git a/core-java-modules/core-java-collections-3/README.md b/core-java-modules/core-java-collections-3/README.md index 9218384640..fb983d9abc 100644 --- a/core-java-modules/core-java-collections-3/README.md +++ b/core-java-modules/core-java-collections-3/README.md @@ -9,3 +9,4 @@ - [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall) - [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) diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/stack/StackUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java rename to core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/stack/StackUnitTest.java diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/abaproblem/Account.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/abaproblem/Account.java new file mode 100644 index 0000000000..ee1bdcd55b --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/abaproblem/Account.java @@ -0,0 +1,66 @@ +package com.baeldung.abaproblem; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +public class Account { + + private AtomicInteger balance; + private AtomicInteger transactionCount; + private ThreadLocal currentThreadCASFailureCount; + + public Account() { + this.balance = new AtomicInteger(0); + this.transactionCount = new AtomicInteger(0); + this.currentThreadCASFailureCount = new ThreadLocal<>(); + this.currentThreadCASFailureCount.set(0); + } + + public int getBalance() { + return balance.get(); + } + + public int getTransactionCount() { + return transactionCount.get(); + } + + public int getCurrentThreadCASFailureCount() { + return currentThreadCASFailureCount.get(); + } + + public boolean withdraw(int amount) { + int current = getBalance(); + maybeWait(); + boolean result = balance.compareAndSet(current, current - amount); + if (result) { + transactionCount.incrementAndGet(); + } else { + int currentCASFailureCount = currentThreadCASFailureCount.get(); + currentThreadCASFailureCount.set(currentCASFailureCount + 1); + } + return result; + } + + private void maybeWait() { + if ("thread1".equals(Thread.currentThread().getName())) { + try { + TimeUnit.SECONDS.sleep(2); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + public boolean deposit(int amount) { + int current = balance.get(); + boolean result = balance.compareAndSet(current, current + amount); + if (result) { + transactionCount.incrementAndGet(); + } else { + int currentCASFailureCount = currentThreadCASFailureCount.get(); + currentThreadCASFailureCount.set(currentCASFailureCount + 1); + } + return result; + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java index 1a46e1ba52..415b24738a 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java @@ -9,13 +9,11 @@ public class StampedAccount { private AtomicStampedReference account = new AtomicStampedReference<>(0, 0); public int getBalance() { - return this.account.get(new int[1]); + return account.getReference(); } public int getStamp() { - int[] stamps = new int[1]; - this.account.get(stamps); - return stamps[0]; + return account.getStamp(); } public boolean deposit(int funds) { diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/abaproblem/AccountUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/abaproblem/AccountUnitTest.java new file mode 100644 index 0000000000..aa5f0f7997 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/abaproblem/AccountUnitTest.java @@ -0,0 +1,98 @@ +package com.baeldung.abaproblem; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class AccountUnitTest { + + private Account account; + + @BeforeEach + public void setUp() { + account = new Account(); + } + + @Test + public void zeroBalanceInitializationTest() { + assertEquals(0, account.getBalance()); + assertEquals(0, account.getTransactionCount()); + assertEquals(0, account.getCurrentThreadCASFailureCount()); + } + + @Test + public void depositTest() { + final int moneyToDeposit = 50; + + assertTrue(account.deposit(moneyToDeposit)); + + assertEquals(moneyToDeposit, account.getBalance()); + } + + @Test + public void withdrawTest() throws InterruptedException { + final int defaultBalance = 50; + final int moneyToWithdraw = 20; + + account.deposit(defaultBalance); + + assertTrue(account.withdraw(moneyToWithdraw)); + + assertEquals(defaultBalance - moneyToWithdraw, account.getBalance()); + } + + @Test + public void abaProblemTest() throws InterruptedException { + final int defaultBalance = 50; + + final int amountToWithdrawByThread1 = 20; + final int amountToWithdrawByThread2 = 10; + final int amountToDepositByThread2 = 10; + + assertEquals(0, account.getTransactionCount()); + assertEquals(0, account.getCurrentThreadCASFailureCount()); + account.deposit(defaultBalance); + assertEquals(1, account.getTransactionCount()); + + Thread thread1 = new Thread(() -> { + + // this will take longer due to the name of the thread + assertTrue(account.withdraw(amountToWithdrawByThread1)); + + // thread 1 fails to capture ABA problem + assertNotEquals(1, account.getCurrentThreadCASFailureCount()); + + }, "thread1"); + + Thread thread2 = new Thread(() -> { + + assertTrue(account.deposit(amountToDepositByThread2)); + assertEquals(defaultBalance + amountToDepositByThread2, account.getBalance()); + + // this will be fast due to the name of the thread + assertTrue(account.withdraw(amountToWithdrawByThread2)); + + // thread 1 didn't finish yet, so the original value will be in place for it + assertEquals(defaultBalance, account.getBalance()); + + assertEquals(0, account.getCurrentThreadCASFailureCount()); + }, "thread2"); + + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + // compareAndSet operation succeeds for thread 1 + assertEquals(defaultBalance - amountToWithdrawByThread1, account.getBalance()); + + //but there are other transactions + assertNotEquals(2, account.getTransactionCount()); + + // thread 2 did two modifications as well + assertEquals(4, account.getTransactionCount()); + } +} diff --git a/core-java-modules/core-java-console/README.md b/core-java-modules/core-java-console/README.md new file mode 100644 index 0000000000..725e2482bb --- /dev/null +++ b/core-java-modules/core-java-console/README.md @@ -0,0 +1,5 @@ +#Core Java Console + +[Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output) +[Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf) +[ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java) \ No newline at end of file diff --git a/core-java-modules/core-java-console/pom.xml b/core-java-modules/core-java-console/pom.xml new file mode 100644 index 0000000000..1d58d8c253 --- /dev/null +++ b/core-java-modules/core-java-console/pom.xml @@ -0,0 +1,142 @@ + + + 4.0.0 + core-java-console + 0.1.0-SNAPSHOT + core-java-console + jar + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + ../ + + + + core-java-console + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + java + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed + + -Xmx300m + -XX:+UseParallelGC + -classpath + + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + ${source.version} + ${target.version} + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + json + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + run-benchmarks + + none + + exec + + + test + java + + -classpath + + org.openjdk.jmh.Main + .* + + + + + + + + + + + + 3.0.0-M1 + 1.6.0 + 1.8 + 1.8 + + + diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java b/core-java-modules/core-java-console/src/main/java/com/baeldung/asciiart/AsciiArt.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java rename to core-java-modules/core-java-console/src/main/java/com/baeldung/asciiart/AsciiArt.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/console/ConsoleConsoleClass.java b/core-java-modules/core-java-console/src/main/java/com/baeldung/console/ConsoleConsoleClass.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/console/ConsoleConsoleClass.java rename to core-java-modules/core-java-console/src/main/java/com/baeldung/console/ConsoleConsoleClass.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/console/ConsoleScannerClass.java b/core-java-modules/core-java-console/src/main/java/com/baeldung/console/ConsoleScannerClass.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/console/ConsoleScannerClass.java rename to core-java-modules/core-java-console/src/main/java/com/baeldung/console/ConsoleScannerClass.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/printf/PrintfExamples.java b/core-java-modules/core-java-console/src/main/java/com/baeldung/printf/PrintfExamples.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/printf/PrintfExamples.java rename to core-java-modules/core-java-console/src/main/java/com/baeldung/printf/PrintfExamples.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java b/core-java-modules/core-java-console/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java similarity index 94% rename from core-java-modules/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java rename to core-java-modules/core-java-console/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java index 8ab1695395..a8c42fbeb1 100644 --- a/core-java-modules/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java +++ b/core-java-modules/core-java-console/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java @@ -1,10 +1,9 @@ package com.baeldung.asciiart; -import java.awt.Font; - +import com.baeldung.asciiart.AsciiArt.Settings; import org.junit.Test; -import com.baeldung.asciiart.AsciiArt.Settings; +import java.awt.*; public class AsciiArtIntegrationTest { @@ -16,5 +15,4 @@ public class AsciiArtIntegrationTest { asciiArt.drawString(text, "*", settings); } - } diff --git a/core-java-modules/core-java-date-operations-2/README.md b/core-java-modules/core-java-date-operations-2/README.md index 19c7b98d30..6dc1302d99 100644 --- a/core-java-modules/core-java-date-operations-2/README.md +++ b/core-java-modules/core-java-date-operations-2/README.md @@ -8,4 +8,5 @@ This module contains articles about date operations in Java. - [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime) - [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone) - [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week) +- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) - [[<-- Prev]](/core-java-modules/core-java-date-operations-1) diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/leapyear/LeapYearUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/leapyear/LeapYearUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/leapyear/LeapYearUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/leapyear/LeapYearUnitTest.java diff --git a/core-java-modules/core-java-jvm/README.md b/core-java-modules/core-java-jvm/README.md index 2f80ea7372..0dae790ec0 100644 --- a/core-java-modules/core-java-jvm/README.md +++ b/core-java-modules/core-java-jvm/README.md @@ -12,3 +12,4 @@ This module contains articles about working with the Java Virtual Machine (JVM). - [Guide to System.gc()](https://www.baeldung.com/java-system-gc) - [Runtime.getRuntime().halt() vs System.exit() in Java](https://www.baeldung.com/java-runtime-halt-vs-system-exit) - [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks) +- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/objectsize/InstrumentationExample.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/objectsize/InstrumentationExample.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/objectsize/InstrumentationExample.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/objectsize/InstrumentationExample.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/objectsize/MANIFEST.MF b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/objectsize/MANIFEST.MF similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/objectsize/MANIFEST.MF rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/objectsize/MANIFEST.MF diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/varargs/HeapPollutionUnitTest.java b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/varargs/HeapPollutionUnitTest.java new file mode 100644 index 0000000000..ced2c00bea --- /dev/null +++ b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/varargs/HeapPollutionUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.varargs; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class HeapPollutionUnitTest { + + @Test(expected = ClassCastException.class) + public void givenGenericVararg_whenUsedUnsafe_shouldThrowClassCastException() { + String one = firstOfFirst(Arrays.asList("one", "two"), Collections.emptyList()); + + assertEquals("one", one); + } + + @Test(expected = ClassCastException.class) + public void givenGenericVararg_whenRefEscapes_mayCauseSubtleBugs() { + String[] args = returnAsIs("One", "Two"); + } + + private static String firstOfFirst(List... strings) { + List ints = Collections.singletonList(42); + Object[] objects = strings; + objects[0] = ints; + + return strings[0].get(0); + } + + private static T[] toArray(T... arguments) { + return arguments; + } + + private static T[] returnAsIs(T a, T b) { + return toArray(a, b); + } +} diff --git a/core-java-modules/core-java-reflection/README.MD b/core-java-modules/core-java-reflection/README.MD index 5aed62b378..d6b3a02e6a 100644 --- a/core-java-modules/core-java-reflection/README.MD +++ b/core-java-modules/core-java-reflection/README.MD @@ -8,3 +8,5 @@ - [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params) - [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) - [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception) +- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null) +- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java rename to core-java-modules/core-java-reflection/src/test/java/com/baeldung/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/java/reflection/ReflectionUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/java/reflection/ReflectionUnitTest.java index 0c090901e7..a791d64874 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/java/reflection/ReflectionUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/java/reflection/ReflectionUnitTest.java @@ -200,7 +200,7 @@ public class ReflectionUnitTest { @Test public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception { final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - final Bird bird = (Bird) birdClass.newInstance(); + final Bird bird = (Bird) birdClass.getConstructor().newInstance(); final Field field = birdClass.getDeclaredField("walks"); field.setAccessible(true); @@ -266,7 +266,7 @@ public class ReflectionUnitTest { @Test public void givenMethod_whenInvokes_thenCorrect() throws Exception { final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - final Bird bird = (Bird) birdClass.newInstance(); + final Bird bird = (Bird) birdClass.getConstructor().newInstance(); final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class); final Method walksMethod = birdClass.getDeclaredMethod("walks"); final boolean walks = (boolean) walksMethod.invoke(bird); diff --git a/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntOrIntegerUnitTest.java b/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntOrIntegerUnitTest.java index 106f1fc974..336b2ac324 100644 --- a/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntOrIntegerUnitTest.java +++ b/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntOrIntegerUnitTest.java @@ -26,6 +26,17 @@ public class StringToIntOrIntegerUnitTest { assertThat(result).isEqualTo(new Integer(42)); } + @Test + public void givenString_whenCallingValueOf_shouldCacheSomeValues() { + for (int i = -128; i <= 127; i++) { + String value = i + ""; + Integer first = Integer.valueOf(value); + Integer second = Integer.valueOf(value); + + assertThat(first).isSameAs(second); + } + } + @Test public void givenString_whenCallingIntegerConstructor_shouldConvertToInt() { String givenString = "42"; diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index 2f54aa9467..cafb3b9017 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -12,4 +12,6 @@ This module contains articles about string operations. - [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives) - [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) - [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8) +- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) +- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) #remove additional readme file - More articles: [[<-- prev]](../core-java-string-operations) diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/encoding/CharacterEncodingExamples.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/encoding/CharacterEncodingExamples.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/encoding/CharacterEncodingExamples.java rename to core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/encoding/CharacterEncodingExamples.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/encoding/CharacterEncodingExamplesUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encoding/CharacterEncodingExamplesUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/encoding/CharacterEncodingExamplesUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encoding/CharacterEncodingExamplesUnitTest.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/hexToAscii/HexToAsciiUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/hexToAscii/HexToAsciiUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/hexToAscii/HexToAsciiUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/hexToAscii/HexToAsciiUnitTest.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/hexToAscii/README.md b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/hexToAscii/README.md similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/hexToAscii/README.md rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/hexToAscii/README.md diff --git a/core-java-modules/core-java/src/test/resources/encoding.txt b/core-java-modules/core-java-string-operations-2/src/test/resources/encoding.txt similarity index 100% rename from core-java-modules/core-java/src/test/resources/encoding.txt rename to core-java-modules/core-java-string-operations-2/src/test/resources/encoding.txt diff --git a/core-java-modules/core-java-string-operations-2/src/test/resources/output.pdf b/core-java-modules/core-java-string-operations-2/src/test/resources/output.pdf new file mode 100644 index 0000000000..94d9477974 Binary files /dev/null and b/core-java-modules/core-java-string-operations-2/src/test/resources/output.pdf differ diff --git a/core-java-modules/core-java-time-measurements/README.md b/core-java-modules/core-java-time-measurements/README.md index 1bd277b6b1..a3e8b71ae8 100644 --- a/core-java-modules/core-java-time-measurements/README.md +++ b/core-java-modules/core-java-time-measurements/README.md @@ -6,3 +6,4 @@ This module contains articles about the measurement of time in Java. - [Guide to the Java Clock Class](http://www.baeldung.com/java-clock) - [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) - [Overriding System Time for Testing in Java](https://www.baeldung.com/java-override-system-time) +- [Java Timer](http://www.baeldung.com/java-timer-and-timertask) diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java b/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java rename to core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/timer/NewsletterTask.java b/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/timer/NewsletterTask.java rename to core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java diff --git a/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/java/clock/ClockUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/clock/ClockUnitTest.java similarity index 99% rename from core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/java/clock/ClockUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/clock/ClockUnitTest.java index e83ba7afc8..4e34271214 100644 --- a/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/java/clock/ClockUnitTest.java +++ b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/clock/ClockUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.clock; +package com.baeldung.clock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/timer/JavaTimerLongRunningUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/JavaTimerLongRunningUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/timer/JavaTimerLongRunningUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/JavaTimerLongRunningUnitTest.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index bffb88cafb..7781382ae5 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -1,35 +1,13 @@ ## Core Java Cookbooks and Examples ### Relevant Articles: -- [Java Timer](http://www.baeldung.com/java-timer-and-timertask) -- [Getting Started with Java Properties](http://www.baeldung.com/java-properties) -- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) -- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) -- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging) -- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null) -- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) -- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) -- [Guide to UUID in Java](http://www.baeldung.com/java-uuid) -- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) -- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack) -- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) -- [Introduction to Javadoc](http://www.baeldung.com/javadoc) -- [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) -- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java) -- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) -- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) -- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) -- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) -- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) -- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) -- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) -- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) -- [Graphs in Java](https://www.baeldung.com/java-graphs) -- [Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output) -- [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf) -- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields) -- [Using Curl in Java](https://www.baeldung.com/java-curl) -- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) -- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post) -- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) -- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) +[Getting Started with Java Properties](http://www.baeldung.com/java-properties) +[Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) +[Introduction to Java Serialization](http://www.baeldung.com/java-serialization) +[Guide to UUID in Java](http://www.baeldung.com/java-uuid) +[Compiling Java *.class Files with javac](http://www.baeldung.com/javac) +[Introduction to Javadoc](http://www.baeldung.com/javadoc) +[Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) +[What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) +[A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) +[Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java b/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java index 2659b29491..cb43a26929 100644 --- a/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java +++ b/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java @@ -3,30 +3,57 @@ package com.baeldung.uuid; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.LocalDateTime; import java.util.Arrays; +import java.util.Random; import java.util.UUID; public class UUIDGenerator { - /** - * These are predefined UUID for name spaces - */ - private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8"; - private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); - public static void main(String[] args) { - try { - System.out.println("Type 3 : " + generateType3UUID(NAMESPACE_DNS, "google.com")); - System.out.println("Type 4 : " + generateType4UUID()); - System.out.println("Type 5 : " + generateType5UUID(NAMESPACE_URL, "google.com")); - System.out.println("Unique key : " + generateUniqueKeysWithUUIDAndMessageDigest()); - } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { - e.printStackTrace(); - } + /** + * Type 1 UUID Generation + */ + public static UUID generateType1UUID() { + + long most64SigBits = get64MostSignificantBitsForVersion1(); + long least64SigBits = get64LeastSignificantBitsForVersion1(); + + return new UUID(most64SigBits, least64SigBits); + } + + private static long get64LeastSignificantBitsForVersion1() { + Random random = new Random(); + long random63BitLong = random.nextLong() & 0x3FFFFFFFFFFFFFFFL; + long variant3BitFlag = 0x8000000000000000L; + return random63BitLong + variant3BitFlag; + } + + private static long get64MostSignificantBitsForVersion1() { + LocalDateTime start = LocalDateTime.of(1582, 10, 15, 0, 0, 0); + Duration duration = Duration.between(start, LocalDateTime.now()); + long seconds = duration.getSeconds(); + long nanos = duration.getNano(); + long timeForUuidIn100Nanos = seconds * 10000000 + nanos * 100; + long least12SignificatBitOfTime = (timeForUuidIn100Nanos & 0x000000000000FFFFL) >> 4; + long version = 1 << 12; + return (timeForUuidIn100Nanos & 0xFFFFFFFFFFFF0000L) + version + least12SignificatBitOfTime; + } + + /** + * Type 3 UUID Generation + * + * @throws UnsupportedEncodingException + */ + public static UUID generateType3UUID(String namespace, String name) throws UnsupportedEncodingException { + + byte[] nameSpaceBytes = bytesFromUUID(namespace); + byte[] nameBytes = name.getBytes("UTF-8"); + byte[] result = joinBytes(nameSpaceBytes, nameBytes); + + return UUID.nameUUIDFromBytes(result); } /** @@ -37,28 +64,18 @@ public class UUIDGenerator { return uuid; } - /** - * Type 3 UUID Generation - * - * @throws UnsupportedEncodingException - */ - public static UUID generateType3UUID(String namespace, String name) throws UnsupportedEncodingException { - String source = namespace + name; - byte[] bytes = source.getBytes("UTF-8"); - UUID uuid = UUID.nameUUIDFromBytes(bytes); - return uuid; - } - /** * Type 5 UUID Generation - * - * @throws UnsupportedEncodingException + * + * @throws UnsupportedEncodingException */ public static UUID generateType5UUID(String namespace, String name) throws UnsupportedEncodingException { - String source = namespace + name; - byte[] bytes = source.getBytes("UTF-8"); - UUID uuid = type5UUIDFromBytes(bytes); - return uuid; + + byte[] nameSpaceBytes = bytesFromUUID(namespace); + byte[] nameBytes = name.getBytes("UTF-8"); + byte[] result = joinBytes(nameSpaceBytes, nameBytes); + + return type5UUIDFromBytes(result); } public static UUID type5UUIDFromBytes(byte[] name) { @@ -91,20 +108,20 @@ public class UUIDGenerator { /** * Unique Keys Generation Using Message Digest and Type 4 UUID - * - * @throws NoSuchAlgorithmException - * @throws UnsupportedEncodingException + * + * @throws NoSuchAlgorithmException + * @throws UnsupportedEncodingException */ public static String generateUniqueKeysWithUUIDAndMessageDigest() throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest salt = MessageDigest.getInstance("SHA-256"); salt.update(UUID.randomUUID() - .toString() - .getBytes("UTF-8")); + .toString() + .getBytes("UTF-8")); String digest = bytesToHex(salt.digest()); return digest; } - public static String bytesToHex(byte[] bytes) { + private static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; @@ -114,4 +131,37 @@ public class UUIDGenerator { return new String(hexChars); } -} + private static byte[] bytesFromUUID(String uuidHexString) { + String normalizedUUIDHexString = uuidHexString.replace("-",""); + + assert normalizedUUIDHexString.length() == 32; + + byte[] bytes = new byte[16]; + for (int i = 0; i < 16; i++) { + byte b = hexToByte(normalizedUUIDHexString.substring(i*2, i*2+2)); + bytes[i] = b; + } + return bytes; + } + + public static byte hexToByte(String hexString) { + int firstDigit = Character.digit(hexString.charAt(0),16); + int secondDigit = Character.digit(hexString.charAt(1),16); + return (byte) ((firstDigit << 4) + secondDigit); + } + + public static byte[] joinBytes(byte[] byteArray1, byte[] byteArray2) { + int finalLength = byteArray1.length + byteArray2.length; + byte[] result = new byte[finalLength]; + + for(int i = 0; i < byteArray1.length; i++) { + result[i] = byteArray1[i]; + } + + for(int i = 0; i < byteArray2.length; i++) { + result[byteArray1.length+i] = byteArray2[i]; + } + + return result; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java new file mode 100644 index 0000000000..9e08363a63 --- /dev/null +++ b/core-java-modules/core-java/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.uuid; + +import org.junit.jupiter.api.Test; + +import java.io.UnsupportedEncodingException; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class UUIDGeneratorUnitTest { + + private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; + + @Test + public void version_1_UUID_is_generated_with_correct_length_version_and_variant() { + + UUID uuid = UUIDGenerator.generateType1UUID(); + + assertEquals(36, uuid.toString().length()); + assertEquals(1, uuid.version()); + assertEquals(2, uuid.variant()); + } + + @Test + public void version_3_UUID_is_correctly_generated_for_domain_baeldung_com() throws UnsupportedEncodingException { + + UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "baeldung.com"); + + assertEquals("23785b78-0132-3ac6-aff6-cfd5be162139", uuid.toString()); + assertEquals(3, uuid.version()); + assertEquals(2, uuid.variant()); + } + + @Test + public void version_3_UUID_is_correctly_generated_for_domain_d() throws UnsupportedEncodingException { + + UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "d"); + + assertEquals("dbd41ecb-f466-33de-b309-1468addfc63b", uuid.toString()); + assertEquals(3, uuid.version()); + assertEquals(2, uuid.variant()); + } + + @Test + public void version_4_UUID_is_generated_with_correct_length_version_and_variant() { + + UUID uuid = UUIDGenerator.generateType4UUID(); + + assertEquals(36, uuid.toString().length()); + assertEquals(4, uuid.version()); + assertEquals(2, uuid.variant()); + } + + @Test + public void version_5_UUID_is_correctly_generated_for_domain_baeldung_com() throws UnsupportedEncodingException { + + UUID uuid = UUIDGenerator.generateType5UUID(NAMESPACE_URL, "baeldung.com"); + + assertEquals("aeff44a5-8a61-52b6-bcbe-c8e5bd7d0300", uuid.toString()); + assertEquals(5, uuid.version()); + assertEquals(2, uuid.variant()); + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-2/README.md b/core-kotlin-modules/core-kotlin-2/README.md deleted file mode 100644 index d6d6b2f706..0000000000 --- a/core-kotlin-modules/core-kotlin-2/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Core Kotlin 2 - -This module contains articles about Kotlin core features. - -### Relevant articles: -- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates) -- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-operator) -- [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences) -- [[<-- Prev]](/core-kotlin-modules/core-kotlin) diff --git a/core-kotlin-modules/core-kotlin-collections/README.md b/core-kotlin-modules/core-kotlin-collections/README.md index 66f15e7419..997680c2bc 100644 --- a/core-kotlin-modules/core-kotlin-collections/README.md +++ b/core-kotlin-modules/core-kotlin-collections/README.md @@ -10,3 +10,4 @@ This module contains articles about core Kotlin collections. - [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection) - [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations) - [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) diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/sorting/SortingExample.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt rename to core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/sorting/SortingExample.kt diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt rename to core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt diff --git a/core-kotlin-modules/core-kotlin-datastructures/README.md b/core-kotlin-modules/core-kotlin-datastructures/README.md new file mode 100644 index 0000000000..3b22730a76 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-datastructures/README.md @@ -0,0 +1,6 @@ +## Core Kotlin + +This module contains articles about data structures in Kotlin + +### Relevant articles: +[Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree) diff --git a/core-kotlin-modules/core-kotlin-datastructures/pom.xml b/core-kotlin-modules/core-kotlin-datastructures/pom.xml new file mode 100644 index 0000000000..eae11c17cf --- /dev/null +++ b/core-kotlin-modules/core-kotlin-datastructures/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + core-kotlin-datastructures + core-kotlin-datastructures + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + 1.1.1 + + + \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Main.kt b/core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Main.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Main.kt rename to core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Main.kt diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Node.kt b/core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Node.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Node.kt rename to core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Node.kt diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/binarytree/NodeTest.kt b/core-kotlin-modules/core-kotlin-datastructures/src/test/kotlin/com/binarytree/NodeTest.kt similarity index 99% rename from core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/binarytree/NodeTest.kt rename to core-kotlin-modules/core-kotlin-datastructures/src/test/kotlin/com/binarytree/NodeTest.kt index 9414d7dde9..5a7f7fc50f 100644 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/binarytree/NodeTest.kt +++ b/core-kotlin-modules/core-kotlin-datastructures/src/test/kotlin/com/binarytree/NodeTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.binarytree +package com.binarytree import org.junit.After import org.junit.Assert.assertEquals diff --git a/core-kotlin-modules/core-kotlin-date-time/README.md b/core-kotlin-modules/core-kotlin-date-time/README.md new file mode 100644 index 0000000000..a3e358d4e3 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-date-time/README.md @@ -0,0 +1,6 @@ +## Core Kotlin Date and Time + +This module contains articles about Kotlin core date/time features. + +### Relevant articles: +[Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates) diff --git a/core-kotlin-modules/core-kotlin-date-time/pom.xml b/core-kotlin-modules/core-kotlin-date-time/pom.xml new file mode 100644 index 0000000000..f3cacefc19 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-date-time/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + core-kotlin-date-time + core-kotlin-date-time + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${org.assertj.core.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + 1.1.1 + 3.9.0 + + + \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt rename to core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt rename to core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt rename to core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt rename to core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt rename to core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt rename to core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt rename to core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt rename to core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt rename to core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt rename to core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-design-patterns/README.md b/core-kotlin-modules/core-kotlin-design-patterns/README.md new file mode 100644 index 0000000000..4bdc164a47 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-design-patterns/README.md @@ -0,0 +1,6 @@ +## Core Kotlin Design Patterns + +This module contains articles about design patterns in Kotlin + +### Relevant articles: +- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) diff --git a/core-kotlin-modules/core-kotlin-design-patterns/pom.xml b/core-kotlin-modules/core-kotlin-design-patterns/pom.xml new file mode 100644 index 0000000000..c112602bc2 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-design-patterns/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + core-kotlin-design-patterns + core-kotlin-design-patterns + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + 1.1.1 + + + \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrder.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt rename to core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrder.kt diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt rename to core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt rename to core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/Main.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt rename to core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/Main.kt diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt rename to core-kotlin-modules/core-kotlin-design-patterns/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-lang-2/README.md b/core-kotlin-modules/core-kotlin-lang-2/README.md index e64a39cb9b..76d490226f 100644 --- a/core-kotlin-modules/core-kotlin-lang-2/README.md +++ b/core-kotlin-modules/core-kotlin-lang-2/README.md @@ -10,4 +10,5 @@ This module contains articles about core features in the Kotlin language. - [Initializing Arrays in Kotlin](https://www.baeldung.com/kotlin-initialize-array) - [Lazy Initialization in Kotlin](https://www.baeldung.com/kotlin-lazy-initialization) - [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety) +- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions) - [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang) diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-testing/README.md b/core-kotlin-modules/core-kotlin-testing/README.md new file mode 100644 index 0000000000..f4d89593a7 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-testing/README.md @@ -0,0 +1,6 @@ +## Core Kotlin Testing + +This module contains articles about testing in Kotlin + +### Relevant articles: +- [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-2/pom.xml b/core-kotlin-modules/core-kotlin-testing/pom.xml similarity index 64% rename from core-kotlin-modules/core-kotlin-2/pom.xml rename to core-kotlin-modules/core-kotlin-testing/pom.xml index ae6e2d175a..d38bc62409 100644 --- a/core-kotlin-modules/core-kotlin-2/pom.xml +++ b/core-kotlin-modules/core-kotlin-testing/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - core-kotlin-2 - core-kotlin-2 + core-kotlin-testing + core-kotlin-testing jar @@ -15,11 +15,15 @@ - org.assertj - assertj-core - ${assertj.version} + org.junit.platform + junit-platform-runner + ${junit.platform.version} test + + 1.1.1 + + \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/Calculator.kt b/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/Calculator.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/Calculator.kt rename to core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/Calculator.kt diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt b/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt rename to core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt b/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt rename to core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt b/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt rename to core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin/README.md b/core-kotlin-modules/core-kotlin/README.md index 90caccf5c8..48d19c987a 100644 --- a/core-kotlin-modules/core-kotlin/README.md +++ b/core-kotlin-modules/core-kotlin/README.md @@ -7,13 +7,5 @@ This module contains articles about Kotlin core features. - [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability) - [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number) - [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project) -- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort) -- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) -- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions) -- [Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree) -- [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin) -- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) -- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) -- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) -- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt) -- [[More --> ]](/core-kotlin-modules/core-kotlin-2) +- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-operator) +- [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences) diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/nullassertion/NotNullAssertionUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/nullassertion/NotNullAssertionUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/nullassertion/NotNullAssertionUnitTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/nullassertion/NotNullAssertionUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt similarity index 74% rename from core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt index 21dfdd2ae0..347290de72 100644 --- a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt @@ -21,4 +21,12 @@ class TernaryOperatorTest { } assertEquals("yes", result) } + + @Test + fun `using elvis`() { + val a: String? = null + val result = a ?: "Default" + + assertEquals("Default", result) + } } \ No newline at end of file diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml index de41aecf73..8b626e1c1b 100644 --- a/core-kotlin-modules/pom.xml +++ b/core-kotlin-modules/pom.xml @@ -18,17 +18,19 @@ core-kotlin - core-kotlin-2 core-kotlin-advanced core-kotlin-annotations core-kotlin-collections core-kotlin-concurrency + core-kotlin-date-time + core-kotlin-design-patterns core-kotlin-io core-kotlin-lang core-kotlin-lang-2 - core-kotlin-strings core-kotlin-lang-oop core-kotlin-lang-oop-2 + core-kotlin-strings + core-kotlin-testing diff --git a/data-structures/README.md b/data-structures/README.md index f9ca78679a..e3436695ce 100644 --- a/data-structures/README.md +++ b/data-structures/README.md @@ -10,3 +10,4 @@ This module contains articles about data structures in Java - [How to Print a Binary Tree Diagram](https://www.baeldung.com/java-print-binary-tree-diagram) - [Introduction to Big Queue](https://www.baeldung.com/java-big-queue) - [Guide to AVL Trees in Java](https://www.baeldung.com/java-avl-trees) +- [Graphs in Java](https://www.baeldung.com/java-graphs) diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java b/data-structures/src/main/java/com/baeldung/graph/Graph.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java rename to data-structures/src/main/java/com/baeldung/graph/Graph.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/graph/GraphTraversal.java b/data-structures/src/main/java/com/baeldung/graph/GraphTraversal.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/graph/GraphTraversal.java rename to data-structures/src/main/java/com/baeldung/graph/GraphTraversal.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphUnitTest.java b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphUnitTest.java rename to data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java diff --git a/ddd-modules/infrastructure/pom.xml b/ddd-modules/infrastructure/pom.xml index c301eaa92a..abf90935c3 100644 --- a/ddd-modules/infrastructure/pom.xml +++ b/ddd-modules/infrastructure/pom.xml @@ -12,8 +12,9 @@ com.baeldung.dddmodules - dddmodules + ddd-modules 1.0 + ../ diff --git a/ddd-modules/mainapp/pom.xml b/ddd-modules/mainapp/pom.xml index a048263d37..59d2ad7d3a 100644 --- a/ddd-modules/mainapp/pom.xml +++ b/ddd-modules/mainapp/pom.xml @@ -11,8 +11,9 @@ com.baeldung.dddmodules - dddmodules + ddd-modules 1.0 + ../ diff --git a/ddd-modules/ordercontext/pom.xml b/ddd-modules/ordercontext/pom.xml index abd166fb69..8dee3a5148 100644 --- a/ddd-modules/ordercontext/pom.xml +++ b/ddd-modules/ordercontext/pom.xml @@ -11,8 +11,9 @@ com.baeldung.dddmodules - dddmodules + ddd-modules 1.0 + ../ diff --git a/ddd-modules/pom.xml b/ddd-modules/pom.xml index c6dd6e1f25..6ab1829198 100644 --- a/ddd-modules/pom.xml +++ b/ddd-modules/pom.xml @@ -28,9 +28,15 @@ - junit - junit - ${junit.version} + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} test @@ -56,15 +62,31 @@ + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 0 + + + - 3.8.1 + UTF-8 + 9 9 - UTF-8 - 3.12.2 + + 3.8.1 + 2.22.2 + 1.0 + + 5.6.2 + 3.12.2 diff --git a/ddd-modules/sharedkernel/pom.xml b/ddd-modules/sharedkernel/pom.xml index a61f03a494..1afddf1e22 100644 --- a/ddd-modules/sharedkernel/pom.xml +++ b/ddd-modules/sharedkernel/pom.xml @@ -11,8 +11,9 @@ com.baeldung.dddmodules - dddmodules + ddd-modules 1.0 + ../ diff --git a/ddd-modules/shippingcontext/pom.xml b/ddd-modules/shippingcontext/pom.xml index 2096923f90..25b5882ef1 100644 --- a/ddd-modules/shippingcontext/pom.xml +++ b/ddd-modules/shippingcontext/pom.xml @@ -11,8 +11,9 @@ com.baeldung.dddmodules - dddmodules + ddd-modules 1.0 + ../ diff --git a/ddd/pom.xml b/ddd/pom.xml index 1253f2ac48..422f9ccd15 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -17,6 +17,35 @@ ../parent-boot-2 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + org.junit + junit-bom + ${junit-jupiter.version} + pom + import + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + org.springframework.boot @@ -26,24 +55,6 @@ org.springframework.boot spring-boot-starter-data-cassandra - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - - - org.junit.platform - junit-platform-launcher - ${junit-platform.version} - test - org.joda joda-money @@ -95,7 +106,10 @@ - 1.0.1 - + 2.22.2 + 1.0.1 + + 5.6.2 + diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt diff --git a/language-interop/README.md b/language-interop/README.md index 458f34a119..f4f2fc0816 100644 --- a/language-interop/README.md +++ b/language-interop/README.md @@ -5,3 +5,4 @@ This module contains articles about Java interop with other language integration ### Relevant Articles: - [How to Call Python From Java](https://www.baeldung.com/java-working-with-python) +- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) diff --git a/core-java-modules/core-java/src/main/resources/js/bind.js b/language-interop/src/main/resources/js/bind.js similarity index 100% rename from core-java-modules/core-java/src/main/resources/js/bind.js rename to language-interop/src/main/resources/js/bind.js diff --git a/core-java-modules/core-java/src/main/resources/js/locations.js b/language-interop/src/main/resources/js/locations.js similarity index 100% rename from core-java-modules/core-java/src/main/resources/js/locations.js rename to language-interop/src/main/resources/js/locations.js diff --git a/core-java-modules/core-java/src/main/resources/js/math_module.js b/language-interop/src/main/resources/js/math_module.js similarity index 100% rename from core-java-modules/core-java/src/main/resources/js/math_module.js rename to language-interop/src/main/resources/js/math_module.js diff --git a/core-java-modules/core-java/src/main/resources/js/no_such.js b/language-interop/src/main/resources/js/no_such.js similarity index 100% rename from core-java-modules/core-java/src/main/resources/js/no_such.js rename to language-interop/src/main/resources/js/no_such.js diff --git a/core-java-modules/core-java/src/main/resources/js/script.js b/language-interop/src/main/resources/js/script.js similarity index 100% rename from core-java-modules/core-java/src/main/resources/js/script.js rename to language-interop/src/main/resources/js/script.js diff --git a/core-java-modules/core-java/src/main/resources/js/trim.js b/language-interop/src/main/resources/js/trim.js similarity index 100% rename from core-java-modules/core-java/src/main/resources/js/trim.js rename to language-interop/src/main/resources/js/trim.js diff --git a/core-java-modules/core-java/src/main/resources/js/typed_arrays.js b/language-interop/src/main/resources/js/typed_arrays.js similarity index 100% rename from core-java-modules/core-java/src/main/resources/js/typed_arrays.js rename to language-interop/src/main/resources/js/typed_arrays.js diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java b/language-interop/src/test/java/com/baeldung/language/interop/javascript/NashornUnitTest.java similarity index 94% rename from core-java-modules/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java rename to language-interop/src/test/java/com/baeldung/language/interop/javascript/NashornUnitTest.java index 9abe8a927c..a9e4243f9d 100644 --- a/core-java-modules/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java +++ b/language-interop/src/test/java/com/baeldung/language/interop/javascript/NashornUnitTest.java @@ -1,14 +1,10 @@ -package com.baeldung.scripting; +package com.baeldung.language.interop.javascript; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import javax.script.Bindings; -import javax.script.Invocable; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; +import javax.script.*; import java.io.InputStreamReader; import java.util.List; import java.util.Map; diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index bdfb2c5ed6..2d27ec2107 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -153,6 +153,13 @@ renjin-script-engine ${renjin.version} + + org.apache.kafka + kafka-clients + ${kafka.version} + test + test + diff --git a/libraries-data-2/src/main/java/com/baeldung/kafka/producer/EvenOddPartitioner.java b/libraries-data-2/src/main/java/com/baeldung/kafka/producer/EvenOddPartitioner.java new file mode 100644 index 0000000000..1c77226037 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/kafka/producer/EvenOddPartitioner.java @@ -0,0 +1,17 @@ +package com.baeldung.kafka.producer; + +import org.apache.kafka.clients.producer.internals.DefaultPartitioner; +import org.apache.kafka.common.Cluster; + +public class EvenOddPartitioner extends DefaultPartitioner { + + @Override + public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { + + if (((String) key).length() % 2 == 0) { + return 0; + } + + return 1; + } +} diff --git a/libraries-data-2/src/main/java/com/baeldung/kafka/producer/KafkaProducer.java b/libraries-data-2/src/main/java/com/baeldung/kafka/producer/KafkaProducer.java new file mode 100644 index 0000000000..911c9ed3d7 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/kafka/producer/KafkaProducer.java @@ -0,0 +1,40 @@ +package com.baeldung.kafka.producer; + +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; + +import java.util.concurrent.Future; + +public class KafkaProducer { + + private final Producer producer; + + public KafkaProducer(Producer producer) { + this.producer = producer; + } + + public Future send(String key, String value) { + ProducerRecord record = new ProducerRecord("topic_sports_news", + key, value); + return producer.send(record); + } + + public void flush() { + producer.flush(); + } + + public void beginTransaction() { + producer.beginTransaction(); + } + + public void initTransaction() { + producer.initTransactions(); + } + + public void commitTransaction() { + producer.commitTransaction(); + } + + +} diff --git a/libraries-data-2/src/test/java/com/baeldung/kafka/producer/KafkaProducerUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/kafka/producer/KafkaProducerUnitTest.java new file mode 100644 index 0000000000..a7156ed886 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/kafka/producer/KafkaProducerUnitTest.java @@ -0,0 +1,116 @@ +package com.baeldung.kafka.producer; + +import com.baeldung.kafka.producer.EvenOddPartitioner; +import com.baeldung.kafka.producer.KafkaProducer; +import org.apache.kafka.clients.producer.MockProducer; +import org.apache.kafka.clients.producer.RecordMetadata; +import org.apache.kafka.common.Cluster; +import org.apache.kafka.common.Node; +import org.apache.kafka.common.PartitionInfo; +import org.apache.kafka.common.serialization.StringSerializer; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import static java.util.Collections.emptySet; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class KafkaProducerUnitTest { + + private final String TOPIC_NAME = "topic_sports_news"; + + private KafkaProducer kafkaProducer; + private MockProducer mockProducer; + + private void buildMockProducer(boolean autoComplete) { + this.mockProducer = new MockProducer<>(autoComplete, new StringSerializer(), new StringSerializer()); + } + + @Test + void givenKeyValue_whenSend_thenVerifyHistory() throws ExecutionException, InterruptedException { + + buildMockProducer(true); + //when + kafkaProducer = new KafkaProducer(mockProducer); + Future recordMetadataFuture = kafkaProducer.send("data", "{\"site\" : \"baeldung\"}"); + + //then + assertTrue(mockProducer.history().size() == 1); + assertTrue(mockProducer.history().get(0).key().equalsIgnoreCase("data")); + assertTrue(recordMetadataFuture.get().partition() == 0); + + } + + @Test + void givenKeyValue_whenSend_thenSendOnlyAfterFlush() { + + buildMockProducer(false); + //when + kafkaProducer = new KafkaProducer(mockProducer); + Future record = kafkaProducer.send("data", "{\"site\" : \"baeldung\"}"); + assertFalse(record.isDone()); + + //then + kafkaProducer.flush(); + assertTrue(record.isDone()); + } + + @Test + void givenKeyValue_whenSend_thenReturnException() { + + buildMockProducer(false); + //when + kafkaProducer = new KafkaProducer(mockProducer); + Future record = kafkaProducer.send("site", "{\"site\" : \"baeldung\"}"); + RuntimeException e = new RuntimeException(); + mockProducer.errorNext(e); + //then + try { + record.get(); + } catch (ExecutionException | InterruptedException ex) { + assertEquals(e, ex.getCause()); + } + assertTrue(record.isDone()); + } + + @Test + void givenKeyValue_whenSendWithTxn_thenSendOnlyOnTxnCommit() { + + buildMockProducer(true); + //when + kafkaProducer = new KafkaProducer(mockProducer); + kafkaProducer.initTransaction(); + kafkaProducer.beginTransaction(); + Future record = kafkaProducer.send("data", "{\"site\" : \"baeldung\"}"); + + //then + assertTrue(mockProducer.history().isEmpty()); + kafkaProducer.commitTransaction(); + assertTrue(mockProducer.history().size() == 1); + } + + @Test + void givenKeyValue_whenSendWithPartitioning_thenVerifyPartitionNumber() throws ExecutionException, InterruptedException { + + PartitionInfo partitionInfo0 = new PartitionInfo(TOPIC_NAME, 0, null, null, null); + PartitionInfo partitionInfo1 = new PartitionInfo(TOPIC_NAME, 1, null, null, null); + List list = new ArrayList<>(); + list.add(partitionInfo0); + list.add(partitionInfo1); + Cluster cluster = new Cluster("kafkab", new ArrayList(), list, emptySet(), emptySet()); + this.mockProducer = new MockProducer<>(cluster, true, new EvenOddPartitioner(), new StringSerializer(), new StringSerializer()); + //when + kafkaProducer = new KafkaProducer(mockProducer); + Future recordMetadataFuture = kafkaProducer.send("partition", "{\"site\" : \"baeldung\"}"); + + //then + assertTrue(recordMetadataFuture.get().partition() == 1); + + } + +} \ No newline at end of file diff --git a/maven-all/versions-maven-plugin/original/pom.xml b/maven-all/versions-maven-plugin/original/pom.xml index 54140aec9b..f81596661e 100644 --- a/maven-all/versions-maven-plugin/original/pom.xml +++ b/maven-all/versions-maven-plugin/original/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - versions-maven-plugin-example + original 0.0.1-SNAPSHOT diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index c7bb11b1d5..631d8a0581 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -32,6 +32,11 @@ io.rest-assured rest-assured + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + org.springframework.boot spring-boot-starter-test diff --git a/pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java b/pdf/src/main/java/com/baeldung/pdfthymeleaf/PDFThymeleafExample.java similarity index 97% rename from pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java rename to pdf/src/main/java/com/baeldung/pdfthymeleaf/PDFThymeleafExample.java index 2e1df1d320..28879b8958 100644 --- a/pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java +++ b/pdf/src/main/java/com/baeldung/pdfthymeleaf/PDFThymeleafExample.java @@ -1,4 +1,4 @@ -package com.baeldung.pdf; +package com.baeldung.pdfthymeleaf; import com.lowagie.text.DocumentException; import org.thymeleaf.TemplateEngine; diff --git a/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java b/pdf/src/test/java/com/baeldung/pdfthymeleaf/PDFThymeleafUnitTest.java similarity index 98% rename from pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java rename to pdf/src/test/java/com/baeldung/pdfthymeleaf/PDFThymeleafUnitTest.java index e253dce06c..75d38fbf22 100644 --- a/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java +++ b/pdf/src/test/java/com/baeldung/pdfthymeleaf/PDFThymeleafUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.pdf; +package com.baeldung.pdfthymeleaf; import com.lowagie.text.DocumentException; import org.junit.Test; diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml index 70ff8d6a87..b1de88e9ea 100644 --- a/persistence-modules/r2dbc/pom.xml +++ b/persistence-modules/r2dbc/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.examples.r2dbc - r2dbc-example + r2dbc 0.0.1-SNAPSHOT r2dbc Sample R2DBC Project diff --git a/persistence-modules/spring-boot-persistence-h2/pom.xml b/persistence-modules/spring-boot-persistence-h2/pom.xml index 7070b5e674..9e6c780931 100644 --- a/persistence-modules/spring-boot-persistence-h2/pom.xml +++ b/persistence-modules/spring-boot-persistence-h2/pom.xml @@ -40,11 +40,6 @@ db-util ${db-util.version} - - net.bytebuddy - byte-buddy - ${byte-buddy.version} - diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index c58e8dbf86..cc26ff58d5 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -77,7 +77,6 @@ UTF-8 2.23.0 2.0.1.Final - 2.1.7.RELEASE diff --git a/quarkus-extension/quarkus-liquibase/deployment/pom.xml b/quarkus-extension/quarkus-liquibase/deployment/pom.xml index 5c6b56e152..d7f1f995ff 100644 --- a/quarkus-extension/quarkus-liquibase/deployment/pom.xml +++ b/quarkus-extension/quarkus-liquibase/deployment/pom.xml @@ -8,7 +8,7 @@ com.baeldung.quarkus.liquibase - quarkus-liquibase-parent + quarkus-liquibase 1.0-SNAPSHOT diff --git a/quarkus-extension/quarkus-liquibase/pom.xml b/quarkus-extension/quarkus-liquibase/pom.xml index 8ed6555ed7..fdede2000e 100644 --- a/quarkus-extension/quarkus-liquibase/pom.xml +++ b/quarkus-extension/quarkus-liquibase/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.quarkus.liquibase - quarkus-liquibase-parent + quarkus-liquibase quarkus-liquibase pom diff --git a/quarkus-extension/quarkus-liquibase/runtime/pom.xml b/quarkus-extension/quarkus-liquibase/runtime/pom.xml index 760e6ab719..5d3b05ef92 100644 --- a/quarkus-extension/quarkus-liquibase/runtime/pom.xml +++ b/quarkus-extension/quarkus-liquibase/runtime/pom.xml @@ -7,7 +7,7 @@ com.baeldung.quarkus.liquibase - quarkus-liquibase-parent + quarkus-liquibase 1.0-SNAPSHOT diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 4b42528d0f..945ddef5e1 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -42,11 +42,6 @@ org.slf4j jcl-over-slf4j - - net.bytebuddy - byte-buddy - ${byte-buddy.version} - org.jetbrains.kotlin diff --git a/spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/CustomUserRepository.java b/spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/CustomUserRepository.java index 428c8bf532..effc750940 100644 --- a/spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/CustomUserRepository.java +++ b/spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/CustomUserRepository.java @@ -5,11 +5,18 @@ import java.util.Collection; import org.apache.commons.lang3.StringUtils; import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Repository; @Repository("userRepository") public class CustomUserRepository implements UserRepository { + private PasswordEncoder passwordEncoder; + + public CustomUserRepository(PasswordEncoder passwordEncoder) { + this.passwordEncoder = passwordEncoder; + } + @Override public User findUser(String username, String domain) { if (StringUtils.isAnyBlank(username, domain)) { @@ -17,7 +24,7 @@ public class CustomUserRepository implements UserRepository { } else { Collection authorities = new ArrayList<>(); User user = new User(username, domain, - "$2a$10$U3GhSMpsMSOE8Kqsbn58/edxDBKlVuYMh7qk/7ErApYFjJzi2VG5K", true, + passwordEncoder.encode("secret"), true, true, true, true, authorities); return user; } diff --git a/spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/SecurityConfig.java b/spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/SecurityConfig.java index def85ab978..88380f1ed6 100644 --- a/spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/SecurityConfig.java +++ b/spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/SecurityConfig.java @@ -1,6 +1,7 @@ package com.baeldung.loginextrafieldscustom; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; @@ -56,6 +57,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { return new SimpleUrlAuthenticationFailureHandler("/login?error=true"); } + @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } diff --git a/spring-5-security/src/main/java/com/baeldung/loginextrafieldssimple/SecurityConfig.java b/spring-5-security/src/main/java/com/baeldung/loginextrafieldssimple/SecurityConfig.java index d8c5ea8147..48ca53c0b2 100644 --- a/spring-5-security/src/main/java/com/baeldung/loginextrafieldssimple/SecurityConfig.java +++ b/spring-5-security/src/main/java/com/baeldung/loginextrafieldssimple/SecurityConfig.java @@ -1,6 +1,7 @@ package com.baeldung.loginextrafieldssimple; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; @@ -59,6 +60,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { return new SimpleUrlAuthenticationFailureHandler("/login?error=true"); } + @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } diff --git a/spring-5-security/src/main/java/com/baeldung/loginextrafieldssimple/SimpleUserRepository.java b/spring-5-security/src/main/java/com/baeldung/loginextrafieldssimple/SimpleUserRepository.java index e8aaa774a1..44929c6189 100644 --- a/spring-5-security/src/main/java/com/baeldung/loginextrafieldssimple/SimpleUserRepository.java +++ b/spring-5-security/src/main/java/com/baeldung/loginextrafieldssimple/SimpleUserRepository.java @@ -5,11 +5,18 @@ import java.util.Collection; import org.apache.commons.lang3.StringUtils; import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Repository; @Repository("userRepository") public class SimpleUserRepository implements UserRepository { + private PasswordEncoder passwordEncoder; + + public SimpleUserRepository(PasswordEncoder passwordEncoder) { + this.passwordEncoder = passwordEncoder; + } + @Override public User findUser(String username, String domain) { if (StringUtils.isAnyBlank(username, domain)) { @@ -17,7 +24,7 @@ public class SimpleUserRepository implements UserRepository { } else { Collection authorities = new ArrayList<>(); User user = new User(username, domain, - "$2a$10$U3GhSMpsMSOE8Kqsbn58/edxDBKlVuYMh7qk/7ErApYFjJzi2VG5K", true, + passwordEncoder.encode("secret"), true, true, true, true, authorities); return user; } diff --git a/spring-5-security/src/main/java/com/baeldung/securityprofile/Application.java b/spring-5-security/src/main/java/com/baeldung/securityprofile/Application.java new file mode 100644 index 0000000000..5f17227777 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/securityprofile/Application.java @@ -0,0 +1,14 @@ +package com.baeldung.securityprofile; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; + +@SpringBootApplication +@EnableWebSecurity +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/securityprofile/ApplicationNoSecurity.java b/spring-5-security/src/main/java/com/baeldung/securityprofile/ApplicationNoSecurity.java new file mode 100644 index 0000000000..c899eb9268 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/securityprofile/ApplicationNoSecurity.java @@ -0,0 +1,17 @@ +package com.baeldung.securityprofile; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@Profile("test") +public class ApplicationNoSecurity extends WebSecurityConfigurerAdapter { + + @Override + public void configure(WebSecurity web) { + web.ignoring().antMatchers("/**"); + } + +} diff --git a/spring-5-security/src/main/java/com/baeldung/securityprofile/ApplicationSecurity.java b/spring-5-security/src/main/java/com/baeldung/securityprofile/ApplicationSecurity.java new file mode 100644 index 0000000000..51a8d6aa11 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/securityprofile/ApplicationSecurity.java @@ -0,0 +1,16 @@ +package com.baeldung.securityprofile; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@Profile("prod") +public class ApplicationSecurity extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().authenticated(); + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/securityprofile/EmployeeController.java b/spring-5-security/src/main/java/com/baeldung/securityprofile/EmployeeController.java new file mode 100644 index 0000000000..a28a5129ca --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/securityprofile/EmployeeController.java @@ -0,0 +1,16 @@ +package com.baeldung.securityprofile; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Collections; +import java.util.List; + +@RestController +public class EmployeeController { + + @GetMapping("/employees") + public List getEmployees() { + return Collections.singletonList("Adam Johnson"); + } +} diff --git a/spring-5-security/src/test/java/com/baeldung/securityprofile/EmployeeControllerNoSecurityUnitTest.java b/spring-5-security/src/test/java/com/baeldung/securityprofile/EmployeeControllerNoSecurityUnitTest.java new file mode 100644 index 0000000000..7112392412 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/securityprofile/EmployeeControllerNoSecurityUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.securityprofile; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@WebMvcTest(value = EmployeeController.class) +@ActiveProfiles("test") +public class EmployeeControllerNoSecurityUnitTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenSecurityDisabled_shouldBeOk() throws Exception { + this.mockMvc.perform(get("/employees")) + .andExpect(status().isOk()); + } + +} \ No newline at end of file diff --git a/spring-5-security/src/test/java/com/baeldung/securityprofile/EmployeeControllerUnitTest.java b/spring-5-security/src/test/java/com/baeldung/securityprofile/EmployeeControllerUnitTest.java new file mode 100644 index 0000000000..b8c8b79eb5 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/securityprofile/EmployeeControllerUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.securityprofile; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@WebMvcTest(value = EmployeeController.class) +@ActiveProfiles("prod") +public class EmployeeControllerUnitTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenSecurityEnabled_shouldBeForbidden() throws Exception { + this.mockMvc.perform(get("/employees")) + .andExpect(status().isForbidden()); + } + +} \ No newline at end of file diff --git a/spring-boot-groovy/pom.xml b/spring-boot-groovy/pom.xml index f61398c5d6..9ea8d7b2a9 100644 --- a/spring-boot-groovy/pom.xml +++ b/spring-boot-groovy/pom.xml @@ -41,11 +41,6 @@ h2 runtime - - net.bytebuddy - byte-buddy-dep - 1.10.9 - diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index 8e917df2b7..68d4ec4b8f 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -41,10 +41,6 @@ org.springframework.boot spring-boot-starter-data-jpa - - net.bytebuddy - byte-buddy - org.springframework.boot diff --git a/spring-boot-modules/spring-boot-kotlin/pom.xml b/spring-boot-modules/spring-boot-kotlin/pom.xml index 79d62645da..7ee048546a 100644 --- a/spring-boot-modules/spring-boot-kotlin/pom.xml +++ b/spring-boot-modules/spring-boot-kotlin/pom.xml @@ -14,38 +14,6 @@ ../../parent-kotlin - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - org.jetbrains.kotlin @@ -142,9 +110,9 @@ 1.3.31 - 1.0.0.M1 - 1.0.0.M7 - 1.0.0.BUILD-SNAPSHOT + 1.0.0.RELEASE + 0.8.2.RELEASE + 0.8.4.RELEASE 1.2.1 diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt index 363090abac..464ed2773a 100644 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt +++ b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt @@ -2,12 +2,11 @@ package com.baeldung.nonblockingcoroutines.controller import com.baeldung.nonblockingcoroutines.model.Product import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred import kotlinx.coroutines.FlowPreview -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType.APPLICATION_JSON @@ -15,7 +14,6 @@ import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.awaitBody -import org.springframework.web.reactive.function.client.awaitExchange class ProductControllerCoroutines { @Autowired @@ -38,7 +36,7 @@ class ProductControllerCoroutines { webClient.get() .uri("/stock-service/product/$id/quantity") .accept(APPLICATION_JSON) - .awaitExchange().awaitBody() + .retrieve().awaitBody() } ProductStockView(product.await()!!, quantity.await()) } diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt index 41c4510e0d..e05b718e64 100644 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt +++ b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt @@ -12,7 +12,6 @@ import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.awaitBody -import org.springframework.web.reactive.function.client.awaitExchange import org.springframework.web.reactive.function.server.ServerRequest import org.springframework.web.reactive.function.server.ServerResponse import org.springframework.web.reactive.function.server.bodyAndAwait @@ -37,7 +36,7 @@ class ProductsHandler( webClient.get() .uri("/stock-service/product/$id/quantity") .accept(MediaType.APPLICATION_JSON) - .awaitExchange().awaitBody() + .retrieve().awaitBody() } return ServerResponse.ok().json().bodyAndAwait(ProductStockView(product.await()!!, quantity.await())) } diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt index 20c3827c26..64ffd014ad 100644 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt +++ b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt @@ -1,7 +1,7 @@ package com.baeldung.nonblockingcoroutines.repository import com.baeldung.nonblockingcoroutines.model.Product -import org.springframework.data.r2dbc.function.DatabaseClient +import org.springframework.data.r2dbc.core.DatabaseClient import org.springframework.stereotype.Repository import reactor.core.publisher.Flux import reactor.core.publisher.Mono @@ -10,7 +10,7 @@ import reactor.core.publisher.Mono class ProductRepository(private val client: DatabaseClient) { fun getProductById(id: Int): Mono { - return client.execute().sql("SELECT * FROM products WHERE id = $1") + return client.execute("SELECT * FROM products WHERE id = $1") .bind(0, id) .`as`(Product::class.java) .fetch() @@ -18,8 +18,7 @@ class ProductRepository(private val client: DatabaseClient) { } fun addNewProduct(name: String, price: Float): Mono { - return client.execute() - .sql("INSERT INTO products (name, price) VALUES($1, $2)") + return client.execute("INSERT INTO products (name, price) VALUES($1, $2)") .bind(0, name) .bind(1, price) .then() diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt index 60a19d4d00..f2667ec033 100644 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt +++ b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt @@ -6,14 +6,14 @@ import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactive.awaitFirstOrNull import kotlinx.coroutines.reactive.flow.asFlow -import org.springframework.data.r2dbc.function.DatabaseClient +import org.springframework.data.r2dbc.core.DatabaseClient import org.springframework.stereotype.Repository @Repository class ProductRepositoryCoroutines(private val client: DatabaseClient) { suspend fun getProductById(id: Int): Product? = - client.execute().sql("SELECT * FROM products WHERE id = $1") + client.execute("SELECT * FROM products WHERE id = $1") .bind(0, id) .`as`(Product::class.java) .fetch() @@ -21,8 +21,7 @@ class ProductRepositoryCoroutines(private val client: DatabaseClient) { .awaitFirstOrNull() suspend fun addNewProduct(name: String, price: Float) = - client.execute() - .sql("INSERT INTO products (name, price) VALUES($1, $2)") + client.execute("INSERT INTO products (name, price) VALUES($1, $2)") .bind(0, name) .bind(1, price) .then() diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/lists/ListsPropertiesUnitTest.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/lists/ListsPropertiesUnitTest.java new file mode 100644 index 0000000000..60ba4cc108 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/lists/ListsPropertiesUnitTest.java @@ -0,0 +1,88 @@ +package com.baeldung.properties.lists; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SpringListPropertiesApplication.class) +public class ListsPropertiesUnitTest { + + @Value("${arrayOfStrings}") + private String[] arrayOfStrings; + + @Value("${arrayOfStrings}") + private List unexpectedListOfStrings; + + @Value("#{'${arrayOfStrings}'.split(',')}") + private List listOfStrings; + + @Value("#{${listOfStrings}}") + private List listOfStringsV2; + + @Value("#{'${listOfStringsWithCustomDelimiter}'.split(';')}") + private List listOfStringsWithCustomDelimiter; + + @Value("#{'${listOfBooleans}'.split(',')}") + private List listOfBooleans; + + @Value("#{'${listOfIntegers}'.split(',')}") + private List listOfIntegers; + + @Value("#{'${listOfCharacters}'.split(',')}") + private List listOfCharacters; + + @Autowired + private Environment environment; + + @Test + public void whenContextIsInitialized_thenInjectedArrayContainsExpectedValues() { + assertEquals(new String[] {"Baeldung", "dot", "com"}, arrayOfStrings); + } + + @Test + public void whenContextIsInitialized_thenInjectedListContainsUnexpectedValues() { + assertEquals(Collections.singletonList("Baeldung,dot,com"), unexpectedListOfStrings); + } + + @Test + public void whenContextIsInitialized_thenInjectedListContainsExpectedValues() { + assertEquals(Arrays.asList("Baeldung", "dot", "com"), listOfStrings); + } + + @Test + public void whenContextIsInitialized_thenInjectedListV2ContainsExpectedValues() { + assertEquals(Arrays.asList("Baeldung", "dot", "com"), listOfStringsV2); + } + + @Test + public void whenContextIsInitialized_thenInjectedListWithCustomDelimiterContainsExpectedValues() { + assertEquals(Arrays.asList("Baeldung", "dot", "com"), listOfStringsWithCustomDelimiter); + } + + @Test + public void whenContextIsInitialized_thenInjectedListOfBasicTypesContainsExpectedValues() { + assertEquals(Arrays.asList(false, false, true), listOfBooleans); + assertEquals(Arrays.asList(1, 2, 3, 4), listOfIntegers); + assertEquals(Arrays.asList('a', 'b', 'c'), listOfCharacters); + } + + @Test + public void whenReadingFromSpringEnvironment_thenPropertiesHaveExpectedValues() { + String[] arrayOfStrings = environment.getProperty("arrayOfStrings", String[].class); + List listOfStrings = (List)environment.getProperty("arrayOfStrings", List.class); + + assertEquals(new String[] {"Baeldung", "dot", "com"}, arrayOfStrings); + assertEquals(Arrays.asList("Baeldung", "dot", "com"), listOfStrings); + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/lists/SpringListPropertiesApplication.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/lists/SpringListPropertiesApplication.java new file mode 100644 index 0000000000..8a66079201 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/lists/SpringListPropertiesApplication.java @@ -0,0 +1,10 @@ +package com.baeldung.properties.lists; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +@Configuration +@PropertySource(value = "lists.properties") +public class SpringListPropertiesApplication { + +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/resources/lists.properties b/spring-boot-modules/spring-boot-properties-2/src/test/resources/lists.properties new file mode 100644 index 0000000000..cc54d699a7 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/resources/lists.properties @@ -0,0 +1,6 @@ +arrayOfStrings=Baeldung,dot,com +listOfStrings={'Baeldung','dot','com'} +listOfStringsWithCustomDelimiter=Baeldung;dot;com +listOfBooleans=false,false,true +listOfIntegers=1,2,3,4 +listOfCharacters=a,b,c \ No newline at end of file diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index a8500d50f2..10dacf99e8 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -79,11 +79,6 @@ modelmapper ${modelmapper.version} - - net.bytebuddy - byte-buddy - ${byte-buddy.version} - diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 3de527c33b..6fddb1693f 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -40,6 +40,7 @@ spring-cloud-task spring-cloud-zuul spring-cloud-zuul-fallback + spring-cloud-ribbon-retry diff --git a/spring-cloud/spring-cloud-connectors-heroku/pom.xml b/spring-cloud/spring-cloud-connectors-heroku/pom.xml index 1dad3ddcb7..c09a282197 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/pom.xml +++ b/spring-cloud/spring-cloud-connectors-heroku/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -35,6 +35,11 @@ org.postgresql postgresql + + net.bytebuddy + byte-buddy-dep + ${bytebuddy.version} + com.h2database h2 @@ -55,8 +60,9 @@ - Brixton.SR7 - 9.4-1201-jdbc4 + Hoxton.SR4 + 42.2.10 + 1.10.10 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/book/BookController.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/book/BookController.java index eb2972f35a..f998059028 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/book/BookController.java +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/book/BookController.java @@ -1,5 +1,7 @@ package com.baeldung.spring.cloud.connectors.heroku.book; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -15,7 +17,7 @@ public class BookController { } @GetMapping("/{bookId}") - public Book findBook(@PathVariable Long bookId) { + public Optional findBook(@PathVariable Long bookId) { return bookService.findBookById(bookId); } diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/book/BookService.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/book/BookService.java index 4978ded65f..a83dfe64b7 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/book/BookService.java +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/book/BookService.java @@ -1,5 +1,7 @@ package com.baeldung.spring.cloud.connectors.heroku.book; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; @@ -15,8 +17,8 @@ public class BookService { this.bookRepository = bookRepository; } - public Book findBookById(Long bookId) { - return bookRepository.findOne(bookId); + public Optional findBookById(Long bookId) { + return bookRepository.findById(bookId); } @Transactional(propagation = Propagation.REQUIRED) diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java index 51cf4412bf..7875c712f9 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java @@ -1,5 +1,7 @@ package com.baeldung.spring.cloud.connectors.heroku.product; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -15,7 +17,7 @@ public class ProductController { } @GetMapping("/{productId}") - public Product findProduct(@PathVariable Long productId) { + public Optional findProduct(@PathVariable Long productId) { return productService.findProductById(productId); } diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java index f25b4ecf7b..bdd13e9863 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java @@ -1,5 +1,7 @@ package com.baeldung.spring.cloud.connectors.heroku.product; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; @@ -15,8 +17,8 @@ public class ProductService { this.productRepository = productRepository; } - public Product findProductById(Long productId) { - return productRepository.findOne(productId); + public Optional findProductById(Long productId) { + return productRepository.findById(productId); } @Transactional(propagation = Propagation.REQUIRED) diff --git a/spring-cloud/spring-cloud-ribbon-retry/pom.xml b/spring-cloud/spring-cloud-ribbon-retry/pom.xml new file mode 100644 index 0000000000..5318ea6913 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-ribbon-retry + 0.0.1-SNAPSHOT + spring-cloud-ribbon-retry + pom + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + ribbon-client-service + ribbon-weather-service + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud.version} + pom + import + + + + + + Hoxton.SR3 + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/pom.xml b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/pom.xml new file mode 100644 index 0000000000..ad47eb6c84 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + ribbon-client-service + + + com.baeldung.spring.cloud + spring-cloud-ribbon-retry + 0.0.1-SNAPSHOT + + + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.retry + spring-retry + + + com.baeldung.spring.cloud + ribbon-weather-service + 0.0.1-SNAPSHOT + test + + + + + Hoxton.SR3 + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/RibbonClientApp.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/RibbonClientApp.java new file mode 100644 index 0000000000..e06d4a93a1 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/RibbonClientApp.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.ribbon.retry; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RibbonClientApp { + + public static void main(String[] args) { + SpringApplication.run(RibbonClientApp.class, args); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/backoff/ExponentialBackoffRetryFactory.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/backoff/ExponentialBackoffRetryFactory.java new file mode 100644 index 0000000000..c70ee71b7d --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/backoff/ExponentialBackoffRetryFactory.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.cloud.ribbon.retry.backoff; + +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryFactory; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.retry.backoff.BackOffPolicy; +import org.springframework.retry.backoff.ExponentialBackOffPolicy; +import org.springframework.stereotype.Component; + +@Component +@Profile("exponential-backoff") +class ExponentialBackoffRetryFactory extends RibbonLoadBalancedRetryFactory { + + public ExponentialBackoffRetryFactory(SpringClientFactory clientFactory) { + super(clientFactory); + } + + @Override + public BackOffPolicy createBackOffPolicy(String service) { + ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy(); + exponentialBackOffPolicy.setInitialInterval(1000); + exponentialBackOffPolicy.setMultiplier(2); + exponentialBackOffPolicy.setMaxInterval(10000); + return exponentialBackOffPolicy; + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/backoff/ExponentialRandomBackoffRetryFactory.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/backoff/ExponentialRandomBackoffRetryFactory.java new file mode 100644 index 0000000000..c1fad4d1a0 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/backoff/ExponentialRandomBackoffRetryFactory.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.cloud.ribbon.retry.backoff; + +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryFactory; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.retry.backoff.BackOffPolicy; +import org.springframework.retry.backoff.ExponentialRandomBackOffPolicy; +import org.springframework.stereotype.Component; + +@Component +@Profile("exponential-random-backoff") +class ExponentialRandomBackoffRetryFactory extends RibbonLoadBalancedRetryFactory { + + public ExponentialRandomBackoffRetryFactory(SpringClientFactory clientFactory) { + super(clientFactory); + } + + @Override + public BackOffPolicy createBackOffPolicy(String service) { + ExponentialRandomBackOffPolicy exponentialRandomBackOffPolicy = new ExponentialRandomBackOffPolicy(); + exponentialRandomBackOffPolicy.setInitialInterval(1000); + exponentialRandomBackOffPolicy.setMultiplier(2); + exponentialRandomBackOffPolicy.setMaxInterval(10000); + return exponentialRandomBackOffPolicy; + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/backoff/FixedBackoffRetryFactory.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/backoff/FixedBackoffRetryFactory.java new file mode 100644 index 0000000000..6dab5d15b4 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/backoff/FixedBackoffRetryFactory.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.cloud.ribbon.retry.backoff; + +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryFactory; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.retry.backoff.BackOffPolicy; +import org.springframework.retry.backoff.FixedBackOffPolicy; +import org.springframework.stereotype.Component; + +@Component +@Profile("fixed-backoff") +class FixedBackoffRetryFactory extends RibbonLoadBalancedRetryFactory { + + public FixedBackoffRetryFactory(SpringClientFactory clientFactory) { + super(clientFactory); + } + + @Override + public BackOffPolicy createBackOffPolicy(String service) { + FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy(); + fixedBackOffPolicy.setBackOffPeriod(2000); + return fixedBackOffPolicy; + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/config/RibbonConfiguration.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/config/RibbonConfiguration.java new file mode 100644 index 0000000000..c493b4dbe2 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/config/RibbonConfiguration.java @@ -0,0 +1,20 @@ +package com.baeldung.spring.cloud.ribbon.retry.config; + +import com.netflix.loadbalancer.IPing; +import com.netflix.loadbalancer.IRule; +import com.netflix.loadbalancer.PingUrl; +import com.netflix.loadbalancer.WeightedResponseTimeRule; +import org.springframework.context.annotation.Bean; + +public class RibbonConfiguration { + + @Bean + public IPing ribbonPing() { + return new PingUrl(); + } + + @Bean + public IRule ribbonRule() { + return new WeightedResponseTimeRule(); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/config/WeatherClientRibbonConfiguration.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/config/WeatherClientRibbonConfiguration.java new file mode 100644 index 0000000000..88955db025 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/config/WeatherClientRibbonConfiguration.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.cloud.ribbon.retry.config; + +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.cloud.netflix.ribbon.RibbonClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +@RibbonClient(name = "weather-service", configuration = RibbonConfiguration.class) +public class WeatherClientRibbonConfiguration { + + @LoadBalanced + @Bean + RestTemplate getRestTemplate() { + return new RestTemplate(); + } + +} diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/controller/RibbonClientController.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/controller/RibbonClientController.java new file mode 100644 index 0000000000..ebe5b58386 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/controller/RibbonClientController.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.cloud.ribbon.retry.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +@RestController +public class RibbonClientController { + + private static final String WEATHER_SERVICE = "weather-service"; + + @Autowired + private RestTemplate restTemplate; + + @GetMapping("/client/weather") + public String weather() { + String result = restTemplate.getForObject("http://" + WEATHER_SERVICE + "/weather", String.class); + return "Weather Service Response: " + result; + } +} diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml new file mode 100644 index 0000000000..3199f38dce --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml @@ -0,0 +1,17 @@ +spring: + profiles: + # fixed-backoff, exponential-backoff, exponential-random-backoff + active: fixed-backoff + application: + name: ribbon-client + +weather-service: + ribbon: + eureka: + enabled: false + listOfServers: http://localhost:8081, http://localhost:8082 + ServerListRefreshInterval: 5000 + MaxAutoRetries: 3 + MaxAutoRetriesNextServer: 1 + OkToRetryOnAllOperations: true + retryableStatusCodes: 503, 408 diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java new file mode 100644 index 0000000000..0e72bdbb86 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java @@ -0,0 +1,50 @@ +package com.baeldung.spring.cloud.ribbon.retry; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.http.ResponseEntity; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RibbonClientApp.class) +public class RibbonRetryFailureIntegrationTest { + + private static ConfigurableApplicationContext weatherServiceInstance1; + private static ConfigurableApplicationContext weatherServiceInstance2; + + @LocalServerPort + private int port; + private TestRestTemplate restTemplate = new TestRestTemplate(); + + @BeforeAll + public static void setup() { + weatherServiceInstance1 = startApp(8081); + weatherServiceInstance2 = startApp(8082); + } + + @AfterAll + public static void cleanup() { + weatherServiceInstance1.close(); + weatherServiceInstance2.close(); + } + + private static ConfigurableApplicationContext startApp(int port) { + return SpringApplication.run(RibbonWeatherServiceApp.class, "--server.port=" + port, "--successful.call.divisor=6"); + } + + @Test + public void whenRibbonClientIsCalledAndServiceUnavailable_thenFailure() { + String url = "http://localhost:" + port + "/client/weather"; + + ResponseEntity response = restTemplate.getForEntity(url, String.class); + + assertTrue(response.getStatusCode().is5xxServerError()); + } + +} diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java new file mode 100644 index 0000000000..2055159117 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.ribbon.retry; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.http.ResponseEntity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RibbonClientApp.class) +public class RibbonRetrySuccessIntegrationTest { + + private static ConfigurableApplicationContext weatherServiceInstance1; + private static ConfigurableApplicationContext weatherServiceInstance2; + + @LocalServerPort + private int port; + private TestRestTemplate restTemplate = new TestRestTemplate(); + + @BeforeAll + public static void setup() { + weatherServiceInstance1 = startApp(8081); + weatherServiceInstance2 = startApp(8082); + } + + private static ConfigurableApplicationContext startApp(int port) { + return SpringApplication.run(RibbonWeatherServiceApp.class, "--server.port=" + port, "--successful.call.divisor=3"); + } + + @AfterAll + public static void cleanup() { + weatherServiceInstance1.close(); + weatherServiceInstance2.close(); + } + + @Test + public void whenRibbonClientIsCalledAndServiceAvailable_thenSuccess() { + String url = "http://localhost:" + port + "/client/weather"; + + ResponseEntity response = restTemplate.getForEntity(url, String.class); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals(response.getBody(), "Weather Service Response: Today's a sunny day"); + } + +} diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/pom.xml b/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/pom.xml new file mode 100644 index 0000000000..f091341025 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + ribbon-weather-service + + + com.baeldung.spring.cloud + spring-cloud-ribbon-retry + 0.0.1-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/RibbonWeatherServiceApp.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/RibbonWeatherServiceApp.java new file mode 100644 index 0000000000..ceeacbd426 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/RibbonWeatherServiceApp.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.ribbon.retry; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RibbonWeatherServiceApp { + + public static void main(String[] args) { + SpringApplication.run(RibbonWeatherServiceApp.class, args); + } +} diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/WeatherController.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/WeatherController.java new file mode 100644 index 0000000000..ec0b94e505 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/src/main/java/com/baeldung/spring/cloud/ribbon/retry/WeatherController.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.cloud.ribbon.retry; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class WeatherController { + + private static final Logger LOGGER = LoggerFactory.getLogger(WeatherController.class); + + private int nrOfCalls = 0; + + @Value("${successful.call.divisor}") + private int divisor; + + @GetMapping("/") + public String health() { + return "I am Ok"; + } + + @GetMapping("/weather") + public ResponseEntity weather() { + LOGGER.info("Providing today's weather information"); + if (isServiceUnavailable()) { + return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE); + } + LOGGER.info("Today's a sunny day"); + return new ResponseEntity<>("Today's a sunny day", HttpStatus.OK); + } + + private boolean isServiceUnavailable() { + return ++nrOfCalls % divisor != 0; + } +} diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/src/main/resources/application.properties b/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/src/main/resources/application.properties new file mode 100644 index 0000000000..ea25e8f2da --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-weather-service/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.application.name=weather-service +successful.call.divisor=3 diff --git a/spring-cloud/spring-cloud-task/pom.xml b/spring-cloud/spring-cloud-task/pom.xml index 377d16a999..e2006ee9d3 100644 --- a/spring-cloud/spring-cloud-task/pom.xml +++ b/spring-cloud/spring-cloud-task/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -40,8 +40,8 @@ - Brixton.SR7 - 1.2.2.RELEASE + Hoxton.SR4 + 2.2.3.RELEASE diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml index fd10322efb..4e6b8b8b6c 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -45,6 +45,13 @@ org.springframework.cloud spring-cloud-task-batch + + + net.bytebuddy + byte-buddy-dep + ${bytebuddy.version} + + com.h2database h2 @@ -63,6 +70,7 @@ com.baeldung.TaskDemo + 1.10.10 diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/resources/application.yml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/resources/application.yml index 794ac4d247..8a6e4fc172 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/resources/application.yml +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/resources/application.yml @@ -1,6 +1,6 @@ spring: datasource: - url: jdbc:h2:mem:springcloud + url: jdbc:h2:mem:springcloud;DB_CLOSE_ON_EXIT=FALSE username: sa password: jpa: diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml index 93255959e4..33f6ccde74 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml @@ -50,8 +50,7 @@ - 1.2.2.RELEASE - 1.3.0.RELEASE + 2.3.1.RELEASE diff --git a/spring-core-4/README.md b/spring-core-4/README.md index 592f4cd011..11a966f23d 100644 --- a/spring-core-4/README.md +++ b/spring-core-4/README.md @@ -6,4 +6,5 @@ This module contains articles about core Spring functionality - [Creating Spring Beans Through Factory Methods](https://www.baeldung.com/spring-beans-factory-methods) - [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) - More articles: [[<-- prev]](/spring-core-3) diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/AnimalConfiguration.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/AnimalConfiguration.java new file mode 100644 index 0000000000..94f22788b8 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/AnimalConfiguration.java @@ -0,0 +1,9 @@ +package com.baeldung.importannotation.animal; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +@Configuration +@Import({ MammalConfiguration.class, BirdConfig.class }) +class AnimalConfiguration { +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/AnimalScanConfiguration.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/AnimalScanConfiguration.java new file mode 100644 index 0000000000..9b4310b6d3 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/AnimalScanConfiguration.java @@ -0,0 +1,9 @@ +package com.baeldung.importannotation.animal; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan +public class AnimalScanConfiguration { +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Bird.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Bird.java new file mode 100644 index 0000000000..a785cf7641 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Bird.java @@ -0,0 +1,4 @@ +package com.baeldung.importannotation.animal; + +class Bird { +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/BirdConfig.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/BirdConfig.java new file mode 100644 index 0000000000..c5cefe8b22 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/BirdConfig.java @@ -0,0 +1,13 @@ +package com.baeldung.importannotation.animal; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +class BirdConfig { + + @Bean + Bird bird() { + return new Bird(); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Bug.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Bug.java new file mode 100644 index 0000000000..6abe08e393 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Bug.java @@ -0,0 +1,7 @@ +package com.baeldung.importannotation.animal; + +import org.springframework.stereotype.Component; + +@Component(value = "bug") +class Bug { +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/BugConfig.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/BugConfig.java new file mode 100644 index 0000000000..9bea16413a --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/BugConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.importannotation.animal; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +@Configuration +@Import(Bug.class) +class BugConfig { +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Cat.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Cat.java new file mode 100644 index 0000000000..7eb36c81ce --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Cat.java @@ -0,0 +1,4 @@ +package com.baeldung.importannotation.animal; + +class Cat { +} \ No newline at end of file diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/CatConfig.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/CatConfig.java new file mode 100644 index 0000000000..ebb35ffc11 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/CatConfig.java @@ -0,0 +1,13 @@ +package com.baeldung.importannotation.animal; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +class CatConfig { + + @Bean + Cat cat() { + return new Cat(); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Dog.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Dog.java new file mode 100644 index 0000000000..00374c1bc0 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/Dog.java @@ -0,0 +1,4 @@ +package com.baeldung.importannotation.animal; + +class Dog { +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/DogConfig.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/DogConfig.java new file mode 100644 index 0000000000..c11ee44623 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/DogConfig.java @@ -0,0 +1,13 @@ +package com.baeldung.importannotation.animal; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +class DogConfig { + + @Bean + Dog dog() { + return new Dog(); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/animal/MammalConfiguration.java b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/MammalConfiguration.java new file mode 100644 index 0000000000..3d77ac878c --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/animal/MammalConfiguration.java @@ -0,0 +1,9 @@ +package com.baeldung.importannotation.animal; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +@Configuration +@Import({ DogConfig.class, CatConfig.class }) +class MammalConfiguration { +} diff --git a/spring-core-4/src/main/java/com/baeldung/importannotation/zoo/ZooApplication.java b/spring-core-4/src/main/java/com/baeldung/importannotation/zoo/ZooApplication.java new file mode 100644 index 0000000000..01aa36a796 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/importannotation/zoo/ZooApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.importannotation.zoo; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +import com.baeldung.importannotation.animal.AnimalScanConfiguration; + +@Configuration +@Import(AnimalScanConfiguration.class) +class ZooApplication { +} diff --git a/spring-core-4/src/test/java/com/baeldung/importannotation/animal/AnimalConfigUnitTest.java b/spring-core-4/src/test/java/com/baeldung/importannotation/animal/AnimalConfigUnitTest.java new file mode 100644 index 0000000000..7f4795da25 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/importannotation/animal/AnimalConfigUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.importannotation.animal; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { AnimalConfiguration.class }) +class AnimalConfigUnitTest { + + @Autowired + ApplicationContext context; + + @Test + void givenImportedBeans_whenGettingEach_shallFindOnlyTheImportedBeans() { + assertThatBeanExists("dog", Dog.class); + assertThatBeanExists("cat", Cat.class); + assertThatBeanExists("bird", Cat.class); + } + + private void assertThatBeanExists(String beanName, Class beanClass) { + assertTrue(context.containsBean(beanName)); + assertNotNull(context.getBean(beanClass)); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/importannotation/animal/BugConfigUnitTest.java b/spring-core-4/src/test/java/com/baeldung/importannotation/animal/BugConfigUnitTest.java new file mode 100644 index 0000000000..2a2e0b332a --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/importannotation/animal/BugConfigUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.importannotation.animal; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = BugConfig.class) +class BugConfigUnitTest { + + @Autowired + ApplicationContext context; + + @Test + void givenImportInComponent_whenLookForBean_shallFindIt() { + assertTrue(context.containsBean("bug")); + assertNotNull(context.getBean(Bug.class)); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/importannotation/animal/ConfigUnitTest.java b/spring-core-4/src/test/java/com/baeldung/importannotation/animal/ConfigUnitTest.java new file mode 100644 index 0000000000..dadd2abae6 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/importannotation/animal/ConfigUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.importannotation.animal; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { BirdConfig.class, CatConfig.class, DogConfig.class }) +class ConfigUnitTest { + + @Autowired + ApplicationContext context; + + @Test + void givenImportedBeans_whenGettingEach_shallFindIt() { + assertThatBeanExists("dog", Dog.class); + assertThatBeanExists("cat", Cat.class); + assertThatBeanExists("bird", Bird.class); + } + + private void assertThatBeanExists(String beanName, Class beanClass) { + assertTrue(context.containsBean(beanName)); + assertNotNull(context.getBean(beanClass)); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/importannotation/animal/MammalConfigUnitTest.java b/spring-core-4/src/test/java/com/baeldung/importannotation/animal/MammalConfigUnitTest.java new file mode 100644 index 0000000000..5e1596253c --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/importannotation/animal/MammalConfigUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.importannotation.animal; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { MammalConfiguration.class }) +class MammalConfigUnitTest { + + @Autowired + ApplicationContext context; + + @Test + void givenImportedBeans_whenGettingEach_shallFindOnlyTheImportedBeans() { + assertThatBeanExists("dog", Dog.class); + assertThatBeanExists("cat", Cat.class); + + assertFalse(context.containsBean("bird")); + } + + private void assertThatBeanExists(String beanName, Class beanClass) { + assertTrue(context.containsBean(beanName)); + assertNotNull(context.getBean(beanClass)); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/importannotation/zoo/ZooApplicationUnitTest.java b/spring-core-4/src/test/java/com/baeldung/importannotation/zoo/ZooApplicationUnitTest.java new file mode 100644 index 0000000000..e832e27b28 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/importannotation/zoo/ZooApplicationUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.importannotation.zoo; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = ZooApplication.class) +class ZooApplicationUnitTest { + + @Autowired + ApplicationContext context; + + @Test + void givenTheScanInTheAnimalPackage_whenGettingAnyAnimal_shallFindItInTheContext() { + assertNotNull(context.getBean("dog")); + assertNotNull(context.getBean("bird")); + assertNotNull(context.getBean("cat")); + assertNotNull(context.getBean("bug")); + } +} diff --git a/spring-jinq/pom.xml b/spring-jinq/pom.xml index 073808823c..647c0907a7 100644 --- a/spring-jinq/pom.xml +++ b/spring-jinq/pom.xml @@ -37,12 +37,6 @@ spring-boot-starter-data-jpa - - net.bytebuddy - byte-buddy-dep - ${bytebuddy.version} - - org.springframework @@ -73,7 +67,6 @@ 1.8.29 - 1.10.10 diff --git a/spring-rest-hal-browser/pom.xml b/spring-rest-hal-browser/pom.xml index 32a0b52875..7b629dba44 100644 --- a/spring-rest-hal-browser/pom.xml +++ b/spring-rest-hal-browser/pom.xml @@ -35,11 +35,6 @@ com.h2database h2 - - net.bytebuddy - byte-buddy-dep - ${bytebuddy.version} - @@ -56,7 +51,6 @@ - 1.10.10 1.8 1.8 diff --git a/spring-rest-http/README.md b/spring-rest-http/README.md index 35793cb281..f78f8784b0 100644 --- a/spring-rest-http/README.md +++ b/spring-rest-http/README.md @@ -13,3 +13,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring RequestMapping](https://www.baeldung.com/spring-requestmapping) - [Guide to DeferredResult in Spring](https://www.baeldung.com/spring-deferred-result) - [Using JSON Patch in Spring REST APIs](https://www.baeldung.com/spring-rest-json-patch) +- [Using OpenAPI and JSON Request Parameters](https://www.baeldung.com/openapi-json-query-parameters) diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 60a662781f..954b9335e4 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -20,7 +20,6 @@ spring-security-cache-control spring-security-core spring-security-cors - spring-security-kerberos spring-security-mvc spring-security-mvc-boot-1 spring-security-mvc-boot-2 diff --git a/spring-security-modules/spring-security-kerberos/README.md b/spring-security-modules/spring-security-kerberos/README.md deleted file mode 100644 index a868fb86b7..0000000000 --- a/spring-security-modules/spring-security-kerberos/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## Spring Security Kerberos - -This module contains articles about Spring Security Kerberos - -### Relevant Articles: - -- [Introduction to SPNEGO/Kerberos Authentication in Spring](https://www.baeldung.com/spring-security-kerberos) - -### @PreFilter and @PostFilter annotations - -### Build the Project ### - -`mvn clean install` \ No newline at end of file diff --git a/spring-security-modules/spring-security-kerberos/pom.xml b/spring-security-modules/spring-security-kerberos/pom.xml deleted file mode 100644 index 51a48a78c6..0000000000 --- a/spring-security-modules/spring-security-kerberos/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - 4.0.0 - spring-security-kerberos - 0.1-SNAPSHOT - spring-security-kerberos - war - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-security - - - - org.springframework.security.kerberos - spring-security-kerberos-core - ${spring-security-kerberos.version} - - - org.springframework.security.kerberos - spring-security-kerberos-web - ${spring-security-kerberos.version} - - - org.springframework.security.kerberos - spring-security-kerberos-client - ${spring-security-kerberos.version} - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - - - - - org.apache.maven.plugins - maven-war-plugin - - - - - - 1.0.1.RELEASE - - - diff --git a/spring-security-modules/spring-security-mvc-boot-1/pom.xml b/spring-security-modules/spring-security-mvc-boot-1/pom.xml index b00b7bab32..7ad18376ec 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/pom.xml +++ b/spring-security-modules/spring-security-mvc-boot-1/pom.xml @@ -106,10 +106,6 @@ ${ehcache-core.version} jar - - net.bytebuddy - byte-buddy - diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md index 3aa092edb8..4bb0eea16c 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md +++ b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Spring Security Kerberos Integration](https://www.baeldung.com/spring-security-kerberos-integration) +- [Introduction to SPNEGO/Kerberos Authentication in Spring](https://www.baeldung.com/spring-security-kerberos) diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/Application.java b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/src/main/java/com/baeldung/intro/Application.java similarity index 90% rename from spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/Application.java rename to spring-security-modules/spring-security-sso/spring-security-sso-kerberos/src/main/java/com/baeldung/intro/Application.java index 37dbe7dab8..2cddbf0f22 100644 --- a/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/Application.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/src/main/java/com/baeldung/intro/Application.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.intro; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/config/WebSecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/src/main/java/com/baeldung/intro/config/WebSecurityConfig.java similarity index 97% rename from spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/config/WebSecurityConfig.java rename to spring-security-modules/spring-security-sso/spring-security-sso-kerberos/src/main/java/com/baeldung/intro/config/WebSecurityConfig.java index c1c206e5c9..cc694a3b83 100644 --- a/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/config/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/src/main/java/com/baeldung/intro/config/WebSecurityConfig.java @@ -1,6 +1,5 @@ -package com.baeldung.config; +package com.baeldung.intro.config; -import com.baeldung.security.DummyUserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.FileSystemResource; @@ -16,6 +15,8 @@ import org.springframework.security.kerberos.web.authentication.SpnegoAuthentica import org.springframework.security.kerberos.web.authentication.SpnegoEntryPoint; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; +import com.baeldung.intro.security.DummyUserDetailsService; + @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/security/DummyUserDetailsService.java b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/src/main/java/com/baeldung/intro/security/DummyUserDetailsService.java similarity index 94% rename from spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/security/DummyUserDetailsService.java rename to spring-security-modules/spring-security-sso/spring-security-sso-kerberos/src/main/java/com/baeldung/intro/security/DummyUserDetailsService.java index 6ddd6c8969..f564c9f756 100644 --- a/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/security/DummyUserDetailsService.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/src/main/java/com/baeldung/intro/security/DummyUserDetailsService.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.intro.security; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index 628f439cc0..0de20cd087 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -62,12 +62,6 @@ h2 - - net.bytebuddy - byte-buddy-dep - ${bytebuddy.version} - - @@ -102,7 +96,6 @@ - 1.10.9 2.0.3.RELEASE diff --git a/twitter4j/pom.xml b/twitter4j/pom.xml index 274b5c75c3..0c36e72892 100644 --- a/twitter4j/pom.xml +++ b/twitter4j/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - twitter4J + twitter4j twitter4J jar