diff --git a/algorithms/README.md b/algorithms/README.md index b0c5ee9d77..5f101c296c 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -14,3 +14,4 @@ - [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort) - [Introduction to JGraphT](http://www.baeldung.com/jgrapht) - [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm) +- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance) diff --git a/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java b/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java new file mode 100644 index 0000000000..48d51a8848 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java @@ -0,0 +1,59 @@ +package com.baeldung.algorithms.prime; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PrimeGenerator { + public static List sieveOfEratosthenes(int n) { + final boolean prime[] = new boolean[n + 1]; + Arrays.fill(prime, true); + + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * 2; i <= n; i += p) + prime[i] = false; + } + } + + final List primes = new LinkedList<>(); + for (int i = 2; i <= n; i++) { + if (prime[i]) + primes.add(i); + } + return primes; + } + + public static List primeNumbersBruteForce(int max) { + final List primeNumbers = new LinkedList(); + for (int i = 2; i <= max; i++) { + if (isPrimeBruteForce(i)) { + primeNumbers.add(i); + } + } + return primeNumbers; + } + + private static boolean isPrimeBruteForce(int x) { + for (int i = 2; i < x; i++) { + if (x % i == 0) { + return false; + } + } + return true; + } + + public static List primeNumbersTill(int max) { + return IntStream.rangeClosed(2, max) + .filter(x -> isPrime(x)) + .boxed() + .collect(Collectors.toList()); + } + + private static boolean isPrime(int x) { + return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) + .allMatch(n -> x % n != 0); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java new file mode 100644 index 0000000000..4995e938b7 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java @@ -0,0 +1,28 @@ +package com.baeldung.algorithms.prime; + +import static com.baeldung.algorithms.prime.PrimeGenerator.*; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PrimeGeneratorTest { + @Test + public void whenBruteForced_returnsSuccessfully() { + final List primeNumbers = primeNumbersBruteForce(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenOptimized_returnsSuccessfully() { + final List primeNumbers = primeNumbersTill(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenSieveOfEratosthenes_returnsSuccessfully() { + final List primeNumbers = sieveOfEratosthenes(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } +} diff --git a/apache-spark/README.md b/apache-spark/README.md new file mode 100644 index 0000000000..fb8059eb27 --- /dev/null +++ b/apache-spark/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [Introduction to Apache Spark](http://www.baeldung.com/apache-spark) diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index f66d54ae67..543354e8b3 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -65,6 +65,24 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + @@ -107,4 +125,5 @@ + diff --git a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java similarity index 84% rename from cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java rename to cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java index 09dbaf0c61..2f2644e2ea 100644 --- a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java +++ b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class CasSecuredAppApplicationTests { +public class CasSecuredAppApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java new file mode 100644 index 0000000000..8788aac747 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java @@ -0,0 +1,35 @@ +/** + * + */ +package com.baeldung.datetime; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.util.Date into java.time.LocalDate. + * + * @author abialas + * + */ +public class DateToLocalDateConverter { + + public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + } + + public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) { + return new java.sql.Date(dateToConvert.getTime()).toLocalDate(); + } + + public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) { + return Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java new file mode 100644 index 0000000000..f994023526 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java @@ -0,0 +1,35 @@ +/** + * + */ +package com.baeldung.datetime; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.util.Date into java.time.LocalDateTime. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverter { + + public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } + + public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) { + return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime(); + } + + public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) { + return Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java new file mode 100644 index 0000000000..ef72c8b4fb --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java @@ -0,0 +1,27 @@ +/** + * + */ +package com.baeldung.datetime; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.time.LocalDateTime into java.util.Date. + * + * @author abialas + * + */ +public class LocalDateTimeToDateConverter { + + public static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) { + return java.sql.Timestamp.valueOf(dateToConvert); + } + + public static Date convertToDateViaInstant(LocalDateTime dateToConvert) { + return java.util.Date.from(dateToConvert.atZone(ZoneId.systemDefault()) + .toInstant()); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java new file mode 100644 index 0000000000..8050815799 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java @@ -0,0 +1,28 @@ +/** + * + */ +package com.baeldung.datetime; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.time.LocalDate into java.util.Date. + * + * @author abialas + * + */ +public class LocalDateToDateConverter { + + public static Date convertToDateViaSqlDate(LocalDate dateToConvert) { + return java.sql.Date.valueOf(dateToConvert); + } + + public static Date convertToDateViaInstant(LocalDate dateToConvert) { + return java.util.Date.from(dateToConvert.atStartOfDay() + .atZone(ZoneId.systemDefault()) + .toInstant()); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java b/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java new file mode 100644 index 0000000000..750807ce77 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java @@ -0,0 +1,59 @@ +package com.baeldung.prime; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PrimeGenerator { + public static List sieveOfEratosthenes(int n) { + final boolean prime[] = new boolean[n + 1]; + Arrays.fill(prime, true); + + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * 2; i <= n; i += p) + prime[i] = false; + } + } + + final List primes = new LinkedList<>(); + for (int i = 2; i <= n; i++) { + if (prime[i]) + primes.add(i); + } + return primes; + } + + public static List primeNumbersBruteForce(int max) { + final List primeNumbers = new LinkedList(); + for (int i = 2; i <= max; i++) { + if (isPrimeBruteForce(i)) { + primeNumbers.add(i); + } + } + return primeNumbers; + } + + private static boolean isPrimeBruteForce(int x) { + for (int i = 2; i < x; i++) { + if (x % i == 0) { + return false; + } + } + return true; + } + + public static List primeNumbersTill(int max) { + return IntStream.rangeClosed(2, max) + .filter(x -> isPrime(x)) + .boxed() + .collect(Collectors.toList()); + } + + private static boolean isPrime(int x) { + return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) + .allMatch(n -> x % n != 0); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java new file mode 100644 index 0000000000..5de6ae3e59 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java @@ -0,0 +1,72 @@ +/** + * + */ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link DateToLocalDateConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateConverterTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java new file mode 100644 index 0000000000..6d8fb8ea93 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java @@ -0,0 +1,78 @@ +/** + * + */ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link DateToLocalDateTimeConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverterTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java new file mode 100644 index 0000000000..519fa69f04 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java @@ -0,0 +1,61 @@ +/** + * + */ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link LocalDateTimeToDateConverter} class. + * + * @author abialas + * + */ +public class LocalDateTimeToDateConverterTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); + + // when + Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(8, calendar.get(Calendar.HOUR)); + assertEquals(20, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() { + // given + LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); + + // when + Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(8, calendar.get(Calendar.HOUR)); + assertEquals(20, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java new file mode 100644 index 0000000000..c1da3af052 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java @@ -0,0 +1,55 @@ +/** + * + */ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link LocalDateToDateConverter} class. + * + * @author abialas + * + */ +public class LocalDateToDateConverterTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertViaInstant() { + // given + LocalDate dateToConvert = LocalDate.of(2010, 11, 10); + + // when + Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { + // given + LocalDate dateToConvert = LocalDate.of(2010, 11, 10); + + // when + Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java new file mode 100644 index 0000000000..e53e1c183e --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java @@ -0,0 +1,28 @@ +package com.baeldung.prime; + +import static com.baeldung.prime.PrimeGenerator.*; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PrimeGeneratorTest { + @Test + public void whenBruteForced_returnsSuccessfully() { + final List primeNumbers = primeNumbersBruteForce(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenOptimized_returnsSuccessfully() { + final List primeNumbers = primeNumbersTill(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenSieveOfEratosthenes_returnsSuccessfully() { + final List primeNumbers = sieveOfEratosthenes(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java new file mode 100644 index 0000000000..bafa9ebff1 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java @@ -0,0 +1,22 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows a way to convert java.util.Date into java.time.LocalDate with new Java 1.9. + * + * @author abialas + * + */ +public class DateToLocalDateConverter { + + public static LocalDate convertToLocalDate(Date dateToConvert) { + return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); + } + +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java new file mode 100644 index 0000000000..538d5a9f63 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java @@ -0,0 +1,22 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows a way to convert java.util.Date into java.time.LocalDateTime with new Java 1.9. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverter { + + public static LocalDateTime convertToLocalDateTime(Date dateToConvert) { + return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java new file mode 100644 index 0000000000..2e0fb0dedd --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java @@ -0,0 +1,41 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +import com.baeldung.java9.datetime.DateToLocalDateConverter; + +/** + * JUnits for {@link DateToLocalDateConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateConverterTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertToLocalDate() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java new file mode 100644 index 0000000000..49988c8b33 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java @@ -0,0 +1,43 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +import com.baeldung.java9.datetime.DateToLocalDateTimeConverter; + +/** + * JUnits for {@link DateToLocalDateTimeConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverterTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + +} diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md index f1d95482d4..48c5f2a50c 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency/README.md @@ -30,3 +30,4 @@ - [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile) - [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent) - [Semaphores in Java](http://www.baeldung.com/java-semaphore) +- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread) diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java new file mode 100644 index 0000000000..0e72821a88 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java @@ -0,0 +1,52 @@ +package com.baeldung.concurrent.stopping; + +import java.util.concurrent.atomic.AtomicBoolean; + +public class ControlSubThread implements Runnable { + + private Thread worker; + private int interval = 100; + private AtomicBoolean running = new AtomicBoolean(false); + private AtomicBoolean stopped = new AtomicBoolean(true); + + + public ControlSubThread(int sleepInterval) { + interval = sleepInterval; + } + + public void start() { + worker = new Thread(this); + worker.start(); + } + + public void stop() { + running.set(false); + } + + public void interrupt() { + running.set(false); + worker.interrupt(); + } + + boolean isRunning() { + return running.get(); + } + + boolean isStopped() { + return stopped.get(); + } + + public void run() { + running.set(true); + stopped.set(false); + while (running.get()) { + try { + Thread.sleep(interval); + } catch (InterruptedException e) { + // no-op, just loop again + } + // do something + } + stopped.set(true); + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java similarity index 87% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java index 4bd4848905..2a51f83e2b 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java @@ -1,24 +1,21 @@ package com.baeldung.concurrent.runnable; import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.lang3.RandomUtils; -import org.junit.After; import org.junit.AfterClass; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class RunnableVsThreadTest { +public class RunnableVsThreadLiveTest { private static Logger log = - LoggerFactory.getLogger(RunnableVsThreadTest.class); + LoggerFactory.getLogger(RunnableVsThreadLiveTest.class); private static ExecutorService executorService; @@ -77,9 +74,7 @@ public class RunnableVsThreadTest { public void givenACallableAsLambda_whenSubmitToES_thenResult() throws Exception { - Future future = executorService.submit(() -> { - return RandomUtils.nextInt(0, 100); - }); + Future future = executorService.submit(() -> RandomUtils.nextInt(0, 100)); log.info("Result from callable: {}", future.get()); } @@ -99,7 +94,7 @@ class SimpleThread extends Thread{ private String message; - public SimpleThread(String message) { + SimpleThread(String message) { this.message = message; } @@ -116,7 +111,7 @@ class SimpleRunnable implements Runnable { private String message; - public SimpleRunnable(String message) { + SimpleRunnable(String message) { this.message = message; } diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java new file mode 100644 index 0000000000..8c1bdbf787 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java @@ -0,0 +1,50 @@ +package com.baeldung.concurrent.stopping; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class StopThreadTest { + + @Test + public void whenStoppedThreadIsStopped() throws InterruptedException { + + int interval = 100; + + ControlSubThread controlSubThread = new ControlSubThread(interval); + controlSubThread.start(); + + // Give things a chance to get set up + Thread.sleep(interval); + assertTrue(controlSubThread.isRunning()); + assertFalse(controlSubThread.isStopped()); + + // Stop it and make sure the flags have been reversed + controlSubThread.stop(); + Thread.sleep(interval); + assertTrue(controlSubThread.isStopped()); + } + + + @Test + public void whenInterruptedThreadIsStopped() throws InterruptedException { + + int interval = 5000; + + ControlSubThread controlSubThread = new ControlSubThread(interval); + controlSubThread.start(); + + // Give things a chance to get set up + Thread.sleep(100); + assertTrue(controlSubThread.isRunning()); + assertFalse(controlSubThread.isStopped()); + + // Stop it and make sure the flags have been reversed + controlSubThread.interrupt(); + + // Wait less than the time we would normally sleep, and make sure we exited. + Thread.sleep(interval/10); + assertTrue(controlSubThread.isStopped()); + } +} diff --git a/core-java/README.md b/core-java/README.md index b4b8d9062e..df3d26d8fa 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -114,4 +114,6 @@ - [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) - [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int) - [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) - +- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) +- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) +- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array) diff --git a/core-java/pom.xml b/core-java/pom.xml index cea5e9b3ec..dbf61c3acf 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -216,6 +216,13 @@ spring-web 4.3.4.RELEASE + + com.sun + tools + 1.8.0 + system + ${java.home}/../lib/tools.jar + diff --git a/core-java/src/main/java/com/baeldung/breakcontinue/BreakContinue.java b/core-java/src/main/java/com/baeldung/breakcontinue/BreakContinue.java new file mode 100644 index 0000000000..ce85b487c1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/breakcontinue/BreakContinue.java @@ -0,0 +1,138 @@ +package com.baeldung.breakcontinue; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +/** + * @author Santosh + * + */ +public class BreakContinue { + + public static int unlabeledBreak() { + String searchName = "Wilson"; + int counter = 0; + List names = Arrays.asList("John", "Peter", "Robert", "Wilson", "Anthony", "Donald", "Richard"); + + for (String name : names) { + counter++; + if (name.equalsIgnoreCase(searchName)) { + break; + } + } + + return counter; + } + + public static int unlabeledBreakNestedLoops() { + String searchName = "Wilson"; + int counter = 0; + Map> nameMap = new HashMap<>(); + nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson")); + nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold")); + nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan")); + + Iterator>> iterator = nameMap.entrySet() + .iterator(); + Entry> entry = null; + List names = null; + while (iterator.hasNext()) { + entry = iterator.next(); + names = entry.getValue(); + for (String name : names) { + if (name.equalsIgnoreCase(searchName)) { + counter++; + break; + } + } + } + + return counter; + } + + public static int labeledBreak() { + String searchName = "Wilson"; + int counter = 0; + Map> nameMap = new HashMap<>(); + nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson")); + nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold")); + nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan")); + + Iterator>> iterator = nameMap.entrySet() + .iterator(); + Entry> entry = null; + List names = null; + compare: + while (iterator.hasNext()) { + entry = iterator.next(); + names = entry.getValue(); + for (String name : names) { + if (name.equalsIgnoreCase(searchName)) { + counter++; + break compare; + } + } + } + + return counter; + } + + public static int unlabeledContinue() { + String searchName = "Wilson"; + int counter = 0; + Map> nameMap = new HashMap<>(); + nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson")); + nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold")); + nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan")); + + Iterator>> iterator = nameMap.entrySet() + .iterator(); + Entry> entry = null; + List names = null; + while (iterator.hasNext()) { + entry = iterator.next(); + names = entry.getValue(); + for (String name : names) { + if (!name.equalsIgnoreCase(searchName)) { + continue; + } + + counter++; + } + } + + return counter; + } + + public static int labeledContinue() { + String searchName = "Wilson"; + int counter = 0; + Map> nameMap = new HashMap<>(); + nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson")); + nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold")); + nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan")); + + Iterator>> iterator = nameMap.entrySet() + .iterator(); + Entry> entry = null; + List names = null; + compare: + while (iterator.hasNext()) { + entry = iterator.next(); + names = entry.getValue(); + for (String name : names) { + if (name.equalsIgnoreCase(searchName)) { + counter++; + continue compare; + } + } + } + + return counter; + } + +} diff --git a/core-java/src/main/java/com/baeldung/javac/Positive.java b/core-java/src/main/java/com/baeldung/javac/Positive.java new file mode 100644 index 0000000000..443b866fea --- /dev/null +++ b/core-java/src/main/java/com/baeldung/javac/Positive.java @@ -0,0 +1,9 @@ +package com.baeldung.javac; + +import java.lang.annotation.*; + +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.PARAMETER}) +public @interface Positive { +} diff --git a/core-java/src/main/java/com/baeldung/javac/SampleJavacPlugin.java b/core-java/src/main/java/com/baeldung/javac/SampleJavacPlugin.java new file mode 100644 index 0000000000..eb48d6a216 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/javac/SampleJavacPlugin.java @@ -0,0 +1,123 @@ +package com.baeldung.javac; + +import com.sun.source.tree.MethodTree; +import com.sun.source.tree.VariableTree; +import com.sun.source.util.*; +import com.sun.tools.javac.api.BasicJavacTask; +import com.sun.tools.javac.code.TypeTag; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.TreeMaker; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Name; +import com.sun.tools.javac.util.Names; + +import javax.tools.JavaCompiler; +import java.util.*; +import java.util.stream.Collectors; + +import static com.sun.tools.javac.util.List.nil; + +/** + * A {@link JavaCompiler javac} plugin which inserts {@code >= 0} checks into resulting {@code *.class} files + * for numeric method parameters marked by {@link Positive} + */ +public class SampleJavacPlugin implements Plugin { + + public static final String NAME = "MyPlugin"; + + private static Set TARGET_TYPES = new HashSet<>(Arrays.asList( + // Use only primitive types for simplicity + byte.class.getName(), short.class.getName(), char.class.getName(), + int.class.getName(), long.class.getName(), float.class.getName(), double.class.getName())); + + @Override + public String getName() { + return NAME; + } + + @Override + public void init(JavacTask task, String... args) { + Context context = ((BasicJavacTask) task).getContext(); + task.addTaskListener(new TaskListener() { + @Override + public void started(TaskEvent e) { + } + + @Override + public void finished(TaskEvent e) { + if (e.getKind() != TaskEvent.Kind.PARSE) { + return; + } + e.getCompilationUnit() + .accept(new TreeScanner() { + @Override + public Void visitMethod(MethodTree method, Void v) { + List parametersToInstrument = method.getParameters() + .stream() + .filter(SampleJavacPlugin.this::shouldInstrument) + .collect(Collectors.toList()); + if (!parametersToInstrument.isEmpty()) { + // There is a possible case that more than one argument is marked by @Positive, + // as the checks are added to the method's body beginning, we process parameters RTL + // to ensure correct order. + Collections.reverse(parametersToInstrument); + parametersToInstrument.forEach(p -> addCheck(method, p, context)); + } + // There is a possible case that there is a nested class declared in a method's body, + // hence, we want to proceed with method body AST as well. + return super.visitMethod(method, v); + } + }, null); + } + }); + } + + private boolean shouldInstrument(VariableTree parameter) { + return TARGET_TYPES.contains(parameter.getType().toString()) + && parameter.getModifiers().getAnnotations() + .stream() + .anyMatch(a -> Positive.class.getSimpleName().equals(a.getAnnotationType().toString())); + } + + private void addCheck(MethodTree method, VariableTree parameter, Context context) { + JCTree.JCIf check = createCheck(parameter, context); + JCTree.JCBlock body = (JCTree.JCBlock) method.getBody(); + body.stats = body.stats.prepend(check); + } + + private static JCTree.JCIf createCheck(VariableTree parameter, Context context) { + TreeMaker factory = TreeMaker.instance(context); + Names symbolsTable = Names.instance(context); + + return factory.at(((JCTree) parameter).pos) + .If(factory.Parens(createIfCondition(factory, symbolsTable, parameter)), + createIfBlock(factory, symbolsTable, parameter), + null); + } + + private static JCTree.JCBinary createIfCondition(TreeMaker factory, Names symbolsTable, VariableTree parameter) { + Name parameterId = symbolsTable.fromString(parameter.getName().toString()); + return factory.Binary(JCTree.Tag.LE, + factory.Ident(parameterId), + factory.Literal(TypeTag.INT, 0)); + } + + private static JCTree.JCBlock createIfBlock(TreeMaker factory, Names symbolsTable, VariableTree parameter) { + String parameterName = parameter.getName().toString(); + Name parameterId = symbolsTable.fromString(parameterName); + + String errorMessagePrefix = String.format("Argument '%s' of type %s is marked by @%s but got '", + parameterName, parameter.getType(), Positive.class.getSimpleName()); + String errorMessageSuffix = "' for it"; + + return factory.Block(0, com.sun.tools.javac.util.List.of( + factory.Throw( + factory.NewClass(null, nil(), + factory.Ident(symbolsTable.fromString(IllegalArgumentException.class.getSimpleName())), + com.sun.tools.javac.util.List.of(factory.Binary(JCTree.Tag.PLUS, + factory.Binary(JCTree.Tag.PLUS, factory.Literal(TypeTag.CLASS, errorMessagePrefix), + factory.Ident(parameterId)), + factory.Literal(TypeTag.CLASS, errorMessageSuffix))), null)))); + } + +} diff --git a/core-java/src/main/resources/META-INF/services/com.sun.source.util.Plugin b/core-java/src/main/resources/META-INF/services/com.sun.source.util.Plugin new file mode 100644 index 0000000000..91fb6eb3b0 --- /dev/null +++ b/core-java/src/main/resources/META-INF/services/com.sun.source.util.Plugin @@ -0,0 +1 @@ +com.baeldung.javac.SampleJavacPlugin \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java new file mode 100644 index 0000000000..1980497cd3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java @@ -0,0 +1,39 @@ +package com.baeldung.breakcontinue; + +import static com.baeldung.breakcontinue.BreakContinue.labeledBreak; +import static com.baeldung.breakcontinue.BreakContinue.labeledContinue; +import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreak; +import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreakNestedLoops; +import static com.baeldung.breakcontinue.BreakContinue.unlabeledContinue; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class BreakContinueTest { + + @Test + public void whenUnlabeledBreak_ThenEqual() { + assertEquals(4, unlabeledBreak()); + } + + @Test + public void whenUnlabeledBreakNestedLoops_ThenEqual() { + assertEquals(2, unlabeledBreakNestedLoops()); + } + + @Test + public void whenLabeledBreak_ThenEqual() { + assertEquals(1, labeledBreak()); + } + + @Test + public void whenUnlabeledContinue_ThenEqual() { + assertEquals(5, unlabeledContinue()); + } + + @Test + public void whenLabeledContinue_ThenEqual() { + assertEquals(3, labeledContinue()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java b/core-java/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java new file mode 100644 index 0000000000..b877038add --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.javac; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SampleJavacPluginIntegrationTest { + + private static final String CLASS_TEMPLATE = + "package com.baeldung.javac;\n" + + "\n" + + "public class Test {\n" + + " public static %1$s service(@Positive %1$s i) {\n" + + " return i;\n" + + " }\n" + + "}\n" + + ""; + + private TestCompiler compiler = new TestCompiler(); + private TestRunner runner = new TestRunner(); + + @Test(expected = IllegalArgumentException.class) + public void givenInt_whenNegative_thenThrowsException() throws Throwable { + compileAndRun(double.class,-1); + } + + @Test(expected = IllegalArgumentException.class) + public void givenInt_whenZero_thenThrowsException() throws Throwable { + compileAndRun(int.class,0); + } + + @Test + public void givenInt_whenPositive_thenSuccess() throws Throwable { + assertEquals(1, compileAndRun(int.class, 1)); + } + + private Object compileAndRun(Class argumentType, Object argument) throws Throwable { + String qualifiedClassName = "com.baeldung.javac.Test"; + byte[] byteCode = compiler.compile(qualifiedClassName, String.format(CLASS_TEMPLATE, argumentType.getName())); + return runner.run(byteCode, qualifiedClassName, "service", new Class[] {argumentType}, argument); + } +} diff --git a/core-java/src/test/java/com/baeldung/javac/SimpleClassFile.java b/core-java/src/test/java/com/baeldung/javac/SimpleClassFile.java new file mode 100644 index 0000000000..2c8e66e6e3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javac/SimpleClassFile.java @@ -0,0 +1,26 @@ +package com.baeldung.javac; + +import javax.tools.SimpleJavaFileObject; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; + +/** Holds compiled byte code in a byte array */ +public class SimpleClassFile extends SimpleJavaFileObject { + + private ByteArrayOutputStream out; + + public SimpleClassFile(URI uri) { + super(uri, Kind.CLASS); + } + + @Override + public OutputStream openOutputStream() throws IOException { + return out = new ByteArrayOutputStream(); + } + + public byte[] getCompiledBinaries() { + return out.toByteArray(); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/javac/SimpleFileManager.java b/core-java/src/test/java/com/baeldung/javac/SimpleFileManager.java new file mode 100644 index 0000000000..346f240754 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javac/SimpleFileManager.java @@ -0,0 +1,34 @@ +package com.baeldung.javac; + +import javax.tools.*; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +/** Adapts {@link SimpleClassFile} to the {@link JavaCompiler} */ +public class SimpleFileManager extends ForwardingJavaFileManager { + + private final List compiled = new ArrayList<>(); + + public SimpleFileManager(StandardJavaFileManager delegate) { + super(delegate); + } + + @Override + public JavaFileObject getJavaFileForOutput(Location location, + String className, + JavaFileObject.Kind kind, + FileObject sibling) + { + SimpleClassFile result = new SimpleClassFile(URI.create("string://" + className)); + compiled.add(result); + return result; + } + + /** + * @return compiled binaries processed by the current class + */ + public List getCompiled() { + return compiled; + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/javac/SimpleSourceFile.java b/core-java/src/test/java/com/baeldung/javac/SimpleSourceFile.java new file mode 100644 index 0000000000..9287b1a0dd --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javac/SimpleSourceFile.java @@ -0,0 +1,23 @@ +package com.baeldung.javac; + +import javax.tools.SimpleJavaFileObject; +import java.net.URI; + +/** Exposes given test source to the compiler. */ +public class SimpleSourceFile extends SimpleJavaFileObject { + + private final String content; + + public SimpleSourceFile(String qualifiedClassName, String testSource) { + super(URI.create(String.format("file://%s%s", + qualifiedClassName.replaceAll("\\.", "/"), + Kind.SOURCE.extension)), + Kind.SOURCE); + content = testSource; + } + + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return content; + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/javac/TestCompiler.java b/core-java/src/test/java/com/baeldung/javac/TestCompiler.java new file mode 100644 index 0000000000..ee40e563a3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javac/TestCompiler.java @@ -0,0 +1,35 @@ +package com.baeldung.javac; + +import javax.tools.JavaCompiler; +import javax.tools.ToolProvider; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; + +public class TestCompiler { + public byte[] compile(String qualifiedClassName, String testSource) { + StringWriter output = new StringWriter(); + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + SimpleFileManager fileManager = new SimpleFileManager(compiler.getStandardFileManager( + null, + null, + null + )); + List compilationUnits = singletonList(new SimpleSourceFile(qualifiedClassName, testSource)); + List arguments = new ArrayList<>(); + arguments.addAll(asList("-classpath", System.getProperty("java.class.path"), + "-Xplugin:" + SampleJavacPlugin.NAME)); + JavaCompiler.CompilationTask task = compiler.getTask(output, + fileManager, + null, + arguments, + null, + compilationUnits); + task.call(); + return fileManager.getCompiled().iterator().next().getCompiledBinaries(); + } +} diff --git a/core-java/src/test/java/com/baeldung/javac/TestRunner.java b/core-java/src/test/java/com/baeldung/javac/TestRunner.java new file mode 100644 index 0000000000..6a03ad4918 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javac/TestRunner.java @@ -0,0 +1,41 @@ +package com.baeldung.javac; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class TestRunner { + + public Object run(byte[] byteCode, + String qualifiedClassName, + String methodName, + Class[] argumentTypes, + Object... args) + throws Throwable + { + ClassLoader classLoader = new ClassLoader() { + @Override + protected Class findClass(String name) throws ClassNotFoundException { + return defineClass(name, byteCode, 0, byteCode.length); + } + }; + Class clazz; + try { + clazz = classLoader.loadClass(qualifiedClassName); + } catch (ClassNotFoundException e) { + throw new RuntimeException("Can't load compiled test class", e); + } + + Method method; + try { + method = clazz.getMethod(methodName, argumentTypes); + } catch (NoSuchMethodException e) { + throw new RuntimeException("Can't find the 'main()' method in the compiled test class", e); + } + + try { + return method.invoke(null, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } +} diff --git a/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java b/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java new file mode 100644 index 0000000000..2b04617f36 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java @@ -0,0 +1,137 @@ +package com.baeldung.stack; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.List; +import java.util.ListIterator; +import java.util.Stack; + +import org.junit.Test; +public class StackUnitTest { + + @Test + public void whenStackIsCreated_thenItHasSize0() { + Stack intStack = new Stack(); + assertEquals(0, intStack.size()); + } + + @Test + public void givenEmptyStack_whenElementIsPushed_thenStackSizeisIncreased() { + Stack intStack = new Stack(); + intStack.push(1); + assertEquals(1, intStack.size()); + } + + @Test + public void givenEmptyStack_whenMultipleElementsArePushed_thenStackSizeisIncreased() { + Stack intStack = new Stack(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + boolean result = intStack.addAll(intList); + assertTrue(result); + assertEquals(7, intList.size()); + } + + @Test + public void whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.pop(); + assertTrue(intStack.isEmpty()); + } + + @Test + public void whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.peek(); + assertEquals(1, intStack.search(5)); + assertEquals(1, intStack.size()); + } + + @Test + public void whenElementIsOnStack_thenSearchReturnsItsDistanceFromTheTop() { + Stack intStack = new Stack(); + intStack.push(5); + assertEquals(1, intStack.search(5)); + } + + @Test + public void whenElementIsOnStack_thenIndexOfReturnsItsIndex() { + Stack intStack = new Stack(); + intStack.push(5); + int indexOf = intStack.indexOf(5); + assertEquals(0, indexOf); + } + + @Test + public void whenMultipleElementsAreOnStack_thenIndexOfReturnsLastElementIndex() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(5); + intStack.push(5); + int lastIndexOf = intStack.lastIndexOf(5); + assertEquals(2, lastIndexOf); + } + + @Test + public void givenElementOnStack_whenRemoveElementIsInvoked_thenElementIsRemoved() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(5); + intStack.removeElement(5); + assertEquals(1, intStack.size()); + } + + @Test + public void givenElementOnStack_whenRemoveElementAtIsInvoked_thenElementIsRemoved() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(7); + intStack.removeElementAt(1); + assertEquals(-1, intStack.search(7)); + } + + @Test + public void givenElementsOnStack_whenRemoveAllElementsIsInvoked_thenAllElementsAreRemoved() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(7); + intStack.removeAllElements(); + assertTrue(intStack.isEmpty()); + } + + @Test + public void givenElementsOnStack_whenRemoveAllIsInvoked_thenAllElementsFromCollectionAreRemoved() { + Stack intStack = new Stack(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + intStack.addAll(intList); + intStack.add(500); + intStack.removeAll(intList); + assertEquals(1, intStack.size()); + } + + @Test + public void givenElementsOnStack_whenRemoveIfIsInvoked_thenAllElementsSatysfyingConditionAreRemoved() { + Stack intStack = new Stack(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + intStack.addAll(intList); + intStack.removeIf(element -> element < 6); + assertEquals(2, intStack.size()); + } + + @Test + public void whenAnotherStackCreatedWhileTraversingStack_thenStacksAreEqual() { + Stack intStack = new Stack<>(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + intStack.addAll(intList); + ListIterator it = intStack.listIterator(); + Stack result = new Stack(); + while(it.hasNext()) { + result.push(it.next()); + } + + assertThat(result, equalTo(intStack)); + } +} diff --git a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java new file mode 100644 index 0000000000..5e8d2c4455 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java @@ -0,0 +1,141 @@ +package com.baeldung.string.formatter; + +import java.util.Calendar; +import java.util.Formatter; +import java.util.GregorianCalendar; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class StringFormatterExampleTests { + + @Test + public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() { + //Syntax of Format Specifiers for Date/Time Representation + Calendar c = new GregorianCalendar(2017, 11, 10); + String s = String.format("The date is: %1$tm %1$te,%1$tY", c); + + assertEquals("The date is: 12 10,2017", s); + } + + @Test + public void givenString_whenGeneralConversion_thenConvertedString() { + //General Conversions + String s = String.format("The correct answer is %s", false); + assertEquals("The correct answer is false", s); + + s = String.format("The correct answer is %b", null); + assertEquals("The correct answer is false", s); + + s = String.format("The correct answer is %B", true); + assertEquals("The correct answer is TRUE", s); + } + + @Test + public void givenString_whenCharConversion_thenConvertedString() { + //Character Conversions + String s = String.format("The correct answer is %c", 'a'); + assertEquals("The correct answer is a", s); + + s = String.format("The correct answer is %c", null); + assertEquals("The correct answer is null", s); + + s = String.format("The correct answer is %C", 'b'); + assertEquals("The correct answer is B", s); + + s = String.format("The valid unicode character: %c", 0x0400); + assertTrue(Character.isValidCodePoint(0x0400)); + assertEquals("The valid unicode character: Ѐ", s); + } + + @Test(expected = java.util.IllegalFormatCodePointException.class) + public void givenString_whenIllegalCodePointForConversion_thenError() { + String s = String.format("The valid unicode character: %c", 0x11FFFF); + assertFalse(Character.isValidCodePoint(0x11FFFF)); + assertEquals("The valid unicode character: Ā", s); + } + + @Test + public void givenString_whenNumericIntegralConversion_thenConvertedString() { + //Numeric Integral Conversions + String s = String.format("The number 25 in decimal = %d", 25); + assertEquals("The number 25 in decimal = 25", s); + + s = String.format("The number 25 in octal = %o", 25); + assertEquals("The number 25 in octal = 31", s); + + s = String.format("The number 25 in hexadecimal = %x", 25); + assertEquals("The number 25 in hexadecimal = 19", s); + } + + @Test + public void givenString_whenNumericFloatingConversion_thenConvertedString() { + //Numeric Floating-point Conversions + String s = String.format("The computerized scientific format of 10000.00 " + + "= %e", 10000.00); + assertEquals("The computerized scientific format of 10000.00 = 1.000000e+04", s); + + s = String.format("The decimal format of 10.019 = %f", 10.019); + assertEquals("The decimal format of 10.019 = 10.019000", s); + } + + @Test + public void givenString_whenLineSeparatorConversion_thenConvertedString() { + //Line Separator Conversion + String s = String.format("First Line %nSecond Line"); + assertEquals("First Line \n" + + "Second Line", s); + } + + @Test + public void givenString_whenSpecifyFlag_thenGotFormattedString() { + //Without left-justified flag + String s = String.format("Without left justified flag: %5d", 25); + assertEquals("Without left justified flag: 25", s); + + //Using left-justified flag + s = String.format("With left justified flag: %-5d", 25); + assertEquals("With left justified flag: 25 ", s); + } + + @Test + public void givenString_whenSpecifyPrecision_thenGotExpected() { + + //Precision + String s = String.format("Output of 25.09878 with Precision 2: %.2f", 25.09878); + assertEquals("Output of 25.09878 with Precision 2: 25.10", s); + + s = String.format("Output of general conversion type with Precision 2: %.2b", true); + assertEquals("Output of general conversion type with Precision 2: tr", s); + } + + @Test + public void givenString_whenSpecifyArgumentIndex_thenGotExpected() { + Calendar c = new GregorianCalendar(2017, 11, 10); + //Argument_Index + String s = String.format("The date is: %1$tm %1$te,%1$tY", c); + assertEquals("The date is: 12 10,2017", s); + + s = String.format("The date is: %1$tm % - - - 4.0.0 - - drools-backward-chaining - 1.0 - drools-backward-chaining - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - 6.4.0.Final - - - - - org.kie - kie-api - ${runtime.version} - - - org.drools - drools-core - ${runtime.version} - - - org.drools - drools-decisiontables - ${runtime.version} - - - diff --git a/drools/backward-chaining/src/main/java/com/baeldung/BackwardChainingBeatles.java b/drools/backward-chaining/src/main/java/com/baeldung/BackwardChainingBeatles.java deleted file mode 100644 index 7fc5bd3685..0000000000 --- a/drools/backward-chaining/src/main/java/com/baeldung/BackwardChainingBeatles.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung; - -import org.kie.api.KieServices; -import org.kie.api.runtime.KieContainer; -import org.kie.api.runtime.KieSession; - -import com.baeldung.model.Beatle; - -public class BackwardChainingBeatles { - public static void main(String[] args) { - - KieServices ks = KieServices.Factory.get(); - KieContainer kContainer = ks.getKieClasspathContainer(); - KieSession kSession = kContainer.newKieSession("ksession-backward-chaining"); - // drools session base on the xml configuration (kmodule.xml) - - // graph population - kSession.insert(new Beatle("Starr", "drums")); - kSession.insert(new Beatle("McCartney", "bass")); - kSession.insert(new Beatle("Lennon", "guitar")); - kSession.insert(new Beatle("Harrison", "guitar")); - - kSession.insert("Ringo"); // invoke the rule that calls the query implentation of backward chaining - kSession.fireAllRules(); // invoke all the rules - - } - -} \ No newline at end of file diff --git a/drools/backward-chaining/src/main/java/com/baeldung/model/Beatle.java b/drools/backward-chaining/src/main/java/com/baeldung/model/Beatle.java deleted file mode 100644 index 4b219b3a69..0000000000 --- a/drools/backward-chaining/src/main/java/com/baeldung/model/Beatle.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.model; - -import org.kie.api.definition.type.Position; - -public class Beatle { - - @Position(0) - private String lastName; - @Position(1) - private String instrument; - - public Beatle(String lastName, String instrument) { - this.lastName = lastName; - this.instrument = instrument; - } - - public String getInstrument() { - return instrument; - } - - public void setInstrument(String instrument) { - this.instrument = instrument; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - -} \ No newline at end of file diff --git a/drools/backward-chaining/src/main/resources/META-INF/kmodule.xml b/drools/backward-chaining/src/main/resources/META-INF/kmodule.xml deleted file mode 100644 index 6498e26343..0000000000 --- a/drools/backward-chaining/src/main/resources/META-INF/kmodule.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/drools/backward-chaining/src/main/resources/META-INF/maven/pom.properties b/drools/backward-chaining/src/main/resources/META-INF/maven/pom.properties deleted file mode 100644 index 26d8331732..0000000000 --- a/drools/backward-chaining/src/main/resources/META-INF/maven/pom.properties +++ /dev/null @@ -1,3 +0,0 @@ -groupId=com.baeldung.drools -artifactId=DroosBackwardChaining -version=1.0.0-SNAPSHOT diff --git a/drools/backward-chaining/src/main/resources/backward_chaining/Beatles.drl b/drools/backward-chaining/src/main/resources/backward_chaining/Beatles.drl deleted file mode 100644 index 8d0d06a79e..0000000000 --- a/drools/backward-chaining/src/main/resources/backward_chaining/Beatles.drl +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung - -import com.baeldung.model.Beatle; - - -query whichBeatle(String lastName, String instrument) - Beatle(lastName, instrument;) - or - (Beatle(lastName, null;) - and - whichBeatle(null, instrument;)) //recursive call to the function that allows to search in a derivation tree structure -end - -rule "Ringo" - when - String(this == "Ringo") - whichBeatle("Starr", "drums";) - then - System.out.println("The beatle is Ringo Starr"); -end - -rule "Paul" - when - String(this == "Paul") - whichBeatle("McCartney", "bass";) - then - System.out.println("The beatle is Paul McCartney"); -end - -rule "John" - when - String(this == "John") - whichBeatle("Lennon", "guitar";) - then - System.out.println("The beatle is John Lennon"); -end - -rule "George" - when - String(this == "George") - whichBeatle("Harrison", "guitar";) - then - System.out.println("The beatle is George Harrison"); -end diff --git a/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java b/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java deleted file mode 100644 index 676e941950..0000000000 --- a/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.test; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.kie.api.KieServices; -import org.kie.api.runtime.KieContainer; -import org.kie.api.runtime.KieSession; - -import com.baeldung.drools.model.Fact; -import com.baeldung.drools.model.Result; - -import static junit.framework.TestCase.assertEquals; - -@RunWith(value = JUnit4.class) -public class BackwardChainingTest { - private Result result; - private KieServices ks; - private KieContainer kContainer; - private KieSession ksession; - - @Before - public void before() { - result = new Result(); - ks = KieServices.Factory.get(); - kContainer = ks.getKieClasspathContainer(); - ksession = kContainer.newKieSession("ksession-backward-chaining"); - ksession.setGlobal("result", result); - } - - @Test - public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() { - - ksession.setGlobal("result", result); - ksession.insert(new Fact("Asia", "Planet Earth")); - ksession.insert(new Fact("China", "Asia")); - ksession.insert(new Fact("Great Wall of China", "China")); - - ksession.fireAllRules(); - - // Assert Decision one - assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth"); - } - - @Test - public void whenChinaIsNotGiven_ThenWallOfChinaDoesNotBelongToPlanetEarth() { - ksession.insert(new Fact("Asia", "Planet Earth")); - // ksession.insert(new Location("China", "Asia")); // not provided to force Decision two - ksession.insert(new Fact("Great Wall of China", "China")); - - ksession.fireAllRules(); - - // Assert Decision two - assertEquals(result.getValue(), "Decision two taken: Great Wall of China DOES NOT BELONG TO Planet Earth"); - } -} diff --git a/drools/pom.xml b/drools/pom.xml index 29231f150c..5f228802fa 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -1,24 +1,19 @@ - 4.0.0 - com.baeldung drools - 1.0.0-SNAPSHOT - com.baeldung parent-modules 1.0.0-SNAPSHOT - - - 4.4.6 - 7.1.0.Beta2 - 3.13 - + + 4.4.6 + 7.4.1.Final + 3.13 + @@ -68,4 +63,25 @@ - \ No newline at end of file + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + + + diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java similarity index 59% rename from drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java rename to drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java index 1c1d258b47..6f15ee510b 100644 --- a/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java +++ b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java @@ -1,9 +1,8 @@ -package com.baeldung.drools; +package com.baeldung.drools.backward_chaining; -import org.kie.api.KieServices; -import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; +import com.baeldung.drools.config.DroolsBeanFactory; import com.baeldung.drools.model.Fact; import com.baeldung.drools.model.Result; @@ -11,23 +10,21 @@ public class BackwardChaining { public static void main(String[] args) { Result result = new BackwardChaining().backwardChaining(); System.out.println(result.getValue()); - result.getFacts().stream().forEach(System.out::println); + result.getFacts() + .stream() + .forEach(System.out::println); } public Result backwardChaining() { Result result = new Result(); - KieServices ks = KieServices.Factory.get(); - KieContainer kContainer = ks.getKieClasspathContainer(); - KieSession ksession = kContainer.newKieSession("ksession-backward-chaining"); + KieSession ksession = new DroolsBeanFactory().getKieSession(); ksession.setGlobal("result", result); ksession.insert(new Fact("Asia", "Planet Earth")); -// ksession.insert(new Fact("China", "Asia")); + ksession.insert(new Fact("China", "Asia")); ksession.insert(new Fact("Great Wall of China", "China")); ksession.fireAllRules(); return result; - } - } \ No newline at end of file diff --git a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java index e8841b05e2..cf5d56f246 100644 --- a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java +++ b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java @@ -3,7 +3,6 @@ package com.baeldung.drools.config; import org.drools.decisiontable.DecisionTableProviderImpl; import org.kie.api.KieServices; import org.kie.api.builder.*; -import org.kie.api.io.KieResources; import org.kie.api.io.Resource; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; @@ -22,7 +21,7 @@ public class DroolsBeanFactory { private KieFileSystem getKieFileSystem() throws IOException{ KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); - List rules=Arrays.asList("SuggestApplicant.drl","Product_rules.xls"); + List rules=Arrays.asList("BackwardChaining.drl","SuggestApplicant.drl","Product_rules.xls"); for(String rule:rules){ kieFileSystem.write(ResourceFactory.newClassPathResource(rule)); } @@ -56,9 +55,11 @@ public class DroolsBeanFactory { getKieRepository(); KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); + kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/BackwardChaining.drl")); kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/SuggestApplicant.drl")); kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.xls")); - + + KieBuilder kb = kieServices.newKieBuilder(kieFileSystem); kb.buildAll(); KieModule kieModule = kb.getKieModule(); diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Fact.java b/drools/src/main/java/com/baeldung/drools/model/Fact.java similarity index 100% rename from drools/backward-chaining/src/main/java/com/baeldung/drools/model/Fact.java rename to drools/src/main/java/com/baeldung/drools/model/Fact.java diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Result.java b/drools/src/main/java/com/baeldung/drools/model/Result.java similarity index 100% rename from drools/backward-chaining/src/main/java/com/baeldung/drools/model/Result.java rename to drools/src/main/java/com/baeldung/drools/model/Result.java diff --git a/drools/backward-chaining/src/main/resources/backward_chaining/rules.drl b/drools/src/main/resources/com/baeldung/drools/rules/BackwardChaining.drl similarity index 67% rename from drools/backward-chaining/src/main/resources/backward_chaining/rules.drl rename to drools/src/main/resources/com/baeldung/drools/rules/BackwardChaining.drl index abcf95b9f1..975be84fb4 100644 --- a/drools/backward-chaining/src/main/resources/backward_chaining/rules.drl +++ b/drools/src/main/resources/com/baeldung/drools/rules/BackwardChaining.drl @@ -1,4 +1,4 @@ -package com.baeldung +package com.baeldung.drools.rules import com.baeldung.drools.model.Fact; @@ -19,13 +19,6 @@ then result.setValue("Decision one taken: Great Wall of China BELONGS TO Planet Earth"); end -rule "Great Wall of China DOES NOT BELONG TO of Planet Earth" -when - not belongsTo("Great Wall of China", "Planet Earth";) -then - result.setValue("Decision two taken: Great Wall of China DOES NOT BELONG TO Planet Earth"); -end - rule "print all facts" when belongsTo(element, place;) diff --git a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java new file mode 100644 index 0000000000..f49d0b82de --- /dev/null +++ b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java @@ -0,0 +1,36 @@ +package com.baeldung.drools.backward_chaining; + +import org.junit.Before; +import org.junit.Test; +import org.kie.api.runtime.KieSession; + +import com.baeldung.drools.config.DroolsBeanFactory; +import com.baeldung.drools.model.Fact; +import com.baeldung.drools.model.Result; + +import static junit.framework.TestCase.assertEquals; + +public class BackwardChainingTest { + private Result result; + private KieSession ksession; + + @Before + public void before() { + result = new Result(); + ksession = new DroolsBeanFactory().getKieSession(); + } + + @Test + public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() { + + ksession.setGlobal("result", result); + ksession.insert(new Fact("Asia", "Planet Earth")); + ksession.insert(new Fact("China", "Asia")); + ksession.insert(new Fact("Great Wall of China", "China")); + + ksession.fireAllRules(); + + // Assert Decision one + assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth"); + } +} diff --git a/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java b/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java index e86f52ff56..57376e9c4a 100644 --- a/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java +++ b/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java @@ -16,32 +16,26 @@ import wildfly.beans.UserBeanLocal; * Servlet implementation class TestEJBServlet */ public class TestEJBServlet extends HttpServlet { - private static final long serialVersionUID = 1L; - @EJB - private UserBeanLocal userBean; + @EJB + private UserBeanLocal userBean; - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - List users = userBean.getUsers(); + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + List users = userBean.getUsers(); - PrintWriter out = response.getWriter(); + PrintWriter out = response.getWriter(); - out.println(""); - out.println("Users"); - out.println(""); - out.println("

List of users:

"); - out.println(""); - for (User user : users) { - out.println(""); - out.print(""); - out.print(""); - out.println(""); - } - } + out.println(""); + out.println(""); + for (User user : users) { + out.print(user.getUsername()); + out.print(" " + user.getEmail() + "
"); + } + out.println(""); + out.println(""); + } - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - doGet(request, response); - } + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doGet(request, response); + } } diff --git a/guava-modules/README.md b/guava-modules/README.md new file mode 100644 index 0000000000..79e45a89e7 --- /dev/null +++ b/guava-modules/README.md @@ -0,0 +1,3 @@ + +## Guava Modules + diff --git a/guava18/README.md b/guava-modules/guava-18/README.md similarity index 100% rename from guava18/README.md rename to guava-modules/guava-18/README.md diff --git a/guava18/pom.xml b/guava-modules/guava-18/pom.xml similarity index 89% rename from guava18/pom.xml rename to guava-modules/guava-18/pom.xml index 0b96918171..a9aba47f12 100644 --- a/guava18/pom.xml +++ b/guava-modules/guava-18/pom.xml @@ -4,13 +4,14 @@ 4.0.0com.baeldung - guava18 + guava-180.1.0-SNAPSHOT com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/guava18/src/main/java/com/baeldung/guava/entity/Administrator.java b/guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/Administrator.java similarity index 100% rename from guava18/src/main/java/com/baeldung/guava/entity/Administrator.java rename to guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/Administrator.java diff --git a/guava18/src/main/java/com/baeldung/guava/entity/Player.java b/guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/Player.java similarity index 100% rename from guava18/src/main/java/com/baeldung/guava/entity/Player.java rename to guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/Player.java diff --git a/guava18/src/main/java/com/baeldung/guava/entity/User.java b/guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/User.java similarity index 100% rename from guava18/src/main/java/com/baeldung/guava/entity/User.java rename to guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/User.java diff --git a/guava18/src/test/java/com/baeldung/guava/FluentIterableUnitTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/FluentIterableUnitTest.java similarity index 100% rename from guava18/src/test/java/com/baeldung/guava/FluentIterableUnitTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/FluentIterableUnitTest.java diff --git a/guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java similarity index 100% rename from guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java diff --git a/guava18/src/test/java/com/baeldung/guava/MoreExecutorsUnitTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/MoreExecutorsUnitTest.java similarity index 100% rename from guava18/src/test/java/com/baeldung/guava/MoreExecutorsUnitTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/MoreExecutorsUnitTest.java diff --git a/guava18/src/test/java/com/baeldung/guava/MoreObjectsUnitTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/MoreObjectsUnitTest.java similarity index 100% rename from guava18/src/test/java/com/baeldung/guava/MoreObjectsUnitTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/MoreObjectsUnitTest.java diff --git a/guava19/README.md b/guava-modules/guava-19/README.md similarity index 100% rename from guava19/README.md rename to guava-modules/guava-19/README.md diff --git a/guava19/pom.xml b/guava-modules/guava-19/pom.xml similarity index 90% rename from guava19/pom.xml rename to guava-modules/guava-19/pom.xml index af9bc51eb9..2345212eba 100644 --- a/guava19/pom.xml +++ b/guava-modules/guava-19/pom.xml @@ -4,13 +4,14 @@ 4.0.0 com.baeldung - guava19 + guava-19 0.1.0-SNAPSHOT com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/guava19/src/main/java/com/baeldung/guava/entity/User.java b/guava-modules/guava-19/src/main/java/com/baeldung/guava/entity/User.java similarity index 100% rename from guava19/src/main/java/com/baeldung/guava/entity/User.java rename to guava-modules/guava-19/src/main/java/com/baeldung/guava/entity/User.java diff --git a/guava19/src/test/java/com/baeldung/guava/CharMatcherUnitTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/CharMatcherUnitTest.java similarity index 100% rename from guava19/src/test/java/com/baeldung/guava/CharMatcherUnitTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/CharMatcherUnitTest.java diff --git a/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java similarity index 100% rename from guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java diff --git a/guava19/src/test/java/com/baeldung/guava/HashingUnitTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/HashingUnitTest.java similarity index 100% rename from guava19/src/test/java/com/baeldung/guava/HashingUnitTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/HashingUnitTest.java diff --git a/guava19/src/test/java/com/baeldung/guava/TypeTokenUnitTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/TypeTokenUnitTest.java similarity index 100% rename from guava19/src/test/java/com/baeldung/guava/TypeTokenUnitTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/TypeTokenUnitTest.java diff --git a/guava21/README.md b/guava-modules/guava-21/README.md similarity index 100% rename from guava21/README.md rename to guava-modules/guava-21/README.md diff --git a/guava21/pom.xml b/guava-modules/guava-21/pom.xml similarity index 90% rename from guava21/pom.xml rename to guava-modules/guava-21/pom.xml index 930def2a67..94bb66e76a 100644 --- a/guava21/pom.xml +++ b/guava-modules/guava-21/pom.xml @@ -4,13 +4,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - guava21 + guava-21 1.0-SNAPSHOT com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/AtomicLongMapTutorials.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/AtomicLongMapTutorials.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/AtomicLongMapTutorials.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/AtomicLongMapTutorials.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/ComparatorsExamples.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/ComparatorsExamples.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/ComparatorsExamples.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/ComparatorsExamples.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/ConcatStreams.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/ConcatStreams.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/ConcatStreams.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/ConcatStreams.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/InternerBuilderExample.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/InternerBuilderExample.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/InternerBuilderExample.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/InternerBuilderExample.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/MonitorExample.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/MonitorExample.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/MonitorExample.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/MonitorExample.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/MoreCollectorsExample.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/MoreCollectorsExample.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/MoreCollectorsExample.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/MoreCollectorsExample.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/StreamsUtility.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/StreamsUtility.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/StreamsUtility.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/StreamsUtility.java diff --git a/guava21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java b/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java similarity index 100% rename from guava21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java rename to guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java diff --git a/guest/spring-security/README.md b/guest/spring-security/README.md new file mode 100644 index 0000000000..9e5cd64a04 --- /dev/null +++ b/guest/spring-security/README.md @@ -0,0 +1,17 @@ +## Building + +To build the module, use Maven's `package` goal: + +``` +mvn clean package +``` + +## Running + +To run the application, use Spring Boot's `run` goal: + +``` +mvn spring-boot:run +``` + +The application will be accessible at [http://localhost:8080/](http://localhost:8080/) diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml new file mode 100644 index 0000000000..c41637bfc2 --- /dev/null +++ b/guest/spring-security/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + com.stackify.guest + spring-security + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.M6 + + + + spring-security + Spring Security Sample Project + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.thymeleaf + thymeleaf-spring5 + 3.0.8.RELEASE + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.h2database + h2 + runtime + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + UTF-8 + UTF-8 + 1.8 + + + \ No newline at end of file diff --git a/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java new file mode 100644 index 0000000000..fbd0eee044 --- /dev/null +++ b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java @@ -0,0 +1,15 @@ +package com.stackify.guest.springsecurity; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = {"com.stackify.guest.springsecurity"}) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java new file mode 100644 index 0000000000..b8dfe9050d --- /dev/null +++ b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java @@ -0,0 +1,16 @@ +package com.stackify.guest.springsecurity.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebMvcConfiguration implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/customLogin").setViewName("customLogin"); + registry.addViewController("/loginSuccess").setViewName("index"); + } + +} \ No newline at end of file diff --git a/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java new file mode 100644 index 0000000000..164808d5b3 --- /dev/null +++ b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java @@ -0,0 +1,40 @@ +package com.stackify.guest.springsecurity.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +import javax.sql.DataSource; + +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Bean + public UserDetailsService jdbcUserDetailsService(DataSource dataSource) { + JdbcUserDetailsManager manager = new JdbcUserDetailsManager(); + manager.setDataSource(dataSource); + return manager; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/css/**").permitAll() + .anyRequest().authenticated() + .and().formLogin() + .loginPage("/customLogin") + .defaultSuccessUrl("/loginSuccess", true) + .permitAll(); + } + +} \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/data.sql b/guest/spring-security/src/main/resources/data.sql new file mode 100644 index 0000000000..b3f7db9105 --- /dev/null +++ b/guest/spring-security/src/main/resources/data.sql @@ -0,0 +1,2 @@ +INSERT INTO users VALUES ('jill', '$2a$04$qUlqAEEYF1YvrpJMosodoewgL6aO.qgHytl2k5L7kdXEWnJsFdxvq', TRUE); +INSERT INTO authorities VALUES ('jill', 'USERS'); diff --git a/guest/spring-security/src/main/resources/schema.sql b/guest/spring-security/src/main/resources/schema.sql new file mode 100644 index 0000000000..3de1b9a29f --- /dev/null +++ b/guest/spring-security/src/main/resources/schema.sql @@ -0,0 +1,10 @@ +CREATE TABLE users ( + username VARCHAR(256) PRIMARY KEY, + password VARCHAR(256), + enabled BOOLEAN +); + +CREATE TABLE authorities ( + username VARCHAR(256) REFERENCES users (username), + authority VARCHAR(256) +); diff --git a/guest/spring-security/src/main/resources/static/css/styles.css b/guest/spring-security/src/main/resources/static/css/styles.css new file mode 100644 index 0000000000..72bcc4934f --- /dev/null +++ b/guest/spring-security/src/main/resources/static/css/styles.css @@ -0,0 +1,3 @@ +.bad-login { + color: red; +} \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/templates/customLogin.html b/guest/spring-security/src/main/resources/templates/customLogin.html new file mode 100644 index 0000000000..c689c78514 --- /dev/null +++ b/guest/spring-security/src/main/resources/templates/customLogin.html @@ -0,0 +1,21 @@ + + + + + + +
+
+ + + + +
+ + + +
Log out successful.
+ + + \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/templates/index.html b/guest/spring-security/src/main/resources/templates/index.html new file mode 100644 index 0000000000..0769f9015f --- /dev/null +++ b/guest/spring-security/src/main/resources/templates/index.html @@ -0,0 +1,11 @@ + + +

Hello, !

+
+ + + + \ No newline at end of file diff --git a/hibernate5/README.md b/hibernate5/README.md index 9ef170a134..4690ebbe76 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) +- [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers) diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 0282673218..c44a80cbd9 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -2,8 +2,17 @@ package com.baeldung.hibernate; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Product; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; + import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; @@ -33,6 +42,14 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Phone.class); metadataSources.addAnnotatedClass(EntityDescription.class); metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(User.class); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(Course.class); + metadataSources.addAnnotatedClass(Product.class); + metadataSources.addAnnotatedClass(OrderEntryPK.class); + metadataSources.addAnnotatedClass(OrderEntry.class); + metadataSources.addAnnotatedClass(OrderEntryIdClass.class); + metadataSources.addAnnotatedClass(UserProfile.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder() diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java new file mode 100644 index 0000000000..97760acd3b --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo; + +import java.util.UUID; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Course { + + @Id + @GeneratedValue + private UUID courseId; + + public UUID getCourseId() { + return courseId; + } + + public void setCourseId(UUID courseId) { + this.courseId = courseId; + } + + + + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java new file mode 100644 index 0000000000..6dd106b88e --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.TableGenerator; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.TABLE, generator="table-generator") + @TableGenerator (name="table-generator", table="dep_ids", pkColumnName="seq_id", valueColumnName="seq_value") + private long depId; + + public long getDepId() { + return depId; + } + + public void setDepId(long depId) { + this.depId = depId; + } + + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java new file mode 100644 index 0000000000..a28b7c8dbe --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java @@ -0,0 +1,20 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; + +@Entity +public class OrderEntry { + + @EmbeddedId + private OrderEntryPK entryId; + + public OrderEntryPK getEntryId() { + return entryId; + } + + public void setEntryId(OrderEntryPK entryId) { + this.entryId = entryId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java new file mode 100644 index 0000000000..18926640af --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; + +@Entity +@IdClass(OrderEntryPK.class) +public class OrderEntryIdClass { + @Id + private long orderId; + @Id + private long productId; + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java new file mode 100644 index 0000000000..637d590629 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java @@ -0,0 +1,46 @@ +package com.baeldung.hibernate.pojo; + +import java.io.Serializable; +import java.util.Objects; + +import javax.persistence.Embeddable; + +@Embeddable +public class OrderEntryPK implements Serializable { + + private long orderId; + private long productId; + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderEntryPK pk = (OrderEntryPK) o; + return Objects.equals(orderId, pk.orderId) && Objects.equals(productId, pk.productId); + } + + @Override + public int hashCode() { + return Objects.hash(orderId, productId); + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java new file mode 100644 index 0000000000..efd6b63dc0 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Parameter; + +@Entity +public class Product { + + @Id + @GeneratedValue(generator = "prod-generator") + @GenericGenerator(name = "prod-generator", parameters = @Parameter(name = "prefix", value = "prod"), strategy = "com.baeldung.hibernate.pojo.generator.MyGenerator") + private String prodId; + + public String getProdId() { + return prodId; + } + + public void setProdId(String prodId) { + this.prodId = prodId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..a6dec4a30d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,23 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue (strategy = GenerationType.SEQUENCE) + private long studentId; + + public long getStudentId() { + return studentId; + } + + public void setStudent_id(long studentId) { + this.studentId = studentId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java new file mode 100644 index 0000000000..90203d29ec --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java @@ -0,0 +1,24 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; + +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-generator") + @SequenceGenerator(name = "sequence-generator", sequenceName = "user_sequence", initialValue = 4) + private long userId; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java new file mode 100644 index 0000000000..ac870c2818 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.MapsId; +import javax.persistence.OneToOne; + +@Entity +public class UserProfile { + + @Id + private long profileId; + + @OneToOne + @MapsId + private User user; + + public long getProfileId() { + return profileId; + } + + public void setProfileId(long profileId) { + this.profileId = profileId; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java new file mode 100644 index 0000000000..17ffe9b7e1 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.pojo.generator; + +import java.io.Serializable; +import java.util.Properties; +import java.util.stream.Stream; + +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.id.Configurable; +import org.hibernate.id.IdentifierGenerator; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.type.Type; + +public class MyGenerator implements IdentifierGenerator, Configurable { + + private String prefix; + + @Override + public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException { + + String query = String.format("select %s from %s", + session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(), + obj.getClass().getSimpleName()); + + Stream ids = session.createQuery(query).stream(); + + Long max = ids.map(o -> o.replace(prefix + "-", "")) + .mapToLong(Long::parseLong) + .max() + .orElse(0L); + + return prefix + "-" + (max + 1); + } + + @Override + public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException { + prefix = properties.getProperty("prefix"); + } + +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java new file mode 100644 index 0000000000..6b54dc80a8 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java @@ -0,0 +1,100 @@ +package com.baeldung.hibernate; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.hibernate.Transaction; +import java.io.IOException; +import org.hibernate.Session; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.hibernate.pojo.Product; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; + +public class IdentifiersIntegrationTest { + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void whenSaveSimpleIdEntities_thenOk() { + Student student = new Student(); + session.save(student); + User user = new User(); + session.save(user); + + assertThat(student.getStudentId()).isEqualTo(1L); + assertThat(user.getUserId()).isEqualTo(4L); + + Course course = new Course(); + session.save(course); + + } + + @Test + public void whenSaveCustomGeneratedId_thenOk() { + Product product = new Product(); + session.save(product); + Product product2 = new Product(); + session.save(product2); + + assertThat(product2.getProdId()).isEqualTo("prod-2"); + } + + @Test + public void whenSaveCompositeIdEntity_thenOk() { + OrderEntryPK entryPK = new OrderEntryPK(); + entryPK.setOrderId(1L); + entryPK.setProductId(30L); + + OrderEntry entry = new OrderEntry(); + entry.setEntryId(entryPK); + session.save(entry); + + assertThat(entry.getEntryId() + .getOrderId()).isEqualTo(1L); + } + + @Test + public void whenSaveIdClassEntity_thenOk() { + OrderEntryIdClass entry = new OrderEntryIdClass(); + entry.setOrderId(1L); + entry.setProductId(30L); + session.save(entry); + + assertThat(entry.getOrderId()).isEqualTo(1L); + } + + @Test + public void whenSaveDerivedIdEntity_thenOk() { + User user = new User(); + session.save(user); + + UserProfile profile = new UserProfile(); + profile.setUser(user); + session.save(profile); + + assertThat(profile.getProfileId()).isEqualTo(user.getUserId()); + } + +} diff --git a/jee7/.gitignore b/jee-7/.gitignore similarity index 100% rename from jee7/.gitignore rename to jee-7/.gitignore diff --git a/jee7/README.md b/jee-7/README.md similarity index 100% rename from jee7/README.md rename to jee-7/README.md diff --git a/jee7/pom.xml b/jee-7/pom.xml similarity index 99% rename from jee7/pom.xml rename to jee-7/pom.xml index 6858a05d17..f1d50f55c6 100644 --- a/jee7/pom.xml +++ b/jee-7/pom.xml @@ -4,7 +4,7 @@ 4.0.0 com.baeldung - jee7 + jee-7 1.0-SNAPSHOT war JavaEE 7 Arquillian Archetype Sample diff --git a/jee7/src/main/java/com/baeldung/arquillian/CapsConvertor.java b/jee-7/src/main/java/com/baeldung/arquillian/CapsConvertor.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/CapsConvertor.java rename to jee-7/src/main/java/com/baeldung/arquillian/CapsConvertor.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/CapsService.java b/jee-7/src/main/java/com/baeldung/arquillian/CapsService.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/CapsService.java rename to jee-7/src/main/java/com/baeldung/arquillian/CapsService.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/Car.java b/jee-7/src/main/java/com/baeldung/arquillian/Car.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/Car.java rename to jee-7/src/main/java/com/baeldung/arquillian/Car.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/CarEJB.java b/jee-7/src/main/java/com/baeldung/arquillian/CarEJB.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/CarEJB.java rename to jee-7/src/main/java/com/baeldung/arquillian/CarEJB.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/Component.java b/jee-7/src/main/java/com/baeldung/arquillian/Component.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/Component.java rename to jee-7/src/main/java/com/baeldung/arquillian/Component.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/ConvertToLowerCase.java b/jee-7/src/main/java/com/baeldung/arquillian/ConvertToLowerCase.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/ConvertToLowerCase.java rename to jee-7/src/main/java/com/baeldung/arquillian/ConvertToLowerCase.java diff --git a/jee7/src/main/java/com/baeldung/convListVal/ConvListVal.java b/jee-7/src/main/java/com/baeldung/convListVal/ConvListVal.java similarity index 100% rename from jee7/src/main/java/com/baeldung/convListVal/ConvListVal.java rename to jee-7/src/main/java/com/baeldung/convListVal/ConvListVal.java diff --git a/jee7/src/main/java/com/baeldung/convListVal/MyListener.java b/jee-7/src/main/java/com/baeldung/convListVal/MyListener.java similarity index 100% rename from jee7/src/main/java/com/baeldung/convListVal/MyListener.java rename to jee-7/src/main/java/com/baeldung/convListVal/MyListener.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/AddEmployee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/AddEmployee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/AddEmployee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/AddEmployee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/AddEmployeeResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/AddEmployeeResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/AddEmployeeResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/AddEmployeeResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/CountEmployees.java b/jee-7/src/main/java/com/baeldung/jaxws/client/CountEmployees.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/CountEmployees.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/CountEmployees.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/CountEmployeesResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/CountEmployeesResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/CountEmployeesResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/CountEmployeesResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/DeleteEmployee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/DeleteEmployee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/DeleteEmployee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/DeleteEmployee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/DeleteEmployeeResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/DeleteEmployeeResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/DeleteEmployeeResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/DeleteEmployeeResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/Employee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/Employee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/Employee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/Employee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists_Exception.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists_Exception.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists_Exception.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists_Exception.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound_Exception.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound_Exception.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound_Exception.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound_Exception.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeService.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeService.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeService.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeService.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeServiceClient.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeServiceClient.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeServiceClient.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeServiceClient.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeService_Service.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeService_Service.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeService_Service.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeService_Service.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/GetAllEmployees.java b/jee-7/src/main/java/com/baeldung/jaxws/client/GetAllEmployees.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/GetAllEmployees.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/GetAllEmployees.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/GetAllEmployeesResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/GetAllEmployeesResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/GetAllEmployeesResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/GetAllEmployeesResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/GetEmployee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/GetEmployee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/GetEmployee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/GetEmployee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/GetEmployeeResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/GetEmployeeResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/GetEmployeeResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/GetEmployeeResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/ObjectFactory.java b/jee-7/src/main/java/com/baeldung/jaxws/client/ObjectFactory.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/ObjectFactory.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/ObjectFactory.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/UpdateEmployee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/UpdateEmployee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/UpdateEmployee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/UpdateEmployee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/UpdateEmployeeResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/UpdateEmployeeResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/UpdateEmployeeResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/UpdateEmployeeResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/package-info.java b/jee-7/src/main/java/com/baeldung/jaxws/client/package-info.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/package-info.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/package-info.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeService.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeService.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeService.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeService.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeServiceImpl.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeServiceImpl.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeServiceImpl.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeServiceImpl.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeAlreadyExists.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeAlreadyExists.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeAlreadyExists.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeAlreadyExists.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeNotFound.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeNotFound.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeNotFound.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeNotFound.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/model/Employee.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/model/Employee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/model/Employee.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/model/Employee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/config/EmployeeServicePublisher.java b/jee-7/src/main/java/com/baeldung/jaxws/server/config/EmployeeServicePublisher.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/config/EmployeeServicePublisher.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/config/EmployeeServicePublisher.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepository.java b/jee-7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepository.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepository.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepository.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepositoryImpl.java b/jee-7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepositoryImpl.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepositoryImpl.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepositoryImpl.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown.java b/jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDownImpl.java b/jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDownImpl.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDownImpl.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDownImpl.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown_Service.java b/jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown_Service.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown_Service.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown_Service.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/topdown/ObjectFactory.java b/jee-7/src/main/java/com/baeldung/jaxws/server/topdown/ObjectFactory.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/topdown/ObjectFactory.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/topdown/ObjectFactory.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl b/jee-7/src/main/java/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl rename to jee-7/src/main/java/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl diff --git a/jee7/src/main/java/com/baeldung/json/Person.java b/jee-7/src/main/java/com/baeldung/json/Person.java similarity index 100% rename from jee7/src/main/java/com/baeldung/json/Person.java rename to jee-7/src/main/java/com/baeldung/json/Person.java diff --git a/jee7/src/main/java/com/baeldung/json/PersonBuilder.java b/jee-7/src/main/java/com/baeldung/json/PersonBuilder.java similarity index 100% rename from jee7/src/main/java/com/baeldung/json/PersonBuilder.java rename to jee-7/src/main/java/com/baeldung/json/PersonBuilder.java diff --git a/jee7/src/main/java/com/baeldung/json/PersonWriter.java b/jee-7/src/main/java/com/baeldung/json/PersonWriter.java similarity index 100% rename from jee7/src/main/java/com/baeldung/json/PersonWriter.java rename to jee-7/src/main/java/com/baeldung/json/PersonWriter.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java b/jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java rename to jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java b/jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java rename to jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java b/jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java rename to jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java b/jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java rename to jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java b/jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java rename to jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java diff --git a/jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/TimerEvent.java b/jee-7/src/main/java/com/baeldung/timer/TimerEvent.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/TimerEvent.java rename to jee-7/src/main/java/com/baeldung/timer/TimerEvent.java diff --git a/jee7/src/main/java/com/baeldung/timer/TimerEventListener.java b/jee-7/src/main/java/com/baeldung/timer/TimerEventListener.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/TimerEventListener.java rename to jee-7/src/main/java/com/baeldung/timer/TimerEventListener.java diff --git a/jee7/src/main/java/com/baeldung/timer/WorkerBean.java b/jee-7/src/main/java/com/baeldung/timer/WorkerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/WorkerBean.java rename to jee-7/src/main/java/com/baeldung/timer/WorkerBean.java diff --git a/jee7/src/main/resources/META-INF/persistence.xml b/jee-7/src/main/resources/META-INF/persistence.xml similarity index 100% rename from jee7/src/main/resources/META-INF/persistence.xml rename to jee-7/src/main/resources/META-INF/persistence.xml diff --git a/jee7/src/main/webapp/ConvListVal.xhtml b/jee-7/src/main/webapp/ConvListVal.xhtml similarity index 100% rename from jee7/src/main/webapp/ConvListVal.xhtml rename to jee-7/src/main/webapp/ConvListVal.xhtml diff --git a/jee7/src/main/webapp/WEB-INF/beans.xml b/jee-7/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from jee7/src/main/webapp/WEB-INF/beans.xml rename to jee-7/src/main/webapp/WEB-INF/beans.xml diff --git a/jee7/src/main/webapp/WEB-INF/faces-config.xml b/jee-7/src/main/webapp/WEB-INF/faces-config.xml similarity index 100% rename from jee7/src/main/webapp/WEB-INF/faces-config.xml rename to jee-7/src/main/webapp/WEB-INF/faces-config.xml diff --git a/jee7/src/main/webapp/WEB-INF/spring/security.xml b/jee-7/src/main/webapp/WEB-INF/spring/security.xml similarity index 100% rename from jee7/src/main/webapp/WEB-INF/spring/security.xml rename to jee-7/src/main/webapp/WEB-INF/spring/security.xml diff --git a/jee7/src/main/webapp/WEB-INF/views/admin.jsp b/jee-7/src/main/webapp/WEB-INF/views/admin.jsp similarity index 100% rename from jee7/src/main/webapp/WEB-INF/views/admin.jsp rename to jee-7/src/main/webapp/WEB-INF/views/admin.jsp diff --git a/jee7/src/main/webapp/WEB-INF/views/home.jsp b/jee-7/src/main/webapp/WEB-INF/views/home.jsp similarity index 100% rename from jee7/src/main/webapp/WEB-INF/views/home.jsp rename to jee-7/src/main/webapp/WEB-INF/views/home.jsp diff --git a/jee7/src/main/webapp/WEB-INF/views/login.jsp b/jee-7/src/main/webapp/WEB-INF/views/login.jsp similarity index 100% rename from jee7/src/main/webapp/WEB-INF/views/login.jsp rename to jee-7/src/main/webapp/WEB-INF/views/login.jsp diff --git a/jee7/src/main/webapp/WEB-INF/views/user.jsp b/jee-7/src/main/webapp/WEB-INF/views/user.jsp similarity index 100% rename from jee7/src/main/webapp/WEB-INF/views/user.jsp rename to jee-7/src/main/webapp/WEB-INF/views/user.jsp diff --git a/jee7/src/main/webapp/WEB-INF/web.xml b/jee-7/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from jee7/src/main/webapp/WEB-INF/web.xml rename to jee-7/src/main/webapp/WEB-INF/web.xml diff --git a/jee7/src/main/webapp/index.jsp b/jee-7/src/main/webapp/index.jsp similarity index 100% rename from jee7/src/main/webapp/index.jsp rename to jee-7/src/main/webapp/index.jsp diff --git a/jee7/src/main/webapp/secure.jsp b/jee-7/src/main/webapp/secure.jsp similarity index 100% rename from jee7/src/main/webapp/secure.jsp rename to jee-7/src/main/webapp/secure.jsp diff --git a/jee7/src/test/java/com/baeldug/json/JsonUnitTest.java b/jee-7/src/test/java/com/baeldug/json/JsonUnitTest.java similarity index 100% rename from jee7/src/test/java/com/baeldug/json/JsonUnitTest.java rename to jee-7/src/test/java/com/baeldug/json/JsonUnitTest.java diff --git a/jee7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java b/jee-7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java rename to jee-7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java diff --git a/jee7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/jaxws/EmployeeServiceLiveTest.java b/jee-7/src/test/java/com/baeldung/jaxws/EmployeeServiceLiveTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/jaxws/EmployeeServiceLiveTest.java rename to jee-7/src/test/java/com/baeldung/jaxws/EmployeeServiceLiveTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java b/jee-7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java rename to jee-7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java diff --git a/jee7/src/test/resources/META-INF/persistence.xml b/jee-7/src/test/resources/META-INF/persistence.xml similarity index 100% rename from jee7/src/test/resources/META-INF/persistence.xml rename to jee-7/src/test/resources/META-INF/persistence.xml diff --git a/jsonb/.gitignore b/jsonb/.gitignore new file mode 100644 index 0000000000..dec013dfa4 --- /dev/null +++ b/jsonb/.gitignore @@ -0,0 +1,12 @@ +#folders# +.idea +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/jsonb/README.md b/jsonb/README.md new file mode 100644 index 0000000000..a638f0355c --- /dev/null +++ b/jsonb/README.md @@ -0,0 +1 @@ +## JSON B diff --git a/jsonb/pom.xml b/jsonb/pom.xml new file mode 100644 index 0000000000..c61e1ac285 --- /dev/null +++ b/jsonb/pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + + com.baeldung + json-b + 0.0.1-SNAPSHOT + jar + + json-b + json-b sample project + + + yasson + + true + + + + + org.eclipse + yasson + ${yasson.version} + + + org.glassfish + javax.json + ${javax.json.version} + + + + + johnzon + + + + org.apache.geronimo.specs + geronimo-json_1.1_spec + ${geronimo-json_1.1_spec.version} + + + org.apache.johnzon + johnzon-jsonb + ${johnzon.version} + + + + + + + javax.json.bind + javax.json.bind-api + ${jsonb-api.version} + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test + + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + + UTF-8 + UTF-8 + 1.8 + 1.8 + 1.0.0 + 5.0.0 + 2.20 + 1.0 + 1.1.3 + 1.0 + 1.0 + 1.1.2 + 4.1 + + + diff --git a/jsonb/src/main/java/com/baeldung/jsonb/Person.java b/jsonb/src/main/java/com/baeldung/jsonb/Person.java new file mode 100644 index 0000000000..7a54b37574 --- /dev/null +++ b/jsonb/src/main/java/com/baeldung/jsonb/Person.java @@ -0,0 +1,127 @@ +package com.baeldung.jsonb; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import javax.json.bind.annotation.JsonbDateFormat; +import javax.json.bind.annotation.JsonbNumberFormat; +import javax.json.bind.annotation.JsonbProperty; +import javax.json.bind.annotation.JsonbTransient; + +public class Person { + + private int id; + @JsonbProperty("person-name") + private String name; + @JsonbProperty(nillable = true) + private String email; + @JsonbTransient + private int age; + @JsonbDateFormat("dd-MM-yyyy") + private LocalDate registeredDate; + private BigDecimal salary; + + public Person() { + } + + public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) { + super(); + this.id = id; + this.name = name; + this.email = email; + this.age = age; + this.registeredDate = registeredDate; + this.salary = salary; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @JsonbNumberFormat(locale = "en_US", value = "#0.0") + public BigDecimal getSalary() { + return salary; + } + + public void setSalary(BigDecimal salary) { + this.salary = salary; + } + + public LocalDate getRegisteredDate() { + return registeredDate; + } + + public void setRegisteredDate(LocalDate registeredDate) { + this.registeredDate = registeredDate; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append(", age="); + builder.append(age); + builder.append(", registeredDate="); + builder.append(registeredDate); + builder.append(", salary="); + builder.append(salary); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Person other = (Person) obj; + if (id != other.id) + return false; + return true; + } + +} diff --git a/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java b/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java new file mode 100644 index 0000000000..92ffe0aa6f --- /dev/null +++ b/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java @@ -0,0 +1,158 @@ +package com.baeldung.jsonb; + +import static org.junit.Assert.assertTrue; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.json.bind.Jsonb; +import javax.json.bind.JsonbBuilder; +import javax.json.bind.JsonbConfig; +import javax.json.bind.config.PropertyNamingStrategy; +import javax.json.bind.config.PropertyOrderStrategy; + +import org.apache.commons.collections4.ListUtils; +import org.junit.Test; + +public class JsonbTest { + + @Test + public void givenPersonList_whenSerializeWithJsonb_thenGetPersonJsonArray() { + Jsonb jsonb = JsonbBuilder.create(); + // @formatter:off + List personList = Arrays.asList( + new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); + // @formatter:on + String jsonArrayPerson = jsonb.toJson(personList); + // @formatter:off + String jsonExpected = "[" + + "{\"email\":\"jhon@test.com\"," + + "\"id\":1,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"jhon1@test.com\"," + + "\"id\":2,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"},{\"email\":null," + + "\"id\":3,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"tom@test.com\"," + + "\"id\":4,\"person-name\":\"Tom\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"}" + + "]"; + // @formatter:on + assertTrue(jsonArrayPerson.equals(jsonExpected)); + } + + @Test + public void givenPersonJsonArray_whenDeserializeWithJsonb_thenGetPersonList() { + Jsonb jsonb = JsonbBuilder.create(); + // @formatter:off + String personJsonArray = + "[" + + "{\"email\":\"jhon@test.com\"," + + "\"id\":1,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"jhon1@test.com\"," + + "\"id\":2,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"},{\"email\":null," + + "\"id\":3,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"tom@test.com\"," + + "\"id\":4,\"person-name\":\"Tom\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"}" + + "]"; + // @formatter:on + @SuppressWarnings("serial") + List personList = jsonb.fromJson(personJsonArray, new ArrayList() { + }.getClass() + .getGenericSuperclass()); + // @formatter:off + List personListExpected = Arrays.asList( + new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); + // @formatter:on + assertTrue(ListUtils.isEqualList(personList, personListExpected)); + } + + @Test + public void givenPersonObject_whenNamingStrategy_thenGetCustomPersonJson() { + JsonbConfig config = new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registered_date\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonObject_whenWithPropertyOrderStrategy_thenGetReversePersonJson() { + JsonbConfig config = new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"salary\":\"1000.0\","+ + "\"registeredDate\":\"07-09-2019\"," + + "\"person-name\":\"Jhon\"," + + "\"id\":1," + + "\"email\":\"jhon@test.com\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { + Jsonb jsonb = JsonbBuilder.create(); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { + Jsonb jsonb = JsonbBuilder.create(); + Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); + // @formatter:off + String jsonPerson = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonb.fromJson(jsonPerson, Person.class) + .equals(person)); + } + +} diff --git a/libraries-data/file.dat b/libraries-data/file.dat new file mode 100644 index 0000000000..70177cef97 Binary files /dev/null and b/libraries-data/file.dat differ diff --git a/libraries/README.md b/libraries/README.md index c6bbb5634c..1b6cbf2735 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -39,7 +39,6 @@ - [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) - [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) - [Introduction to NoException](http://www.baeldung.com/no-exception) -- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java) - [Apache Commons IO](http://www.baeldung.com/apache-commons-io) - [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types) - [Introduction to javax.measure](http://www.baeldung.com/javax-measure) @@ -53,7 +52,11 @@ - [Using Pairs in Java](http://www.baeldung.com/java-pairs) - [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag) - [Introduction to Caffeine](http://www.baeldung.com/java-caching-caffeine) -+-[Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) +- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) +- [Introduction To Docx4J](http://www.baeldung.com/docx4j) +- [Introduction to StreamEx](http://www.baeldung.com/streamex) +- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) +- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 25c1113fea..546fe8a6d8 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -622,6 +622,21 @@ bcpkix-jdk15on 1.58 + + com.google.http-client + google-http-client + ${googleclient.version} + + + com.google.http-client + google-http-client-jackson2 + ${googleclient.version} + + + com.google.http-client + google-http-client-gson + ${googleclient.version} +
@@ -639,6 +654,7 @@ + 1.23.0 0.1.0 0.7.0 3.2.4 diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java new file mode 100644 index 0000000000..0618a7294d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java @@ -0,0 +1,65 @@ +package com.baeldung.googlehttpclientguide; + +import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; +import com.google.api.client.http.HttpRequest; +import com.google.api.client.http.HttpRequestFactory; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.apache.ApacheHttpTransport; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.JsonObjectParser; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.client.util.ExponentialBackOff; +import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class GitHubExample { + static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); + //static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport(); + static final JsonFactory JSON_FACTORY = new JacksonFactory(); + //static final JsonFactory JSON_FACTORY = new GsonFactory(); + + private static void run() throws Exception { + HttpRequestFactory requestFactory + = HTTP_TRANSPORT.createRequestFactory( + (HttpRequest request) -> { + request.setParser(new JsonObjectParser(JSON_FACTORY)); + }); + GitHubUrl url = new GitHubUrl("https://api.github.com/users"); + url.per_page = 10; + url.page = 1; + HttpRequest request = requestFactory.buildGetRequest(url); + ExponentialBackOff backoff = new ExponentialBackOff.Builder() + .setInitialIntervalMillis(500) + .setMaxElapsedTimeMillis(900000) + .setMaxIntervalMillis(6000) + .setMultiplier(1.5) + .setRandomizationFactor(0.5) + .build(); + request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff)); + Type type = new TypeToken>() {}.getType(); + List users = (List)request.execute().parseAs(type); + System.out.println(users); + url.appendRawPath("/eugenp"); + request = requestFactory.buildGetRequest(url); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future responseFuture = request.executeAsync(executor); + User eugen = responseFuture.get().parseAs(User.class); + System.out.println(eugen); + executor.shutdown(); + } + + public static void main(String[] args) { + try { + run(); + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } +} diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java new file mode 100644 index 0000000000..c44de1e145 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java @@ -0,0 +1,18 @@ +package com.baeldung.googlehttpclientguide; + +import com.google.api.client.http.GenericUrl; +import com.google.api.client.util.Key; + +public class GitHubUrl extends GenericUrl{ + + public GitHubUrl(String encodedUrl) { + super(encodedUrl); + } + + @Key + public int per_page; + + @Key + public int page; + +} diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java new file mode 100644 index 0000000000..bf4ee96b25 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java @@ -0,0 +1,77 @@ +package com.baeldung.googlehttpclientguide; + +import com.google.api.client.json.GenericJson; +import com.google.api.client.util.Key; + +public class User extends GenericJson { + @Key + private String login; + @Key + private long id; + @Key + private String url; + @Key + private String company; + @Key + private String blog; + @Key + private String email; + + @Key("subscriptions_url") + private String subscriptionsUrl; + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getBlog() { + return blog; + } + + public void setBlog(String blog) { + this.blog = blog; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; + } + + +} diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties b/libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties new file mode 100644 index 0000000000..02489378df --- /dev/null +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties @@ -0,0 +1,10 @@ +# Properties file which configures the operation of the JDK logging facility. +# The system will look for this config file to be specified as a system property: +# -Djava.util.logging.config.file=${project_loc:dailymotion-simple-cmdline-sample}/logging.properties + +# Set up the console handler (uncomment "level" to show more fine-grained messages) +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = ALL + +# Set up logging of HTTP requests and responses (uncomment "level" to show) +com.google.api.client.http.level = ALL diff --git a/logging-modules/README.md b/logging-modules/README.md new file mode 100644 index 0000000000..23458cf30b --- /dev/null +++ b/logging-modules/README.md @@ -0,0 +1,3 @@ + +## Logging Modules + diff --git a/log-mdc/README.md b/logging-modules/log-mdc/README.md similarity index 100% rename from log-mdc/README.md rename to logging-modules/log-mdc/README.md diff --git a/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml similarity index 98% rename from log-mdc/pom.xml rename to logging-modules/log-mdc/pom.xml index e91d4e231e..918e052a15 100644 --- a/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/log-mdc/src/main/java/com/baeldung/config/AppConfiguration.java b/logging-modules/log-mdc/src/main/java/com/baeldung/config/AppConfiguration.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/config/AppConfiguration.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/config/AppConfiguration.java diff --git a/log-mdc/src/main/java/com/baeldung/config/AppInitializer.java b/logging-modules/log-mdc/src/main/java/com/baeldung/config/AppInitializer.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/config/AppInitializer.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/config/AppInitializer.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/Transfer.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/Transfer.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/Transfer.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/Transfer.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/TransferService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransferService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/TransferService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransferService.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/Investment.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/Investment.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/Investment.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/Investment.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/controller/JBossLoggingController.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/JBossLoggingController.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/controller/JBossLoggingController.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/JBossLoggingController.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4J2Controller.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4J2Controller.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/controller/Log4J2Controller.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4J2Controller.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4JController.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4JController.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/controller/Log4JController.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4JController.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/service/InvestmentService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/InvestmentService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/service/InvestmentService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/InvestmentService.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/service/JBossLoggingInvestmentService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/JBossLoggingInvestmentService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/service/JBossLoggingInvestmentService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/JBossLoggingInvestmentService.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/service/Log4J2InvestmentService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/Log4J2InvestmentService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/service/Log4J2InvestmentService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/Log4J2InvestmentService.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/service/Log4JInvestmentService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/Log4JInvestmentService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/service/Log4JInvestmentService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/Log4JInvestmentService.java diff --git a/log-mdc/src/main/resources/log4j.properties b/logging-modules/log-mdc/src/main/resources/log4j.properties similarity index 100% rename from log-mdc/src/main/resources/log4j.properties rename to logging-modules/log-mdc/src/main/resources/log4j.properties diff --git a/log-mdc/src/main/resources/log4j2.xml b/logging-modules/log-mdc/src/main/resources/log4j2.xml similarity index 100% rename from log-mdc/src/main/resources/log4j2.xml rename to logging-modules/log-mdc/src/main/resources/log4j2.xml diff --git a/log-mdc/src/main/resources/logback.xml b/logging-modules/log-mdc/src/main/resources/logback.xml similarity index 100% rename from log-mdc/src/main/resources/logback.xml rename to logging-modules/log-mdc/src/main/resources/logback.xml diff --git a/log-mdc/src/test/java/com/baeldung/mdc/log4j/DemoIntegrationTest.java b/logging-modules/log-mdc/src/test/java/com/baeldung/mdc/log4j/DemoIntegrationTest.java similarity index 100% rename from log-mdc/src/test/java/com/baeldung/mdc/log4j/DemoIntegrationTest.java rename to logging-modules/log-mdc/src/test/java/com/baeldung/mdc/log4j/DemoIntegrationTest.java diff --git a/log-mdc/src/test/java/com/baeldung/mdc/log4j2/DemoIntegrationTest.java b/logging-modules/log-mdc/src/test/java/com/baeldung/mdc/log4j2/DemoIntegrationTest.java similarity index 100% rename from log-mdc/src/test/java/com/baeldung/mdc/log4j2/DemoIntegrationTest.java rename to logging-modules/log-mdc/src/test/java/com/baeldung/mdc/log4j2/DemoIntegrationTest.java diff --git a/log-mdc/src/test/java/com/baeldung/mdc/slf4j/DemoIntegrationTest.java b/logging-modules/log-mdc/src/test/java/com/baeldung/mdc/slf4j/DemoIntegrationTest.java similarity index 100% rename from log-mdc/src/test/java/com/baeldung/mdc/slf4j/DemoIntegrationTest.java rename to logging-modules/log-mdc/src/test/java/com/baeldung/mdc/slf4j/DemoIntegrationTest.java diff --git a/log-mdc/src/test/java/com/baeldung/ndc/NDCLogIntegrationTest.java b/logging-modules/log-mdc/src/test/java/com/baeldung/ndc/NDCLogIntegrationTest.java similarity index 100% rename from log-mdc/src/test/java/com/baeldung/ndc/NDCLogIntegrationTest.java rename to logging-modules/log-mdc/src/test/java/com/baeldung/ndc/NDCLogIntegrationTest.java diff --git a/log4j/README.md b/logging-modules/log4j/README.md similarity index 100% rename from log4j/README.md rename to logging-modules/log4j/README.md diff --git a/log4j/pom.xml b/logging-modules/log4j/pom.xml similarity index 96% rename from log4j/pom.xml rename to logging-modules/log4j/pom.xml index 20906c4c05..a3bfb0a33a 100644 --- a/log4j/pom.xml +++ b/logging-modules/log4j/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/log4j/src/main/java/com/baeldung/log4j/Log4jExample.java b/logging-modules/log4j/src/main/java/com/baeldung/log4j/Log4jExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/log4j/Log4jExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/log4j/Log4jExample.java diff --git a/log4j/src/main/java/com/baeldung/log4j/Log4jRollingExample.java b/logging-modules/log4j/src/main/java/com/baeldung/log4j/Log4jRollingExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/log4j/Log4jRollingExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/log4j/Log4jRollingExample.java diff --git a/log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java b/logging-modules/log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java similarity index 100% rename from log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java rename to logging-modules/log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java diff --git a/log4j/src/main/java/com/baeldung/log4j2/Log4j2RollingExample.java b/logging-modules/log4j/src/main/java/com/baeldung/log4j2/Log4j2RollingExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/log4j2/Log4j2RollingExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/log4j2/Log4j2RollingExample.java diff --git a/log4j/src/main/java/com/baeldung/logback/LogbackExample.java b/logging-modules/log4j/src/main/java/com/baeldung/logback/LogbackExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/logback/LogbackExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/logback/LogbackExample.java diff --git a/log4j/src/main/java/com/baeldung/logback/LogbackRollingExample.java b/logging-modules/log4j/src/main/java/com/baeldung/logback/LogbackRollingExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/logback/LogbackRollingExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/logback/LogbackRollingExample.java diff --git a/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java b/logging-modules/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java diff --git a/log4j/src/main/java/com/baeldung/slf4j/Slf4jRollingExample.java b/logging-modules/log4j/src/main/java/com/baeldung/slf4j/Slf4jRollingExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/slf4j/Slf4jRollingExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/slf4j/Slf4jRollingExample.java diff --git a/log4j/src/main/resources/log4j.xml b/logging-modules/log4j/src/main/resources/log4j.xml similarity index 100% rename from log4j/src/main/resources/log4j.xml rename to logging-modules/log4j/src/main/resources/log4j.xml diff --git a/log4j/src/main/resources/log4j2.xml b/logging-modules/log4j/src/main/resources/log4j2.xml similarity index 100% rename from log4j/src/main/resources/log4j2.xml rename to logging-modules/log4j/src/main/resources/log4j2.xml diff --git a/log4j/src/main/resources/logback.xml b/logging-modules/log4j/src/main/resources/logback.xml similarity index 100% rename from log4j/src/main/resources/logback.xml rename to logging-modules/log4j/src/main/resources/logback.xml diff --git a/log4j2/README.md b/logging-modules/log4j2/README.md similarity index 100% rename from log4j2/README.md rename to logging-modules/log4j2/README.md diff --git a/log4j2/pom.xml b/logging-modules/log4j2/pom.xml similarity index 98% rename from log4j2/pom.xml rename to logging-modules/log4j2/pom.xml index ea398af845..58bc4b74e7 100644 --- a/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -9,7 +9,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - .. + ../ diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java similarity index 100% rename from log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java similarity index 100% rename from log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java similarity index 100% rename from log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java diff --git a/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml b/logging-modules/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml similarity index 100% rename from log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml rename to logging-modules/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml diff --git a/log4j2/src/test/resources/log4j2.xml b/logging-modules/log4j2/src/test/resources/log4j2.xml similarity index 100% rename from log4j2/src/test/resources/log4j2.xml rename to logging-modules/log4j2/src/test/resources/log4j2.xml diff --git a/lucene/pom.xml b/lucene/pom.xml new file mode 100644 index 0000000000..42b81a7d4a --- /dev/null +++ b/lucene/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + lucene + 0.0.1-SNAPSHOT + lucene + An Apache Lucene demo application + + + + + org.apache.lucene + lucene-core + 7.1.0 + + + + org.apache.lucene + lucene-queryparser + 7.1.0 + + + + junit + junit + 4.12 + test + + + + + \ No newline at end of file diff --git a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java new file mode 100644 index 0000000000..40a35fad86 --- /dev/null +++ b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java @@ -0,0 +1,78 @@ +package com.baeldung.lucene; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.TextField; +import org.apache.lucene.index.DirectoryReader; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.queryparser.classic.ParseException; +import org.apache.lucene.queryparser.classic.QueryParser; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.TopDocs; +import org.apache.lucene.store.Directory; + +public class InMemoryLuceneIndex { + + private Directory memoryIndex; + private StandardAnalyzer analyzer; + + public InMemoryLuceneIndex(Directory memoryIndex, StandardAnalyzer analyzer) { + super(); + this.memoryIndex = memoryIndex; + this.analyzer = analyzer; + } + + /** + * + * @param title + * @param body + */ + public void indexDocument(String title, String body) { + + IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); + try { + IndexWriter writter = new IndexWriter(memoryIndex, indexWriterConfig); + Document document = new Document(); + + document.add(new TextField("title", title, Field.Store.YES)); + document.add(new TextField("body", body, Field.Store.YES)); + + writter.addDocument(document); + writter.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public List searchIndex(String inField, String queryString) { + try { + Query query = new QueryParser(inField, analyzer).parse(queryString); + + IndexReader indexReader = DirectoryReader.open(memoryIndex); + IndexSearcher searcher = new IndexSearcher(indexReader); + TopDocs topDocs = searcher.search(query, 10); + List documents = new ArrayList<>(); + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { + documents.add(searcher.doc(scoreDoc.doc)); + } + + return documents; + } catch (IOException | ParseException e) { + e.printStackTrace(); + } + return null; + + } + +} + + diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java new file mode 100644 index 0000000000..c3a498a4b8 --- /dev/null +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java @@ -0,0 +1,23 @@ +package com.baeldung.lucene; + +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.store.RAMDirectory; +import org.junit.Assert; +import org.junit.Test; + +public class LuceneInMemorySearchTest { + + @Test + public void givenSearchQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Hello world", "Some hello world "); + + List documents = inMemoryLuceneIndex.searchIndex("body", "world"); + + Assert.assertEquals("Hello world", documents.get(0).get("title")); + } + +} diff --git a/metrics/README.md b/metrics/README.md index 09fe925604..c7772bffa0 100644 --- a/metrics/README.md +++ b/metrics/README.md @@ -2,3 +2,4 @@ - [Intro to Dropwizard Metrics](http://www.baeldung.com/dropwizard-metrics) - [Introduction to Netflix Servo](http://www.baeldung.com/netflix-servo) +- [Quick Guide to Micrometer](http://www.baeldung.com/micrometer) diff --git a/osgi/osgi-intro-sample-activator/pom.xml b/osgi/osgi-intro-sample-activator/pom.xml new file mode 100644 index 0000000000..1584913627 --- /dev/null +++ b/osgi/osgi-intro-sample-activator/pom.xml @@ -0,0 +1,55 @@ + + + + + + osgi-intro + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + + bundle + + osgi-intro-sample-activator + + + + org.osgi + org.osgi.core + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.groupId}.${project.artifactId} + ${project.artifactId} + ${project.version} + + + com.baeldung.osgi.sample.activator.HelloWorld + + + + com.baeldung.osgi.sample.activator + + + + + + + + diff --git a/osgi/osgi-intro-sample-activator/src/main/java/com/baeldung/osgi/sample/activator/HelloWorld.java b/osgi/osgi-intro-sample-activator/src/main/java/com/baeldung/osgi/sample/activator/HelloWorld.java new file mode 100644 index 0000000000..72fe624bac --- /dev/null +++ b/osgi/osgi-intro-sample-activator/src/main/java/com/baeldung/osgi/sample/activator/HelloWorld.java @@ -0,0 +1,16 @@ +package com.baeldung.osgi.sample.activator; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +public class HelloWorld implements BundleActivator { + + public void start(BundleContext ctx) { + System.out.println("Hello World."); + } + + public void stop(BundleContext bundleContext) { + System.out.println("Goodbye World."); + } + +} \ No newline at end of file diff --git a/osgi/osgi-intro-sample-client/pom.xml b/osgi/osgi-intro-sample-client/pom.xml new file mode 100644 index 0000000000..4096674d7d --- /dev/null +++ b/osgi/osgi-intro-sample-client/pom.xml @@ -0,0 +1,49 @@ + + + + osgi-intro + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + + osgi-intro-sample-client + + bundle + + + + com.baeldung + osgi-intro-sample-service + 1.0-SNAPSHOT + + + org.osgi + org.osgi.core + + + + + + + org.apache.felix + maven-bundle-plugin + + + ${project.groupId}.${project.artifactId} + ${project.artifactId} + ${project.version} + com.baeldung.osgi.sample.client.Client + + com.baeldung.osgi.sample.client + + + + + + + + \ No newline at end of file diff --git a/osgi/osgi-intro-sample-client/src/main/java/com/baeldung/osgi/sample/client/Client.java b/osgi/osgi-intro-sample-client/src/main/java/com/baeldung/osgi/sample/client/Client.java new file mode 100644 index 0000000000..a82ed63fa7 --- /dev/null +++ b/osgi/osgi-intro-sample-client/src/main/java/com/baeldung/osgi/sample/client/Client.java @@ -0,0 +1,44 @@ +package com.baeldung.osgi.sample.client; + +import com.baeldung.osgi.sample.service.definition.Greeter; +import org.osgi.framework.*; + +public class Client implements BundleActivator, ServiceListener { + + private BundleContext ctx; + private ServiceReference serviceReference; + + public void start(BundleContext ctx) { + this.ctx = ctx; + try { + ctx.addServiceListener(this, "(objectclass=" + Greeter.class.getName() + ")"); + } catch (InvalidSyntaxException ise) { + ise.printStackTrace(); + } + } + + public void stop(BundleContext bundleContext) { + if (serviceReference != null) { + ctx.ungetService(serviceReference); + } + this.ctx = null; + } + + public void serviceChanged(ServiceEvent serviceEvent) { + int type = serviceEvent.getType(); + switch (type) { + case (ServiceEvent.REGISTERED): + System.out.println("Notification of service registered."); + serviceReference = serviceEvent.getServiceReference(); + Greeter service = (Greeter) (ctx.getService(serviceReference)); + System.out.println(service.sayHiTo("John")); + break; + case (ServiceEvent.UNREGISTERING): + System.out.println("Notification of service unregistered."); + ctx.ungetService(serviceEvent.getServiceReference()); + break; + default: + break; + } + } +} diff --git a/osgi/osgi-intro-sample-service/pom.xml b/osgi/osgi-intro-sample-service/pom.xml new file mode 100644 index 0000000000..cbc660bb74 --- /dev/null +++ b/osgi/osgi-intro-sample-service/pom.xml @@ -0,0 +1,46 @@ + + + + + + osgi-intro + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + osgi-intro-sample-service + + + bundle + + + + org.osgi + org.osgi.core + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.groupId}.${project.artifactId} + ${project.artifactId} + ${project.version} + com.baeldung.osgi.sample.service.implementation.GreeterImpl + com.baeldung.osgi.sample.service.implementation + com.baeldung.osgi.sample.service.definition + + + + + + + \ No newline at end of file diff --git a/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/definition/Greeter.java b/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/definition/Greeter.java new file mode 100644 index 0000000000..f1e82a3465 --- /dev/null +++ b/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/definition/Greeter.java @@ -0,0 +1,7 @@ +package com.baeldung.osgi.sample.service.definition; + +public interface Greeter { + + public String sayHiTo(String name); + +} diff --git a/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/implementation/GreeterImpl.java b/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/implementation/GreeterImpl.java new file mode 100644 index 0000000000..48e26e3e6b --- /dev/null +++ b/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/implementation/GreeterImpl.java @@ -0,0 +1,30 @@ +package com.baeldung.osgi.sample.service.implementation; + +import com.baeldung.osgi.sample.service.definition.Greeter; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.ServiceRegistration; + +import java.util.Hashtable; + +public class GreeterImpl implements Greeter, BundleActivator { + + private ServiceReference reference; + private ServiceRegistration registration; + + @Override public String sayHiTo(String name) { + return "Hello " + name; + } + + @Override public void start(BundleContext context) throws Exception { + System.out.println("Registering service."); + registration = context.registerService(Greeter.class, new GreeterImpl(), new Hashtable()); + reference = registration.getReference(); + } + + @Override public void stop(BundleContext context) throws Exception { + System.out.println("Unregistering service."); + registration.unregister(); + } +} diff --git a/osgi/pom.xml b/osgi/pom.xml new file mode 100644 index 0000000000..4298a0d3eb --- /dev/null +++ b/osgi/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + osgi-intro + pom + 1.0-SNAPSHOT + + osgi-intro-sample-activator + osgi-intro-sample-service + osgi-intro-sample-client + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + + + + ${project.groupId} + osgi-intro-client + ${project.version} + + + + ${project.groupId} + osgi-intro-service + ${project.version} + + + + ${project.groupId} + osgi-intro-gxyz + ${project.version} + + + + ${project.groupId} + osgi-intro-mapquest + ${project.version} + + + + com.squareup.okhttp3 + okhttp + 3.9.0 + + + javax.json + javax.json-api + 1.1 + + + org.glassfish + javax.json + 1.1 + + + org.osgi + org.osgi.core + 5.0.0 + provided + + + + + + + + + org.apache.felix + maven-bundle-plugin + 1.4.0 + true + + + + + + \ No newline at end of file diff --git a/osgi/readme.md b/osgi/readme.md new file mode 100644 index 0000000000..ea4a411c7b --- /dev/null +++ b/osgi/readme.md @@ -0,0 +1,91 @@ +OSGi +==== + +Info +--- + +com.baeldung.osgi +com.baeldung.osgi.sample.activator + +Apache Felix +--- + + +### Start + +Download Apache Felix Framework Distribution +from +org.apache.felix.main.distribution-5.6.8 + +No! The Apache Karaf container is best. +Download it from: + +Download a binary distribution and unzip wherever you prefer. + +Then run + + bin\karaf.bat start + + +Unzip, pay attention to the files not being clipped(!). + + system:exit + +exit! + + shutdown -h + +or `^D` + +### clean start + +full clean, remove "data directory " + +or... + + bin\karaf.bat clean + + bin\start.bat clean + +### run mode + +can be launched in + +- the "regular" mode starts Apache Karaf in foreground, including the shell console. +- the "server" mode starts Apache Karaf in foreground, without the shell console. +- the "background" mode starts Apache Karaf in background. + +### Logging + +https://karaf.apache.org/manual/latest/#_log + +can be logged to console + + +### Bundle deploy + + bundle:install mvn:com.baeldung/osgi-intro-sample-activator/1.0-SNAPSHOT + + install mvn:com.baeldung/osgi-intro-sample-service/1.0-SNAPSHOT + install mvn:com.baeldung/osgi-intro-sample-client/1.0-SNAPSHOT + +Eclipse's Equinox +==== + +Eclipse's OSGi platform +http://www.eclipse.org/equinox/ + +http://www.eclipse.org/equinox/documents/quickstart-framework.php + +click on "download" + +Latest Release +Oxygen.1 Wed, 6 Sep 2017 -- 17:00 (-0400) + +org.eclipse.osgi_3.12.1.v20170821-1548.jar + + = = NOT GOOD = = + + + + diff --git a/patterns/README.md b/patterns/README.md index bcd54a64b1..67d84154cb 100644 --- a/patterns/README.md +++ b/patterns/README.md @@ -1,3 +1,4 @@ ###Relevant Articles: - [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) - [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) +- [Implementing the Template Method Pattern in Java](http://www.baeldung.com/template-method-pattern-in-java) diff --git a/patterns/pom.xml b/patterns/pom.xml index c40d7c58b7..68e5316f64 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -9,6 +9,7 @@ front-controller intercepting-filter + template-method @@ -51,4 +52,4 @@ 3.0.0 9.4.0.v20161208 - + \ No newline at end of file diff --git a/patterns/template-method/pom.xml b/patterns/template-method/pom.xml index c3b6a084ac..4b863fe0a4 100644 --- a/patterns/template-method/pom.xml +++ b/patterns/template-method/pom.xml @@ -1,15 +1,17 @@ 4.0.0 - com.baeldung.templatemethodpattern - templatemethodpattern + com.baeldung.templatemethod + template-method 1.0 jar - - UTF-8 - 1.8 - 1.8 - + + com.baeldung.patterns + patterns-parent + 1.0.0-SNAPSHOT + .. + + junit @@ -18,4 +20,18 @@ test + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + + + + UTF-8 + 1.8 + 1.8 + \ No newline at end of file diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java index 581c774f52..bd383b4568 100644 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java @@ -1,18 +1,21 @@ package com.baeldung.templatemethodpattern.application; import com.baeldung.templatemethodpattern.model.Computer; -import com.baeldung.templatemethodpattern.model.HighEndComputer; import com.baeldung.templatemethodpattern.model.StandardComputer; +import com.baeldung.templatemethodpattern.model.HighEndComputer; +import com.baeldung.templatemethodpattern.model.ComputerBuilder; +import com.baeldung.templatemethodpattern.model.HighEndComputerBuilder; +import com.baeldung.templatemethodpattern.model.StandardComputerBuilder; public class Application { public static void main(String[] args) { - Computer standardComputer = new StandardComputer(); - standardComputer.buildComputer(); + ComputerBuilder standardComputerBuilder = new StandardComputerBuilder(); + Computer standardComputer = standardComputerBuilder.buildComputer(); standardComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v)); - Computer highEndComputer = new HighEndComputer(); - highEndComputer.buildComputer(); + ComputerBuilder highEndComputerBuilder = new HighEndComputerBuilder(); + Computer highEndComputer = highEndComputerBuilder.buildComputer(); highEndComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v)); } } diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java index c5d1a2cde8..128eec59ad 100644 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java @@ -2,33 +2,18 @@ package com.baeldung.templatemethodpattern.model; import java.util.HashMap; import java.util.Map; +import java.util.ArrayList; +import java.util.List; -public abstract class Computer { +public class Computer { - protected Map computerParts = new HashMap<>(); + private Map computerParts = new HashMap<>(); - public final void buildComputer() { - addMotherboard(); - addProcessor(); - addMemory(); - addHardDrive(); - addGraphicCard(); - addSoundCard(); + public Computer(Map computerParts) { + this.computerParts = computerParts; } - public abstract void addProcessor(); - - public abstract void addMotherboard(); - - public abstract void addMemory(); - - public abstract void addHardDrive(); - - public abstract void addGraphicCard(); - - public abstract void addSoundCard(); - public Map getComputerParts() { return computerParts; - } + } } diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/ComputerBuilder.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/ComputerBuilder.java new file mode 100644 index 0000000000..39052f4776 --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/ComputerBuilder.java @@ -0,0 +1,37 @@ +package com.baeldung.templatemethodpattern.model; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class ComputerBuilder { + + protected Map computerParts = new HashMap<>(); + protected List motherboardSetupStatus = new ArrayList<>(); + + public final Computer buildComputer() { + addMotherboard(); + setupMotherboard(); + addProcessor(); + return getComputer(); + } + + public abstract void addMotherboard(); + + public abstract void setupMotherboard(); + + public abstract void addProcessor(); + + public List getMotherboardSetupStatus() { + return motherboardSetupStatus; + } + + public Map getComputerParts() { + return computerParts; + } + + private Computer getComputer() { + return new Computer(computerParts); + } +} diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java index 11baeca6f7..16d89f1ad6 100644 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java @@ -1,34 +1,10 @@ package com.baeldung.templatemethodpattern.model; +import java.util.Map; + public class HighEndComputer extends Computer { - - @Override - public void addProcessor() { - computerParts.put("Processor", "High End Processor"); - } - - @Override - public void addMotherboard() { - computerParts.put("Motherboard", "High End Motherboard"); - } - - @Override - public void addMemory() { - computerParts.put("Memory", "16GB"); - } - - @Override - public void addHardDrive() { - computerParts.put("Hard Drive", "2TB Hard Drive"); - } - - @Override - public void addGraphicCard() { - computerParts.put("Graphic Card", "High End Graphic Card"); - } - - @Override - public void addSoundCard() { - computerParts.put("Sound Card", "High End Sound Card"); - } + + public HighEndComputer(Map computerParts) { + super(computerParts); + } } diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputerBuilder.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputerBuilder.java new file mode 100644 index 0000000000..baa800ca8f --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputerBuilder.java @@ -0,0 +1,21 @@ +package com.baeldung.templatemethodpattern.model; + +public class HighEndComputerBuilder extends ComputerBuilder { + + @Override + public void addMotherboard() { + computerParts.put("Motherboard", "High-end Motherboard"); + } + + @Override + public void setupMotherboard() { + motherboardSetupStatus.add("Screwing the high-end motherboard to the case."); + motherboardSetupStatus.add("Pluging in the power supply connectors."); + motherboardSetupStatus.forEach(step -> System.out.println(step)); + } + + @Override + public void addProcessor() { + computerParts.put("Processor", "High-end Processor"); + } +} diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java index 22ff370203..14d32d7b64 100644 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java @@ -1,34 +1,10 @@ package com.baeldung.templatemethodpattern.model; - + +import java.util.Map; + public class StandardComputer extends Computer { - - @Override - public void addProcessor() { - computerParts.put("Processor", "Standard Processor"); - } - - @Override - public void addMotherboard() { - computerParts.put("Motherboard", "Standard Motherboard"); - } - - @Override - public void addMemory() { - computerParts.put("Memory", "8GB"); - } - - @Override - public void addHardDrive() { - computerParts.put("Hard Drive", "1TB Hard Drive"); - } - - @Override - public void addGraphicCard() { - computerParts.put("Graphic Card", "Standard Graphic Card"); - } - - @Override - public void addSoundCard() { - computerParts.put("Sound Card", "Standard Sound Card"); - } + + public StandardComputer(Map computerParts) { + super(computerParts); + } } diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputerBuilder.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputerBuilder.java new file mode 100644 index 0000000000..78547dc38b --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputerBuilder.java @@ -0,0 +1,21 @@ +package com.baeldung.templatemethodpattern.model; + +public class StandardComputerBuilder extends ComputerBuilder { + + @Override + public void addMotherboard() { + computerParts.put("Motherboard", "Standard Motherboard"); + } + + @Override + public void setupMotherboard() { + motherboardSetupStatus.add("Screwing the standard motherboard to the case."); + motherboardSetupStatus.add("Pluging in the power supply connectors."); + motherboardSetupStatus.forEach(step -> System.out.println(step)); + } + + @Override + public void addProcessor() { + computerParts.put("Processor", "Standard Processor"); + } +} diff --git a/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java b/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java index afe66883ac..1d608ff2c2 100644 --- a/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java +++ b/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java @@ -1,120 +1,89 @@ package com.baeldung.templatemethodpatterntest; +import com.baeldung.templatemethodpattern.model.Computer; +import com.baeldung.templatemethodpattern.model.HighEndComputerBuilder; +import com.baeldung.templatemethodpattern.model.StandardComputerBuilder; import com.baeldung.templatemethodpattern.model.HighEndComputer; import com.baeldung.templatemethodpattern.model.StandardComputer; import org.junit.Assert; +import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertThat; public class TemplateMethodPatternTest { - - private static StandardComputer standardComputer; - private static HighEndComputer highEndComputer; - + + private static StandardComputerBuilder standardComputerBuilder; + private static HighEndComputerBuilder highEndComputerBuilder; + @BeforeClass - public static void setUpStandardComputerInstance() { - standardComputer = new StandardComputer(); + public static void setUpStandardComputerBuilderInstance() { + standardComputerBuilder = new StandardComputerBuilder(); } - + @BeforeClass - public static void setUpHighEndComputerInstance() { - highEndComputer = new HighEndComputer(); + public static void setUpHighEndComputerBuilderInstance() { + highEndComputerBuilder = new HighEndComputerBuilder(); } - - @Test - public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() { - standardComputer.addProcessor(); - Assert.assertEquals("Standard Processor", standardComputer - .getComputerParts().get("Processor")); - } - + @Test public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { - standardComputer.addMotherboard(); - Assert.assertEquals("Standard Motherboard", standardComputer - .getComputerParts().get("Motherboard")); + standardComputerBuilder.addMotherboard(); + assertEquals("Standard Motherboard", standardComputerBuilder.getComputerParts().get("Motherboard")); + } + + @Test + public void givenStandardMotherboard_whenSetup_thenTwoEqualAssertions() { + standardComputerBuilder.setupMotherboard(); + assertEquals("Screwing the standard motherboard to the case.", standardComputerBuilder.getMotherboardSetupStatus().get(0)); + assertEquals("Pluging in the power supply connectors.", standardComputerBuilder.getMotherboardSetupStatus().get(1)); + } + + @Test + public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() { + standardComputerBuilder.addProcessor(); + assertEquals("Standard Processor", standardComputerBuilder.getComputerParts().get("Processor")); + } + + @Test + public void givenAllStandardParts_whenBuildingComputer_thenTwoParts() { + standardComputerBuilder.buildComputer(); + assertEquals(2, standardComputerBuilder.getComputerParts().size()); } @Test - public void givenStandardMemory_whenAddingMemory_thenEqualAssertion() { - standardComputer.addMemory(); - Assert.assertEquals("8GB", standardComputer - .getComputerParts().get("Memory")); - } - - @Test - public void givenStandardHardDrive_whenAddingHardDrive_thenEqualAssertion() { - standardComputer.addHardDrive(); - Assert.assertEquals("1TB Hard Drive", standardComputer - .getComputerParts().get("Hard Drive")); - } - - @Test - public void givenStandardGraphicaCard_whenAddingGraphicCard_thenEqualAssertion() { - standardComputer.addGraphicCard(); - Assert.assertEquals("Standard Graphic Card", standardComputer - .getComputerParts().get("Graphic Card")); - } - - @Test - public void givenStandardSoundCard_whenAddingSoundCard_thenEqualAssertion() { - standardComputer.addSoundCard(); - Assert.assertEquals("Standard Sound Card", standardComputer - .getComputerParts().get("Sound Card")); - } - - @Test - public void givenAllStandardParts_whenBuildingComputer_thenSixParts() { - standardComputer.buildComputer(); - Assert.assertEquals(6, standardComputer - .getComputerParts().size()); - } - - @Test - public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() { - highEndComputer.addProcessor(); - Assert.assertEquals("High End Processor", highEndComputer - .getComputerParts().get("Processor")); + public void givenAllStandardParts_whenComputerisBuilt_thenComputerInstance() { + assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); } @Test public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { - highEndComputer.addMotherboard(); - Assert.assertEquals("High End Motherboard", highEndComputer - .getComputerParts().get("Motherboard")); + highEndComputerBuilder.addMotherboard(); + Assert.assertEquals("High-end Motherboard", highEndComputerBuilder.getComputerParts().get("Motherboard")); + } + + @Test + public void givenHighEnddMotheroboard_whenSetup_thenTwoEqualAssertions() { + highEndComputerBuilder.setupMotherboard(); + assertEquals("Screwing the high-end motherboard to the case.", highEndComputerBuilder.getMotherboardSetupStatus().get(0)); + assertEquals("Pluging in the power supply connectors.", highEndComputerBuilder.getMotherboardSetupStatus().get(1)); + } + + @Test + public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() { + highEndComputerBuilder.addProcessor(); + assertEquals("High-end Processor", highEndComputerBuilder.getComputerParts().get("Processor")); } @Test - public void givenHighEndMemory_whenAddingMemory_thenEqualAssertion() { - highEndComputer.addMemory(); - Assert.assertEquals("16GB", highEndComputer - .getComputerParts().get("Memory")); + public void givenAllHighEnddParts_whenBuildingComputer_thenTwoParts() { + highEndComputerBuilder.buildComputer(); + assertEquals(2, highEndComputerBuilder.getComputerParts().size()); } @Test - public void givenHighEndHardDrive_whenAddingHardDrive_thenEqualAssertion() { - highEndComputer.addHardDrive(); - Assert.assertEquals("2TB Hard Drive", highEndComputer - .getComputerParts().get("Hard Drive")); + public void givenAllHighEndParts_whenComputerisBuilt_thenComputerInstance() { + assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); } - - @Test - public void givenHighEndGraphicCard_whenAddingGraphicCard_thenEqualAssertion() { - highEndComputer.addGraphicCard(); - Assert.assertEquals("High End Graphic Card", highEndComputer - .getComputerParts().get("Graphic Card")); - } - - @Test - public void givenHighEndSoundCard_whenAddingSoundCard_thenEqualAssertion() { - highEndComputer.addSoundCard(); - Assert.assertEquals("High End Sound Card", highEndComputer - .getComputerParts().get("Sound Card")); - } - - @Test - public void givenAllHighEndParts_whenBuildingComputer_thenSixParts() { - highEndComputer.buildComputer(); - Assert.assertEquals(6, highEndComputer.getComputerParts().size()); - } } diff --git a/persistence-modules/README.md b/persistence-modules/README.md new file mode 100644 index 0000000000..6c2b1d2ca9 --- /dev/null +++ b/persistence-modules/README.md @@ -0,0 +1,3 @@ + +## Persistence Modules + diff --git a/pom.xml b/pom.xml index c2dee7d2f9..20f7c4ffad 100644 --- a/pom.xml +++ b/pom.xml @@ -62,15 +62,15 @@ feign flyway - + geotools - groovy-spock + testing-modules/groovy-spock gson guava - guava18 - guava19 - guava21 + guava-modules/guava-18 + guava-modules/guava-19 + guava-modules/guava-21 guice disruptor @@ -90,7 +90,7 @@ javax-servlets javaxval jaxb - jee7 + jee-7 jjwt jpa-storedprocedure @@ -98,26 +98,27 @@ json-path json jsoup - junit5 + testing-modules/junit-5 jws libraries libraries-data linkrest - log-mdc - log4j - log4j2 + logging-modules/log-mdc + logging-modules/log4j + logging-modules/log4j2 lombok mapstruct metrics mesos-marathon - mockito - mockito2 - mocks + testing-modules/mockito + testing-modules/mockito-2 + testing-modules/mocks mustache noexception + osgi orika patterns @@ -129,13 +130,13 @@ reactor-core persistence-modules/redis - rest-assured - rest-testing + testing-modules/rest-assured + testing-modules/rest-testing resteasy rxjava spring-swagger-codegen - selenium-junit-testng + testing-modules/selenium-junit-testng persistence-modules/solr spark-java @@ -149,6 +150,7 @@ spring-batch spring-bom spring-boot + spring-boot-keycloak spring-boot-bootstrap spring-cloud-data-flow spring-cloud @@ -230,16 +232,18 @@ spring-zuul spring-reactor spring-vertx + + spring-rest-embedded-tomcat - testing - testng + testing-modules/testing + testing-modules/testng video-tutorials xml - xmlunit2 - struts2 + xmlunit-2 + struts-2 apache-velocity apache-solrj @@ -251,12 +255,13 @@ drools persistence-modules/liquibase spring-boot-property-exp - mockserver + testing-modules/mockserver undertow vertx-and-rxjava saas deeplearning4j spring-boot-admin + lucene diff --git a/rxjava/README.md b/rxjava/README.md index 71231cc391..c88ec36991 100644 --- a/rxjava/README.md +++ b/rxjava/README.md @@ -8,3 +8,4 @@ - [Observable Utility Operators in RxJava](http://www.baeldung.com/rxjava-observable-operators) - [Introduction to rxjava-jdbc](http://www.baeldung.com/rxjava-jdbc) - [Schedulers in RxJava](http://www.baeldung.com/rxjava-schedulers) +- [Mathematical and Aggregate Operators in RxJava](http://www.baeldung.com/rxjava-math) diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 4dfede4dab..7e30179f07 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M3 + 2.0.0.M6 @@ -49,6 +49,18 @@ javax.json.bind-api ${jsonb-api.version} + + + + + + + + + + + + org.apache.geronimo.specs geronimo-json_1.1_spec @@ -87,6 +99,18 @@ spring-boot-starter-test test + + org.springframework.security + spring-security-test + test + + + + org.apache.commons + commons-collections4 + 4.1 + test + org.junit.jupiter @@ -170,7 +194,7 @@ 1.0.0 5.0.0 2.20 - 5.0.0.RELEASE + 5.0.1.RELEASE 1.0.1.RELEASE 1.1.3 1.0 diff --git a/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java b/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java new file mode 100644 index 0000000000..02c91a1879 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java @@ -0,0 +1,34 @@ +package com.baeldung; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.web.reactive.config.EnableWebFlux; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import reactor.ipc.netty.NettyContext; +import reactor.ipc.netty.http.server.HttpServer; + +@ComponentScan(basePackages = {"com.baeldung.security"}) +@EnableWebFlux +public class SpringSecurity5Application { + + public static void main(String[] args) { + try (AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(SpringSecurity5Application.class)) { + context.getBean(NettyContext.class).onClose().block(); + } + } + + @Bean + public NettyContext nettyContext(ApplicationContext context) { + HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context) + .build(); + ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); + HttpServer httpServer = HttpServer.create("localhost", 8080); + return httpServer.newHandler(adapter).block(); + } + +} diff --git a/spring-5/src/main/java/com/baeldung/security/GreetController.java b/spring-5/src/main/java/com/baeldung/security/GreetController.java new file mode 100644 index 0000000000..6b69e3bc9b --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/security/GreetController.java @@ -0,0 +1,37 @@ +package com.baeldung.security; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +import java.security.Principal; + +@RestController +public class GreetController { + + private GreetService greetService; + + public GreetController(GreetService greetService) { + this.greetService = greetService; + } + + @GetMapping("/") + public Mono greet(Mono principal) { + return principal + .map(Principal::getName) + .map(name -> String.format("Hello, %s", name)); + } + + @GetMapping("/admin") + public Mono greetAdmin(Mono principal) { + return principal + .map(Principal::getName) + .map(name -> String.format("Admin access: %s", name)); + } + + @GetMapping("/greetService") + public Mono greetService() { + return greetService.greet(); + } + +} diff --git a/spring-5/src/main/java/com/baeldung/security/GreetService.java b/spring-5/src/main/java/com/baeldung/security/GreetService.java new file mode 100644 index 0000000000..7622b360be --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/security/GreetService.java @@ -0,0 +1,15 @@ +package com.baeldung.security; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Mono; + +@Service +public class GreetService { + + @PreAuthorize("hasRole('ADMIN')") + public Mono greet() { + return Mono.just("Hello from service!"); + } + +} diff --git a/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java b/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java new file mode 100644 index 0000000000..a9e44a2eee --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java @@ -0,0 +1,42 @@ +package com.baeldung.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@EnableWebFluxSecurity +@EnableReactiveMethodSecurity +public class SecurityConfig { + + @Bean + public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { + return http.authorizeExchange() + .pathMatchers("/admin").hasAuthority("ROLE_ADMIN") + .anyExchange().authenticated() + .and().formLogin() + .and().build(); + } + + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .roles("USER") + .build(); + + UserDetails admin = User.withDefaultPasswordEncoder() + .username("admin") + .password("password") + .roles("ADMIN") + .build(); + + return new MapReactiveUserDetailsService(user, admin); + } + +} diff --git a/spring-5/src/main/resources/application.properties b/spring-5/src/main/resources/application.properties index 886ea1978b..ccec014c2b 100644 --- a/spring-5/src/main/resources/application.properties +++ b/spring-5/src/main/resources/application.properties @@ -1,6 +1,3 @@ server.port=8081 -security.user.name=user -security.user.password=pass - logging.level.root=INFO \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java deleted file mode 100644 index 4caab86f7d..0000000000 --- a/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.jsonb; - -import static org.junit.Assert.assertTrue; - -import java.math.BigDecimal; -import java.time.LocalDate; - -import javax.json.bind.Jsonb; -import javax.json.bind.JsonbBuilder; - -import org.junit.Before; -import org.junit.Test; - -public class JsonbTest { - - private Jsonb jsonb; - - @Before - public void setup() { - jsonb = JsonbBuilder.create(); - } - - @Test - public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { - Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); - String jsonPerson = jsonb.toJson(person); - assertTrue("{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}".equals(jsonPerson)); - } - - @Test - public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { - Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); - String jsonPerson = "{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}"; - assertTrue(jsonb.fromJson(jsonPerson, Person.class) - .equals(person)); - } - -} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/EnabledOnJava8.java b/spring-5/src/test/java/com/baeldung/jupiter/EnabledOnJava8.java new file mode 100644 index 0000000000..c6d3b7ff10 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/EnabledOnJava8.java @@ -0,0 +1,18 @@ +package com.baeldung.jupiter; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.springframework.test.context.junit.jupiter.EnabledIf; + +@Target({ ElementType.TYPE, ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +@EnabledIf( + expression = "#{systemProperties['java.version'].startsWith('1.8')}", + reason = "Enabled on Java 8" +) +public @interface EnabledOnJava8 { + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java new file mode 100644 index 0000000000..ae058bc8ba --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java @@ -0,0 +1,50 @@ +package com.baeldung.jupiter; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.DisabledIf; +import org.springframework.test.context.junit.jupiter.EnabledIf; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig(Spring5EnabledAnnotationTest.Config.class) +@TestPropertySource(properties = { "tests.enabled=true" }) +public class Spring5EnabledAnnotationTest { + + @Configuration + static class Config { + } + + @EnabledIf("true") + @Test + void givenEnabledIfLiteral_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @EnabledIf(expression = "${tests.enabled}", loadContext = true) + @Test + void givenEnabledIfExpression_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @EnabledIf("#{systemProperties['java.version'].startsWith('1.8')}") + @Test + void givenEnabledIfSpel_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @EnabledOnJava8 + @Test + void givenEnabledOnJava8_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @DisabledIf("#{systemProperties['java.version'].startsWith('1.7')}") + @Test + void givenDisabledIf_WhenTrue_ThenTestNotExecuted() { + assertTrue(true); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/security/SecurityTest.java b/spring-5/src/test/java/com/baeldung/security/SecurityTest.java new file mode 100644 index 0000000000..a1c940a17a --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/security/SecurityTest.java @@ -0,0 +1,48 @@ +package com.baeldung.security; + +import com.baeldung.SpringSecurity5Application; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = SpringSecurity5Application.class) +public class SecurityTest { + + @Autowired + ApplicationContext context; + + private WebTestClient rest; + + @Before + public void setup() { + this.rest = WebTestClient + .bindToApplicationContext(this.context) + .configureClient() + .build(); + } + + @Test + public void whenNoCredentials_thenRedirectToLogin() { + this.rest.get() + .uri("/") + .exchange() + .expectStatus().is3xxRedirection(); + } + + @Test + @WithMockUser + public void whenHasCredentials_thenSeesGreeting() { + this.rest.get() + .uri("/") + .exchange() + .expectStatus().isOk() + .expectBody(String.class).isEqualTo("Hello, user"); + } +} diff --git a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java index b05f903b4b..43114b5b50 100644 --- a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java +++ b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java @@ -53,7 +53,7 @@ public class WebTestClientTest { .uri("/resource") .exchange() .expectStatus() - .is4xxClientError() + .is3xxRedirection() .expectBody(); } diff --git a/spring-activiti/README.md b/spring-activiti/README.md index 3580e29a52..703dfeec52 100644 --- a/spring-activiti/README.md +++ b/spring-activiti/README.md @@ -2,4 +2,5 @@ - [A Guide to Activiti with Java](http://www.baeldung.com/java-activiti) - [Introduction to Activiti with Spring](http://www.baeldung.com/spring-activiti) - +- [Activiti with Spring Security](http://www.baeldung.com/activiti-spring-security) +- [ProcessEngine Configuration in Activiti](http://www.baeldung.com/activiti-process-engine) diff --git a/spring-all/README.md b/spring-all/README.md index 36bf7da778..e1504a66db 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -23,3 +23,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent) - [A CLI with Spring Shell](http://www.baeldung.com/spring-shell-cli) - [JasperReports with Spring](http://www.baeldung.com/spring-jasper) +- [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view) diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java b/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java similarity index 97% rename from spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java rename to spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java index d70fb1c7cf..0201deabca 100644 --- a/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java +++ b/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java @@ -19,7 +19,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT) -public class SpringBootAdminClientApplicationTests { +public class SpringBootAdminClientApplicationIntegrationTest { @Autowired Environment environment; diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java similarity index 95% rename from spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java rename to spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java index 8ca50a6f75..7c1b1881a4 100644 --- a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java @@ -13,7 +13,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest(classes = { HazelcastConfig.class }, webEnvironment = NONE) -public class HazelcastConfigTest { +public class HazelcastConfigIntegrationTest { @Autowired private ApplicationContext applicationContext; diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java similarity index 96% rename from spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java rename to spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java index 85f6b374a4..465d079ac3 100644 --- a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java @@ -16,7 +16,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest(classes = { NotifierConfiguration.class }, webEnvironment = NONE) -public class NotifierConfigurationTest { +public class NotifierConfigurationIntegrationTest { @Autowired private ApplicationContext applicationContext; diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java similarity index 97% rename from spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java rename to spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java index 40611f00f6..0c0695e6c2 100644 --- a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java @@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class WebSecurityConfigTest { +public class WebSecurityConfigIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-boot-keycloak/pom.xml b/spring-boot-keycloak/pom.xml index 657f96a265..ab76d0af43 100644 --- a/spring-boot-keycloak/pom.xml +++ b/spring-boot-keycloak/pom.xml @@ -12,10 +12,12 @@ This is a simple application demonstrating integration between Keycloak and Spring Boot. - org.springframework.boot - spring-boot-starter-parent - 1.5.8.RELEASE - + + com.baeldung + parent-boot-4 + 0.0.1-SNAPSHOT + ../parent-boot-4 + diff --git a/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java b/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java similarity index 97% rename from spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java rename to spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java index 41662e5c17..e0bbef1c7f 100644 --- a/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java +++ b/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java @@ -20,7 +20,7 @@ import static org.mockito.Mockito.when; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = SpringBoot.class) -public class KeycloakConfigurationTest { +public class KeycloakConfigurationIntegrationTest { @Spy private KeycloakSecurityContextClientRequestInterceptor factory; diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 5d7eb11954..f126df00af 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -27,4 +27,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Java Client for a WebSockets API](http://www.baeldung.com/websockets-api-java-spring-client) - [Spring Boot and Togglz Aspect](http://www.baeldung.com/spring-togglz) - [Getting Started with GraphQL and Spring Boot](http://www.baeldung.com/spring-graphql) +- [Guide to Spring Type Conversions](http://www.baeldung.com/spring-type-conversions) diff --git a/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java index a51e3a6884..ffd5bf55d6 100644 --- a/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java @@ -1,7 +1,5 @@ package org.baeldung.properties; -import org.baeldung.properties.ConfigProperties; -import org.baeldung.properties.ConfigPropertiesDemoApplication; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot/src/test/resources/data.sql b/spring-boot/src/test/resources/data.sql new file mode 100644 index 0000000000..f36e034ce1 --- /dev/null +++ b/spring-boot/src/test/resources/data.sql @@ -0,0 +1,5 @@ +INSERT INTO country (name) VALUES ('India'); +INSERT INTO country (name) VALUES ('Brazil'); +INSERT INTO country (name) VALUES ('USA'); +INSERT INTO country (name) VALUES ('Italy'); +COMMIT; diff --git a/spring-boot/src/test/resources/schema.sql b/spring-boot/src/test/resources/schema.sql new file mode 100644 index 0000000000..15d7788cd7 --- /dev/null +++ b/spring-boot/src/test/resources/schema.sql @@ -0,0 +1,5 @@ +CREATE TABLE country ( + id INTEGER NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + PRIMARY KEY (id) +); diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 93bf6ea74b..e6d78f292d 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud @@ -15,8 +15,10 @@ spring-cloud-ribbon-client spring-cloud-rest spring-cloud-zookeeper - spring-cloud-gateway - spring-cloud-connectors-heroku + spring-cloud-gateway + spring-cloud-stream + spring-cloud-connectors-heroku + spring-cloud-aws pom @@ -38,6 +40,7 @@ 1.2.3.RELEASE 1.2.3.RELEASE 1.2.3.RELEASE + 1.3.0.RELEASE 1.4.2.RELEASE 3.6.0 1.4.2.RELEASE diff --git a/spring-cloud/spring-cloud-aws/README.md b/spring-cloud/spring-cloud-aws/README.md new file mode 100644 index 0000000000..c5f58159c8 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/README.md @@ -0,0 +1,21 @@ +# Spring Cloud AWS + +#### Running the Integration Tests + +To run the Integration Tests, we need to have an AWS account and have API keys generated for programmatic access. Edit +the `application.properties` file to add the following properties: + +``` +cloud.aws.credentials.accessKey=YourAccessKey +cloud.aws.credentials.secretKey=YourSecretKey +cloud.aws.region.static=us-east-1 +``` + +To test automatic DataSource creation from RDS instance, we also need to create an RDS instance in the AWS account. +Let's say that the RDS instance is called `spring-cloud-test-db` having the master password `se3retpass`, then we need +to write the following in `application.properties`: + +``` +cloud.aws.rds.spring-cloud-test-db +cloud.aws.rds.spring-cloud-test-db.password=se3retpass +``` diff --git a/spring-cloud/spring-cloud-aws/pom.xml b/spring-cloud/spring-cloud-aws/pom.xml new file mode 100644 index 0000000000..632e050d92 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-aws + 0.0.1-SNAPSHOT + jar + + Spring Cloud AWS + Spring Cloud AWS Examples + + + org.springframework.boot + spring-boot-starter-parent + 1.5.8.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + Dalston.SR4 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-aws + + + org.springframework.cloud + spring-cloud-starter-aws-jdbc + + + org.springframework.cloud + spring-cloud-starter-aws-messaging + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.postgresql + postgresql + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + maven-surefire-plugin + + + **/*IntegrationTest.java + + + + + + + + + diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/SpringCloudAwsApplication.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/SpringCloudAwsApplication.java new file mode 100644 index 0000000000..2c3909b3eb --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/SpringCloudAwsApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.aws; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringCloudAwsApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringCloudAwsApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/config/SpringCloudAwsConfig.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/config/SpringCloudAwsConfig.java new file mode 100644 index 0000000000..85dcd05c86 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/config/SpringCloudAwsConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.cloud.aws.config; + +import com.amazonaws.services.sns.AmazonSNS; +import com.amazonaws.services.sqs.AmazonSQSAsync; +import org.springframework.cloud.aws.messaging.core.NotificationMessagingTemplate; +import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringCloudAwsConfig { + + @Bean + public QueueMessagingTemplate queueMessagingTemplate(AmazonSQSAsync amazonSQSAsync) { + return new QueueMessagingTemplate(amazonSQSAsync); + } + + @Bean + public NotificationMessagingTemplate notificationMessagingTemplate(AmazonSNS amazonSNS) { + return new NotificationMessagingTemplate(amazonSNS); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java new file mode 100644 index 0000000000..cfad6e904f --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.aws.s3; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.WritableResource; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +@Component +public class SpringCloudS3 { + + @Autowired + ResourceLoader resourceLoader; + + @Autowired + ResourcePatternResolver resourcePatternResolver; + + public void downloadS3Object(String s3Url) throws IOException { + Resource resource = resourceLoader.getResource(s3Url); + File downloadedS3Object = new File(resource.getFilename()); + try (InputStream inputStream = resource.getInputStream()) { + Files.copy(inputStream, downloadedS3Object.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } + + public void uploadFileToS3(File file, String s3Url) throws IOException { + WritableResource resource = (WritableResource) resourceLoader.getResource(s3Url); + try (OutputStream outputStream = resource.getOutputStream()) { + Files.copy(file.toPath(), outputStream); + } + } + + public void downloadMultipleS3Objects(String s3UrlPattern) throws IOException { + Resource[] allFileMatchingPatten = this.resourcePatternResolver.getResources(s3UrlPattern); + for (Resource resource : allFileMatchingPatten) { + String fileName = resource.getFilename(); + fileName = fileName.substring(0, fileName.lastIndexOf("/") + 1); + File downloadedS3Object = new File(fileName); + try (InputStream inputStream = resource.getInputStream()) { + Files.copy(inputStream, downloadedS3Object.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointController.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointController.java new file mode 100644 index 0000000000..7c78fcbe37 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointController.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.cloud.aws.sns; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.aws.messaging.config.annotation.NotificationMessage; +import org.springframework.cloud.aws.messaging.config.annotation.NotificationSubject; +import org.springframework.cloud.aws.messaging.endpoint.NotificationStatus; +import org.springframework.cloud.aws.messaging.endpoint.annotation.NotificationMessageMapping; +import org.springframework.cloud.aws.messaging.endpoint.annotation.NotificationSubscriptionMapping; +import org.springframework.cloud.aws.messaging.endpoint.annotation.NotificationUnsubscribeConfirmationMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/topic-subscriber") +public class SNSEndpointController { + + private static final Logger logger = LoggerFactory.getLogger(SNSEndpointController.class); + + @NotificationMessageMapping + public void receiveNotification(@NotificationMessage String message, @NotificationSubject String subject) { + logger.info("Received message: {}, having subject: {}", message, subject); + } + + @NotificationUnsubscribeConfirmationMapping + public void confirmSubscriptionMessage(NotificationStatus notificationStatus) { + logger.info("Unsubscribed from Topic"); + notificationStatus.confirmSubscription(); + } + + @NotificationSubscriptionMapping + public void confirmUnsubscribeMessage(NotificationStatus notificationStatus) { + logger.info("Subscribed to Topic"); + notificationStatus.confirmSubscription(); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSMessageSender.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSMessageSender.java new file mode 100644 index 0000000000..58cb03644b --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSMessageSender.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.aws.sns; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.aws.messaging.core.NotificationMessagingTemplate; +import org.springframework.stereotype.Component; + +@Component +public class SNSMessageSender { + + @Autowired + NotificationMessagingTemplate notificationMessagingTemplate; + + public void send(String topicName, Object message, String subject) { + notificationMessagingTemplate.sendNotification(topicName, message, subject); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQS.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQS.java new file mode 100644 index 0000000000..d2a5fcf9ca --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQS.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.aws.sqs; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate; +import org.springframework.cloud.aws.messaging.listener.annotation.SqsListener; +import org.springframework.context.annotation.Lazy; +import org.springframework.messaging.handler.annotation.Header; +import org.springframework.stereotype.Component; + +import java.util.concurrent.CountDownLatch; + +@Component +@Lazy +public class SpringCloudSQS { + + private static final Logger logger = LoggerFactory.getLogger(SpringCloudSQS.class); + + static final String QUEUE_NAME = "spring-cloud-test-queue"; + + /* + * CountDownLatch is added to wait for messages + * during integration test + */ + CountDownLatch countDownLatch; + + public void setCountDownLatch(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + @Autowired + QueueMessagingTemplate queueMessagingTemplate; + + @SqsListener(QUEUE_NAME) + public void receiveMessage(String message, @Header("SenderId") String senderId) { + logger.info("Received message: {}, having SenderId: {}", message, senderId); + if (countDownLatch != null) { + countDownLatch.countDown(); + } + } + + public void send(String queueName, Object message) { + queueMessagingTemplate.convertAndSend(queueName, message); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/resources/application.properties b/spring-cloud/spring-cloud-aws/src/main/resources/application.properties new file mode 100644 index 0000000000..a769b70ddd --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/resources/application.properties @@ -0,0 +1,14 @@ +cloud.aws.credentials.accessKey=YourAccessKey +cloud.aws.credentials.secretKey=YourSecretKey +cloud.aws.region.static=us-east-1 + +cloud.aws.rds.spring-cloud-test-db +cloud.aws.rds.spring-cloud-test-db.password=se3retpass + +# These 3 properties are optional +cloud.aws.rds.spring-cloud-test-db.username=testuser +cloud.aws.rds.spring-cloud-test-db.readReplicaSupport=true +cloud.aws.rds.spring-cloud-test-db.databaseName=test + +# Disable auto cloudfromation +cloud.aws.stack.auto=false diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/SpringCloudAwsTestUtil.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/SpringCloudAwsTestUtil.java new file mode 100644 index 0000000000..fe10eb6f15 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/SpringCloudAwsTestUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.spring.cloud.aws; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.AWSCredentialsProvider; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.AmazonS3ClientBuilder; +import com.amazonaws.services.sns.AmazonSNS; +import com.amazonaws.services.sns.AmazonSNSClientBuilder; +import com.amazonaws.services.sqs.AmazonSQS; +import com.amazonaws.services.sqs.AmazonSQSClientBuilder; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.junit.BeforeClass; + +/** + * This class is needed only for testing. This is because we need to + * create AWS resources before Spring's Application context is created + * in a {@link BeforeClass} method. Since Autowired dependencies don't + * work in static context, we will use this class for AWS clients. + */ +public class SpringCloudAwsTestUtil { + + private static String awsAccessKey; + private static String awsSecretKey; + private static String defaultRegion; + + static { + try { + InputStream is = SpringCloudAwsTestUtil.class.getResourceAsStream("/application.properties"); + Properties properties = new Properties(); + properties.load(is); + awsAccessKey = properties.getProperty("cloud.aws.credentials.accessKey"); + awsSecretKey = properties.getProperty("cloud.aws.credentials.secretKey"); + defaultRegion = properties.getProperty("cloud.aws.region.static"); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static AWSCredentials awsCredentials() { + return new BasicAWSCredentials(awsAccessKey, awsSecretKey); + } + + public static AWSCredentialsProvider awsCredentialsProvider() { + return new AWSStaticCredentialsProvider(awsCredentials()); + } + + public static AmazonS3 amazonS3() { + return AmazonS3ClientBuilder.standard() + .withCredentials(awsCredentialsProvider()) + .withRegion(defaultRegion) + .build(); + } + + public static AmazonSNS amazonSNS() { + return AmazonSNSClientBuilder.standard() + .withCredentials(awsCredentialsProvider()) + .withRegion(defaultRegion) + .build(); + } + + public static AmazonSQS amazonSQS() { + return AmazonSQSClientBuilder.standard() + .withCredentials(awsCredentialsProvider()) + .withRegion(defaultRegion) + .build(); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/rds/SpringCloudRDSIntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/rds/SpringCloudRDSIntegrationTest.java new file mode 100644 index 0000000000..9e163d6dc4 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/rds/SpringCloudRDSIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.aws.rds; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@RunWith(SpringRunner.class) +public class SpringCloudRDSIntegrationTest { + + @Autowired + DataSource dataSource; + + @Test + public void whenDataSourceCreated_thenSuccess() { + assertThat(dataSource).isNotNull(); + } + + @Test + public void givenDataSource_whenConnectionCreated_thenSuccess() throws SQLException { + Connection connection = dataSource.getConnection(); + assertThat(connection).isNotNull(); + } + + @Test + public void givenConnection_whenQueryExecuted_thenSuccess() throws SQLException { + Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT 1"); + while (resultSet.next()) { + int result = resultSet.getInt(1); + assertThat(result).isEqualTo(1); + } + connection.close(); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3IntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3IntegrationTest.java new file mode 100644 index 0000000000..a866287dec --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3IntegrationTest.java @@ -0,0 +1,101 @@ +package com.baeldung.spring.cloud.aws.s3; + +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.model.ListObjectsV2Result; +import com.amazonaws.services.s3.model.S3ObjectSummary; +import com.baeldung.spring.cloud.aws.SpringCloudAwsTestUtil; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@RunWith(SpringRunner.class) +@TestPropertySource("classpath:application-test.properties") +public class SpringCloudS3IntegrationTest { + + @Autowired + private SpringCloudS3 springCloudS3; + + private static String bucketName; + private static String testFileToDownload; + private static String testFileToUpload; + + private static String[] filesWithSimilarName; + private static List similarNameFiles; + + @BeforeClass + public static void setupResources() throws IOException { + + bucketName = UUID.randomUUID().toString(); + testFileToDownload = "test-file-download.txt"; + testFileToUpload = "test-file-upload.txt"; + + filesWithSimilarName = new String[] { "foo/hello-apple.txt", "foo/hello-orange.txt", "bar/hello-grapes.txt", }; + + similarNameFiles = new ArrayList<>(); + for (String name : filesWithSimilarName) { + similarNameFiles.add(new File(name.substring(0, name.lastIndexOf("/") + 1))); + } + + Files.write(Paths.get(testFileToUpload), "Hello World Uploaded!".getBytes()); + + AmazonS3 amazonS3 = SpringCloudAwsTestUtil.amazonS3(); + amazonS3.createBucket(bucketName); + + amazonS3.putObject(bucketName, testFileToDownload, "Hello World"); + + for (String s3Key : filesWithSimilarName) { + amazonS3.putObject(bucketName, s3Key, "Hello World"); + } + } + + @Test + public void whenS3ObjectDownloaded_thenSuccess() throws IOException { + String s3Url = "s3://" + bucketName + "/" + testFileToDownload; + springCloudS3.downloadS3Object(s3Url); + assertThat(new File(testFileToDownload)).exists(); + } + + @Test + public void whenS3ObjectUploaded_thenSuccess() throws IOException { + String s3Url = "s3://" + bucketName + "/" + testFileToUpload; + File file = new File(testFileToUpload); + springCloudS3.uploadFileToS3(file, s3Url); + } + + @Test + public void whenMultipleS3ObjectsDownloaded_thenSuccess() throws IOException { + String s3Url = "s3://" + bucketName + "/**/hello-*.txt"; + springCloudS3.downloadMultipleS3Objects(s3Url); + similarNameFiles.forEach(f -> assertThat(f).exists()); + } + + @AfterClass + public static void cleanUpResources() { + AmazonS3 amazonS3 = SpringCloudAwsTestUtil.amazonS3(); + ListObjectsV2Result listObjectsV2Result = amazonS3.listObjectsV2(bucketName); + for (S3ObjectSummary objectSummary : listObjectsV2Result.getObjectSummaries()) { + amazonS3.deleteObject(bucketName, objectSummary.getKey()); + } + amazonS3.deleteBucket(bucketName); + + new File(testFileToDownload).delete(); + new File(testFileToUpload).delete(); + similarNameFiles.forEach(File::delete); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointControllerUnitTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointControllerUnitTest.java new file mode 100644 index 0000000000..14958570e2 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointControllerUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.cloud.aws.sns; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.cloud.aws.messaging.endpoint.NotificationStatus; + +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; + +public class SNSEndpointControllerUnitTest { + + SNSEndpointController snsEndpointController; + + @Before + public void setUp() { + snsEndpointController = new SNSEndpointController(); + } + + @Test + public void whenReceivedNotificationInvoked_thenSuccess() { + snsEndpointController.receiveNotification("Message", "Subject"); + } + + @Test + public void whenConfirmUnsubscribeReturned_thenSuccess() { + NotificationStatus notificationStatus = mock(NotificationStatus.class); + doNothing().when(notificationStatus).confirmSubscription(); + snsEndpointController.confirmUnsubscribeMessage(notificationStatus); + } + + @Test + public void whenConfirmSubscriptionReturned_thenSuccess() { + NotificationStatus notificationStatus = mock(NotificationStatus.class); + doNothing().when(notificationStatus).confirmSubscription(); + snsEndpointController.confirmSubscriptionMessage(notificationStatus); + } + +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SpringCloudSNSIntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SpringCloudSNSIntegrationTest.java new file mode 100644 index 0000000000..e1f23d5c76 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SpringCloudSNSIntegrationTest.java @@ -0,0 +1,61 @@ +package com.baeldung.spring.cloud.aws.sns; + +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import com.amazonaws.services.sns.AmazonSNS; +import com.amazonaws.services.sns.model.CreateTopicResult; +import com.baeldung.spring.cloud.aws.SpringCloudAwsTestUtil; +import com.baeldung.spring.cloud.aws.sqs.Greeting; + +@SpringBootTest +@RunWith(SpringRunner.class) +@TestPropertySource("classpath:application-test.properties") +public class SpringCloudSNSIntegrationTest { + + @Autowired + private SNSMessageSender snsMessageSender; + + private static String topicName; + private static String topicArn; + + @BeforeClass + public static void setupAwsResources() { + + topicName = UUID.randomUUID().toString(); + + AmazonSNS amazonSNS = SpringCloudAwsTestUtil.amazonSNS(); + + CreateTopicResult result = amazonSNS.createTopic(topicName); + topicArn = result.getTopicArn(); + } + + @Test + public void whenMessagePublished_thenSuccess() { + String subject = "Test Message"; + String message = "Hello World"; + snsMessageSender.send(topicName, message, subject); + } + + @Test + public void whenConvertedMessagePublished_thenSuccess() { + String subject = "Test Message"; + Greeting message = new Greeting("Helo", "World"); + snsMessageSender.send(topicName, message, subject); + } + + @AfterClass + public static void cleanupAwsResources() { + AmazonSNS amazonSNS = SpringCloudAwsTestUtil.amazonSNS(); + amazonSNS.deleteTopic(topicArn); + } + +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/Greeting.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/Greeting.java new file mode 100644 index 0000000000..3d14d55f14 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/Greeting.java @@ -0,0 +1,63 @@ +package com.baeldung.spring.cloud.aws.sqs; + +public class Greeting { + private String message; + private String name; + + public Greeting() { + + } + + public Greeting(String mesage, String name) { + this.message = mesage; + this.name = name; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Greeting other = (Greeting) obj; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQSIntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQSIntegrationTest.java new file mode 100644 index 0000000000..76d2fd7c0d --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQSIntegrationTest.java @@ -0,0 +1,135 @@ +package com.baeldung.spring.cloud.aws.sqs; + +import com.amazonaws.services.sqs.AmazonSQS; +import com.amazonaws.services.sqs.model.CreateQueueResult; +import com.amazonaws.services.sqs.model.PurgeQueueRequest; +import com.amazonaws.services.sqs.model.ReceiveMessageRequest; +import com.amazonaws.services.sqs.model.ReceiveMessageResult; +import com.baeldung.spring.cloud.aws.SpringCloudAwsTestUtil; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Lazy; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@RunWith(SpringRunner.class) +@TestPropertySource("classpath:application-test.properties") +public class SpringCloudSQSIntegrationTest { + + private static final Logger logger = LoggerFactory.getLogger(SpringCloudSQSIntegrationTest.class); + + @Autowired + @Lazy + private SpringCloudSQS springCloudSQS; + + private static String receiveQueueName; + private static String receiveQueueUrl; + + private static String sendQueueName; + private static String sendQueueURl; + + @BeforeClass + public static void setupAwsResources() { + + sendQueueName = UUID.randomUUID().toString(); + receiveQueueName = SpringCloudSQS.QUEUE_NAME; + + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + + CreateQueueResult receiveQueue = amazonSQS.createQueue(receiveQueueName); + receiveQueueUrl = receiveQueue.getQueueUrl(); + + CreateQueueResult sendQueue = amazonSQS.createQueue(sendQueueName); + sendQueueURl = sendQueue.getQueueUrl(); + } + + @Test + public void whenMessageSentAndVerified_thenSuccess() throws InterruptedException { + + String message = "Hello World"; + springCloudSQS.send(sendQueueName, message); + + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + + ReceiveMessageRequest request = new ReceiveMessageRequest(sendQueueURl); + request.setMaxNumberOfMessages(1); + + ReceiveMessageResult result = null; + do { + result = amazonSQS.receiveMessage(request); + if (result.getMessages().size() == 0) { + logger.info("Message not received at first time, waiting for 1 second"); + } + } while (result.getMessages().size() == 0); + assertThat(result.getMessages().get(0).getBody()).isEqualTo(message); + + // Delete message so that it doen't interfere with other test + amazonSQS.deleteMessage(sendQueueURl, result.getMessages().get(0).getReceiptHandle()); + + } + + @Test + public void whenConvertedMessageSentAndVerified_thenSuccess() throws InterruptedException, IOException { + + Greeting message = new Greeting("Hello", "World"); + springCloudSQS.send(sendQueueName, message); + + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + + ReceiveMessageRequest request = new ReceiveMessageRequest(sendQueueURl); + request.setMaxNumberOfMessages(1); + + ReceiveMessageResult result = null; + do { + result = amazonSQS.receiveMessage(request); + if (result.getMessages().size() == 0) { + logger.info("Message not received at first time, waiting for 1 second"); + } + } while (result.getMessages().size() == 0); + assertThat(new ObjectMapper().readValue(result.getMessages().get(0).getBody(), Greeting.class)).isEqualTo(message); + + // Delete message so that it doen't interfere with other test + amazonSQS.deleteMessage(sendQueueURl, result.getMessages().get(0).getReceiptHandle()); + } + + @Test + public void givenMessageSent_whenMessageReceived_thenSuccess() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(5); + springCloudSQS.setCountDownLatch(countDownLatch); + + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + for (int i = 0; i < 5; i++) { + amazonSQS.sendMessage(receiveQueueUrl, "Hello World " + i); + logger.info("Sent message {}, waiting for 1 second", i + 1); + Thread.sleep(1000L); + } + countDownLatch.await(); + } + + @AfterClass + public static void cleanupAwsResources() { + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + PurgeQueueRequest receiveQueuePurge = new PurgeQueueRequest(receiveQueueUrl); + amazonSQS.purgeQueue(receiveQueuePurge); + amazonSQS.deleteQueue(receiveQueueUrl); + + PurgeQueueRequest sendQueuePurge = new PurgeQueueRequest(sendQueueURl); + amazonSQS.purgeQueue(sendQueuePurge); + amazonSQS.deleteQueue(sendQueueURl); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/test/resources/application-test.properties b/spring-cloud/spring-cloud-aws/src/test/resources/application-test.properties new file mode 100644 index 0000000000..0d3d90b03a --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/resources/application-test.properties @@ -0,0 +1,4 @@ +# Don't try to create DataSouce when running tests which don't need a DataSource +spring.autoconfigure.exclude=\ + org.springframework.cloud.aws.autoconfigure.jdbc.AmazonRdsDatabaseAutoConfiguration,\ + org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration diff --git a/spring-cloud/spring-cloud-stream/README.md b/spring-cloud/spring-cloud-stream/README.md new file mode 100644 index 0000000000..5ecb852df5 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Introduction to Spring Cloud Stream](http://www.baeldung.com/spring-cloud-stream) diff --git a/spring-cloud/spring-cloud-stream/pom.xml b/spring-cloud/spring-cloud-stream/pom.xml new file mode 100644 index 0000000000..5ec24268d9 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + org.baeldung + spring-cloud-stream + pom + + spring-cloud-stream + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + + + + spring-cloud-stream-rabbit + + + + UTF-8 + 3.6.0 + + + + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + ${spring-cloud-stream.version} + + + + org.springframework.cloud + spring-cloud-stream + ${spring-cloud-stream.version} + + + + org.springframework.cloud + spring-cloud-stream-test-support + ${spring-cloud-stream.version} + test + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + + diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml new file mode 100644 index 0000000000..a954a7035e --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + + spring-cloud-stream-rabbit + jar + + spring-cloud-stream-rabbit + Simple Spring Cloud Stream + + + org.baeldung + spring-cloud-stream + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + + + + org.springframework.cloud + spring-cloud-stream-test-support + test + + + + diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplication.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplication.java new file mode 100644 index 0000000000..375494dfac --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplication.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.cloud.stream.rabbit; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.MessageBuilder; + +import com.baeldung.spring.cloud.stream.rabbit.processor.MyProcessor; + +@SpringBootApplication +@EnableBinding(MyProcessor.class) +public class MultipleOutputsServiceApplication { + public static void main(String[] args) { + SpringApplication.run(MultipleOutputsServiceApplication.class, args); + } + + @Autowired + private MyProcessor processor; + + @StreamListener(MyProcessor.INPUT) + public void routeValues(Integer val) { + if (val < 10) { + processor.anOutput() + .send(message(val)); + } else { + processor.anotherOutput() + .send(message(val)); + } + } + + private static final Message message(T val) { + return MessageBuilder.withPayload(val) + .build(); + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceApplication.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceApplication.java new file mode 100644 index 0000000000..4729e418b6 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceApplication.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.cloud.stream.rabbit; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.MessageBuilder; + +import com.baeldung.spring.cloud.stream.rabbit.processor.MyProcessor; + +@SpringBootApplication +@EnableBinding(MyProcessor.class) +public class MultipleOutputsWithConditionsServiceApplication { + public static void main(String[] args) { + SpringApplication.run(MultipleOutputsWithConditionsServiceApplication.class, args); + } + + @Autowired + private MyProcessor processor; + + @StreamListener(target = MyProcessor.INPUT, condition = "payload < 10") + public void routeValuesToAnOutput(Integer val) { + processor.anOutput() + .send(message(val)); + } + + @StreamListener(target = MyProcessor.INPUT, condition = "payload >= 10") + public void routeValuesToAnotherOutput(Integer val) { + processor.anotherOutput() + .send(message(val)); + } + + private static final Message message(T val) { + return MessageBuilder.withPayload(val) + .build(); + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerServiceApplication.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerServiceApplication.java new file mode 100644 index 0000000000..aac551e544 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerServiceApplication.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.stream.rabbit; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.context.annotation.Bean; +import org.springframework.messaging.converter.MessageConverter; +import org.springframework.messaging.handler.annotation.SendTo; + +import com.baeldung.spring.cloud.stream.rabbit.messages.TextPlainMessageConverter; +import com.baeldung.spring.cloud.stream.rabbit.model.LogMessage; + +@SpringBootApplication +@EnableBinding(Processor.class) +public class MyLoggerServiceApplication { + public static void main(String[] args) { + SpringApplication.run(MyLoggerServiceApplication.class, args); + } + + @Bean + public MessageConverter providesTextPlainMessageConverter() { + return new TextPlainMessageConverter(); + } + + @StreamListener(Processor.INPUT) + @SendTo(Processor.OUTPUT) + public LogMessage enrichLogMessage(LogMessage log) { + return new LogMessage(String.format("[1]: %s", log.getMessage())); + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/messages/TextPlainMessageConverter.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/messages/TextPlainMessageConverter.java new file mode 100644 index 0000000000..d690ee38a9 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/messages/TextPlainMessageConverter.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.cloud.stream.rabbit.messages; + +import org.springframework.messaging.Message; +import org.springframework.messaging.converter.AbstractMessageConverter; +import org.springframework.util.MimeType; + +import com.baeldung.spring.cloud.stream.rabbit.model.LogMessage; + +public class TextPlainMessageConverter extends AbstractMessageConverter { + + public TextPlainMessageConverter() { + super(new MimeType("text", "plain")); + } + + @Override + protected boolean supports(Class clazz) { + return (LogMessage.class == clazz); + } + + @Override + protected Object convertFromInternal(Message message, Class targetClass, Object conversionHint) { + Object payload = message.getPayload(); + String text = payload instanceof String ? (String) payload : new String((byte[]) payload); + return new LogMessage(text); + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/model/LogMessage.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/model/LogMessage.java new file mode 100644 index 0000000000..44a6ca4d4e --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/model/LogMessage.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.stream.rabbit.model; + +import java.io.Serializable; + +public class LogMessage implements Serializable { + + private static final long serialVersionUID = -5857383701708275796L; + + private String message; + + public LogMessage() { + + } + + public LogMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return message; + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/processor/MyProcessor.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/processor/MyProcessor.java new file mode 100644 index 0000000000..563ce06b6f --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/java/com/baeldung/spring/cloud/stream/rabbit/processor/MyProcessor.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.cloud.stream.rabbit.processor; + +import org.springframework.cloud.stream.annotation.Input; +import org.springframework.cloud.stream.annotation.Output; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.SubscribableChannel; + +public interface MyProcessor { + String INPUT = "myInput"; + + @Input + SubscribableChannel myInput(); + + @Output("myOutput") + MessageChannel anOutput(); + + @Output + MessageChannel anotherOutput(); +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/resources/application.yml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/resources/application.yml new file mode 100644 index 0000000000..3d9d97a736 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/resources/application.yml @@ -0,0 +1,28 @@ +spring: + cloud: + stream: + bindings: + input: + destination: queue.log.messages + binder: local_rabbit + group: logMessageConsumers + output: + destination: queue.pretty.log.messages + binder: local_rabbit + binders: + local_rabbit: + type: rabbit + environment: + spring: + rabbitmq: + host: localhost + port: 5672 + username: guest + password: guest + virtual-host: / +server: + port: 0 +management: + health: + binders: + enabled: true \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java new file mode 100644 index 0000000000..898d06897f --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.stream.rabbit; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.test.binder.MessageCollector; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.cloud.stream.rabbit.processor.MyProcessor; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MultipleOutputsServiceApplication.class) +@DirtiesContext +public class MultipleOutputsServiceApplicationIntegrationTest { + + @Autowired + private MyProcessor pipe; + + @Autowired + private MessageCollector messageCollector; + + @Test + public void whenSendMessage_thenResponseIsInAOutput() { + whenSendMessage(1); + thenPayloadInChannelIs(pipe.anOutput(), 1); + } + + @Test + public void whenSendMessage_thenResponseIsInAnotherOutput() { + whenSendMessage(11); + thenPayloadInChannelIs(pipe.anotherOutput(), 11); + } + + private void whenSendMessage(Integer val) { + pipe.myInput() + .send(MessageBuilder.withPayload(val) + .build()); + } + + private void thenPayloadInChannelIs(MessageChannel channel, Integer expectedValue) { + Object payload = messageCollector.forChannel(channel) + .poll() + .getPayload(); + assertEquals(expectedValue, payload); + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java new file mode 100644 index 0000000000..c3bf5a1205 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.stream.rabbit; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.test.binder.MessageCollector; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.cloud.stream.rabbit.processor.MyProcessor; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MultipleOutputsWithConditionsServiceApplication.class) +@DirtiesContext +public class MultipleOutputsWithConditionsServiceIntegrationTest { + + @Autowired + private MyProcessor pipe; + + @Autowired + private MessageCollector messageCollector; + + @Test + public void whenSendMessage_thenResponseIsInAOutput() { + whenSendMessage(1); + thenPayloadInChannelIs(pipe.anOutput(), 1); + } + + @Test + public void whenSendMessage_thenResponseIsInAnotherOutput() { + whenSendMessage(11); + thenPayloadInChannelIs(pipe.anotherOutput(), 11); + } + + private void whenSendMessage(Integer val) { + pipe.myInput() + .send(MessageBuilder.withPayload(val) + .build()); + } + + private void thenPayloadInChannelIs(MessageChannel channel, Integer expectedValue) { + Object payload = messageCollector.forChannel(channel) + .poll() + .getPayload(); + assertEquals(expectedValue, payload); + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java new file mode 100644 index 0000000000..21d84e79e0 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.cloud.stream.rabbit; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.cloud.stream.test.binder.MessageCollector; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.cloud.stream.rabbit.model.LogMessage; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MyLoggerServiceApplication.class) +@DirtiesContext +public class MyLoggerApplicationIntegrationTest { + + @Autowired + private Processor pipe; + + @Autowired + private MessageCollector messageCollector; + + @Test + public void whenSendMessage_thenResponseShouldUpdateText() { + pipe.input() + .send(MessageBuilder.withPayload(new LogMessage("This is my message")) + .build()); + + Object payload = messageCollector.forChannel(pipe.output()) + .poll() + .getPayload(); + + assertEquals("[1]: This is my message", payload.toString()); + } +} diff --git a/spring-core/src/main/resources/com.baeldung.di.spring.xml b/spring-core/src/main/resources/com.baeldung.di.spring.xml index 9c44d911d1..e0c5d22abb 100644 --- a/spring-core/src/main/resources/com.baeldung.di.spring.xml +++ b/spring-core/src/main/resources/com.baeldung.di.spring.xml @@ -5,7 +5,7 @@ - + @@ -29,15 +29,15 @@ - + - + - + \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java index 1d133faf63..1660b99726 100644 --- a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java @@ -15,31 +15,17 @@ public class BeanInjectionTest { applicationContext = new ClassPathXmlApplicationContext("com.baeldung.di.spring.xml"); } - @Test - public void protoBean_getBean_returnsMultipleInstance() { - final MessageApp messageApp1 = applicationContext.getBean("messageWorldApp", MessageApp.class); - final MessageApp messageApp2 = applicationContext.getBean("messageWorldApp", MessageApp.class); - assertNotEquals(messageApp1, messageApp2); - } - - @Test - public void protoFactoryMethod_getBean_returnsMultipleInstance() { - final IndexApp indexApp1 = applicationContext.getBean("indexAppWithFactoryMethod", IndexApp.class); - final IndexApp indexApp2 = applicationContext.getBean("indexAppWithFactoryMethod", IndexApp.class); - assertNotEquals(indexApp1, indexApp2); - } - - @Test - public void protoStaticFactory_getBean_returnsMultipleInstance() { - final IndexApp indexApp1 = applicationContext.getBean("indexAppWithStaticFactory", IndexApp.class); - final IndexApp indexApp2 = applicationContext.getBean("indexAppWithStaticFactory", IndexApp.class); - assertNotEquals(indexApp1, indexApp2); - } - @Test public void singletonBean_getBean_returnsSingleInstance() { final IndexApp indexApp1 = applicationContext.getBean("indexApp", IndexApp.class); final IndexApp indexApp2 = applicationContext.getBean("indexApp", IndexApp.class); assertEquals(indexApp1, indexApp2); } + + @Test + public void getBean_returnsInstance() { + final IndexApp indexApp = applicationContext.getBean("indexApp", IndexApp.class); + assertNotNull(indexApp); + } + } diff --git a/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationTests.java b/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java similarity index 82% rename from spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationTests.java rename to spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java index b39a5605b1..71eec9cf45 100644 --- a/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationTests.java +++ b/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class SpringJMeterJenkinsApplicationTests { +public class SpringJMeterJenkinsApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java new file mode 100644 index 0000000000..180f54326e --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java @@ -0,0 +1,29 @@ +package org.baeldung.dsrouting; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +/** + * Database access code for datasource routing example. + */ +public class ClientDao { + + private static final String SQL_GET_CLIENT_NAME = "select name from client"; + + private final JdbcTemplate jdbcTemplate; + + public ClientDao(DataSource datasource) { + this.jdbcTemplate = new JdbcTemplate(datasource); + } + + public String getClientName() { + return this.jdbcTemplate.query(SQL_GET_CLIENT_NAME, rowMapper) + .get(0); + } + + private static RowMapper rowMapper = (rs, rowNum) -> { + return rs.getString("name"); + }; +} diff --git a/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java new file mode 100644 index 0000000000..997e461cde --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java @@ -0,0 +1,14 @@ +package org.baeldung.dsrouting; + +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; + +/** + * Returns thread bound client lookup key for current context. + */ +public class ClientDataSourceRouter extends AbstractRoutingDataSource { + + @Override + protected Object determineCurrentLookupKey() { + return ClientDatabaseContextHolder.getClientDatabase(); + } +} diff --git a/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabase.java b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabase.java new file mode 100644 index 0000000000..619b8707d8 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabase.java @@ -0,0 +1,7 @@ +package org.baeldung.dsrouting; + +public enum ClientDatabase { + + CLIENT_A, CLIENT_B + +} diff --git a/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java new file mode 100644 index 0000000000..c08559e877 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java @@ -0,0 +1,26 @@ +package org.baeldung.dsrouting; + +import org.springframework.util.Assert; + +/** + * Thread shared context to point to the datasource which should be used. This + * enables context switches between different clients. + */ +public class ClientDatabaseContextHolder { + + private static final ThreadLocal CONTEXT = new ThreadLocal<>(); + + public static void set(ClientDatabase clientDatabase) { + Assert.notNull(clientDatabase, "clientDatabase cannot be null"); + CONTEXT.set(clientDatabase); + } + + public static ClientDatabase getClientDatabase() { + return CONTEXT.get(); + } + + public static void clear() { + CONTEXT.remove(); + } + +} diff --git a/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientService.java b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientService.java new file mode 100644 index 0000000000..4b63c6333c --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientService.java @@ -0,0 +1,21 @@ +package org.baeldung.dsrouting; + +/** + * Service layer code for datasource routing example. Here, the service methods are responsible + * for setting and clearing the context. + */ +public class ClientService { + + private final ClientDao clientDao; + + public ClientService(ClientDao clientDao) { + this.clientDao = clientDao; + } + + public String getClientName(ClientDatabase clientDb) { + ClientDatabaseContextHolder.set(clientDb); + String clientName = this.clientDao.getClientName(); + ClientDatabaseContextHolder.clear(); + return clientName; + } +} diff --git a/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java b/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java new file mode 100644 index 0000000000..0555c8186c --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java @@ -0,0 +1,33 @@ +package org.baeldung.sqlfiles; + +import static javax.persistence.GenerationType.IDENTITY; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Country { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Integer id; + + @Column(nullable = false) + private String name; + + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-jpa/src/main/resources/sqlfiles.properties b/spring-jpa/src/main/resources/sqlfiles.properties new file mode 100644 index 0000000000..0bea6adad1 --- /dev/null +++ b/spring-jpa/src/main/resources/sqlfiles.properties @@ -0,0 +1 @@ +spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java new file mode 100644 index 0000000000..f81247e3cd --- /dev/null +++ b/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java @@ -0,0 +1,53 @@ +package org.baeldung.dsrouting; + +import static org.junit.Assert.assertEquals; + +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = DataSourceRoutingTestConfiguration.class) +public class DataSourceRoutingIntegrationTest { + + @Autowired + DataSource routingDatasource; + + @Autowired + ClientService clientService; + + @Before + public void setup() { + final String SQL_CLIENT_A = "insert into client (id, name) values (1, 'CLIENT A')"; + final String SQL_CLIENT_B = "insert into client (id, name) values (2, 'CLIENT B')"; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.setDataSource(routingDatasource); + + ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_A); + jdbcTemplate.execute(SQL_CLIENT_A); + ClientDatabaseContextHolder.clear(); + + ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_B); + jdbcTemplate.execute(SQL_CLIENT_B); + ClientDatabaseContextHolder.clear(); + } + + @Test + public void givenClientDbs_whenContextsSwitch_thenRouteToCorrectDatabase() throws Exception { + + // test ACME WIDGETS + String clientName = clientService.getClientName(ClientDatabase.CLIENT_A); + assertEquals(clientName, "CLIENT A"); + + // test WIDGETS_ARE_US + clientName = clientService.getClientName(ClientDatabase.CLIENT_B); + assertEquals(clientName, "CLIENT B"); + } +} diff --git a/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java b/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java new file mode 100644 index 0000000000..dee9d58722 --- /dev/null +++ b/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java @@ -0,0 +1,51 @@ +package org.baeldung.dsrouting; + +import java.util.HashMap; +import java.util.Map; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +@Configuration +public class DataSourceRoutingTestConfiguration { + + @Bean + public ClientService clientService() { + return new ClientService(new ClientDao(clientDatasource())); + } + + @Bean + public DataSource clientDatasource() { + Map targetDataSources = new HashMap<>(); + DataSource clientADatasource = clientADatasource(); + DataSource clientBDatasource = clientBDatasource(); + targetDataSources.put(ClientDatabase.CLIENT_A, clientADatasource); + targetDataSources.put(ClientDatabase.CLIENT_B, clientBDatasource); + + ClientDataSourceRouter clientRoutingDatasource = new ClientDataSourceRouter(); + clientRoutingDatasource.setTargetDataSources(targetDataSources); + clientRoutingDatasource.setDefaultTargetDataSource(clientADatasource); + return clientRoutingDatasource; + } + + private DataSource clientADatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + return dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("CLIENT_A") + .addScript("classpath:dsrouting-db.sql") + .build(); + } + + private DataSource clientBDatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + return dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("CLIENT_B") + .addScript("classpath:dsrouting-db.sql") + .build(); + } +} diff --git a/spring-jpa/src/test/resources/dsrouting-db.sql b/spring-jpa/src/test/resources/dsrouting-db.sql new file mode 100644 index 0000000000..c9ca52907a --- /dev/null +++ b/spring-jpa/src/test/resources/dsrouting-db.sql @@ -0,0 +1,5 @@ +create table client ( + id numeric, + name varchar(50), + constraint pk_client primary key (id) +); \ No newline at end of file diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml new file mode 100644 index 0000000000..554040e763 --- /dev/null +++ b/spring-rest-embedded-tomcat/pom.xml @@ -0,0 +1,83 @@ + + 4.0.0 + org.baeldung.embedded + SpringRestTomcat + 0.0.1-SNAPSHOT + + spring-rest-embedded-tomcat + war + + + + junit + junit + ${junit.version} + test + + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + + javax.servlet + javax.servlet-api + 4.0.0 + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.library} + + + + org.apache.tomcat.embed + tomcat-embed-core + 9.0.1 + test + + + + org.apache.tomcat + tomcat-jasper + 9.0.1 + test + + + + org.apache.httpcomponents + httpclient + 4.5.3 + + + + org.apache.httpcomponents + httpcore + 4.4.8 + + + + + + spring-rest-embedded-tomcat + + + + 5.0.1.RELEASE + 4.12 + 2.9.2 + 1.8 + 1.8 + false + + + \ No newline at end of file diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/AppInitializer.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/AppInitializer.java new file mode 100644 index 0000000000..24bd28166b --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/AppInitializer.java @@ -0,0 +1,22 @@ +package org.baeldung.embedded.configuration; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { UserConfiguration.class }; + } + + @Override + protected Class[] getServletConfigClasses() { + return null; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/UserConfiguration.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/UserConfiguration.java new file mode 100644 index 0000000000..4c102a74cb --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/UserConfiguration.java @@ -0,0 +1,12 @@ +package org.baeldung.embedded.configuration; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "org.baeldung.embedded") +public class UserConfiguration { + +} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/controller/UserController.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/controller/UserController.java new file mode 100644 index 0000000000..a9a5faa0c6 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/controller/UserController.java @@ -0,0 +1,28 @@ +package org.baeldung.embedded.controller; + +import org.baeldung.embedded.domain.User; +import org.baeldung.embedded.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + @Autowired + UserService userService; + + @RequestMapping("/") + public String welcome() { + return "Hello World!"; + } + + @RequestMapping(method = RequestMethod.GET, value = "/user/{userName}") + @ResponseBody + public User user(@PathVariable String userName) { + return this.userService.getUser(userName); + } +} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/domain/User.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/domain/User.java new file mode 100644 index 0000000000..2f9443daea --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/domain/User.java @@ -0,0 +1,23 @@ +package org.baeldung.embedded.domain; + +public class User { + + private String name; + private String hobby; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getHobby() { + return hobby; + } + + public void setHobby(String hobby) { + this.hobby = hobby; + } +} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/service/UserService.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/service/UserService.java new file mode 100644 index 0000000000..76696e12c2 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/service/UserService.java @@ -0,0 +1,38 @@ +package org.baeldung.embedded.service; + +import java.util.ArrayList; +import java.util.List; + +import org.baeldung.embedded.domain.User; +import org.springframework.stereotype.Service; + +@Service +public class UserService { + private List users = new ArrayList<>(); + + public void addUser(String name) { + User user = new User(); + user.setName(name); + if (name == "HarryPotter") { + user.setHobby("Quidditch"); + } else { + user.setHobby("MuggleActivity"); + } + users.add(user); + } + + public User getUser(String name) { + for (User user : users) { + if (user.getName() + .equalsIgnoreCase(name)) { + return user; + } + } + + User user = new User(); + user.setName(name); + user.setHobby("None"); + + return user; + } +} diff --git a/spring-rest-embedded-tomcat/src/main/webapp/emptyFile b/spring-rest-embedded-tomcat/src/main/webapp/emptyFile new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatApp.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatApp.java new file mode 100644 index 0000000000..f340f6c837 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatApp.java @@ -0,0 +1,70 @@ +package org.baeldung.embedded; + +import java.io.File; +import java.util.concurrent.CountDownLatch; +import org.apache.catalina.Context; +import org.apache.catalina.startup.Tomcat; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.WebApplicationContextUtils; + +public class EmbeddedTomcatApp { + + private Tomcat tomcatInstance; + private WebApplicationContext webApplicationContext; + private CountDownLatch started = new CountDownLatch(1); + + public void start() throws Exception { + tomcatInstance = new Tomcat(); + tomcatInstance.setBaseDir(new File(getClass().getResource(".") + .toURI()).getAbsolutePath()); // Tomcat's temporary directory + tomcatInstance.setPort(0); + + Context webapp = tomcatInstance.addWebapp("", new File("src/main/webapp/").getAbsolutePath()); + + webapp.addLifecycleListener(event -> { + if (event.getType() + .equals("after_stop")) { + started.countDown(); + } else if (event.getType() + .equals("after_start")) { + webApplicationContext = WebApplicationContextUtils + .findWebApplicationContext(webapp.getServletContext()); + + ((ConfigurableListableBeanFactory) webApplicationContext + .getAutowireCapableBeanFactory()).registerSingleton("baseUrl", getBaseUrl()); + + started.countDown(); + } + }); + + tomcatInstance.start(); + started.await(); + } + + public Tomcat getTomcatInstance() { + return this.tomcatInstance; + } + + public String getBaseUrl() { + return String.format("http://localhost:%d%s", getLocalPort(), getWebApplicationContext().getServletContext() + .getContextPath()); + } + + public int getLocalPort() { + return tomcatInstance.getConnector() + .getLocalPort(); + } + + public WebApplicationContext getWebApplicationContext() { + return webApplicationContext; + } + + public boolean isStarted() { + return started.getCount() == 0; + } + + public boolean isStartedSucessfully() { + return webApplicationContext != null; + } +} diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatRunner.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatRunner.java new file mode 100644 index 0000000000..1bf15556e8 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatRunner.java @@ -0,0 +1,45 @@ +package org.baeldung.embedded; + +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.Statement; + +public class EmbeddedTomcatRunner extends BlockJUnit4ClassRunner { + + public EmbeddedTomcatRunner(Class klass) throws InitializationError { + super(klass); + } + + // use one static Tomcat instance shared across all tests + private static EmbeddedTomcatApp embeddedTomcatApp = new EmbeddedTomcatApp(); + + @Override + protected Statement classBlock(RunNotifier notifier) { + ensureSharedTomcatStarted(); + Statement result = super.classBlock(notifier); + return result; + } + + private void ensureSharedTomcatStarted() { + if (!embeddedTomcatApp.isStarted()) { + try { + embeddedTomcatApp.start(); + } catch (Exception e) { + throw new RuntimeException("Error while starting embedded Tomcat server", e); + } + } + } + + @Override + protected Object createTest() throws Exception { + if (!embeddedTomcatApp.isStartedSucessfully()) { + throw new RuntimeException("Tomcat server not started successfully. Skipping test"); + } + Object testInstance = super.createTest(); + embeddedTomcatApp.getWebApplicationContext() + .getAutowireCapableBeanFactory() + .autowireBean(testInstance); + return testInstance; + } +} \ No newline at end of file diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/UserIntegrationTest.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/UserIntegrationTest.java new file mode 100644 index 0000000000..1c5d482171 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/UserIntegrationTest.java @@ -0,0 +1,60 @@ +package org.baeldung.embedded; + +import java.io.IOException; +import java.util.Map; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.baeldung.embedded.service.UserService; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(EmbeddedTomcatRunner.class) +public class UserIntegrationTest { + + @Autowired + protected String baseUrl; + + @Autowired + private UserService userService; + + private String userName = "HarryPotter"; + + @Before + public void setUp() { + userService.addUser(userName); + } + + @Test + public void givenUserName_whenSendGetForHarryPotter_thenHobbyQuidditch() throws IOException { + String url = baseUrl + "/user/" + userName; + + HttpClient httpClient = HttpClientBuilder.create() + .build(); + HttpGet getUserRequest = new HttpGet(url); + getUserRequest.addHeader("Content-type", "application/json"); + HttpResponse response = httpClient.execute(getUserRequest); + + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine() + .getStatusCode()); + + HttpEntity responseEntity = response.getEntity(); + + Assert.assertNotNull(responseEntity); + + ObjectMapper mapper = new ObjectMapper(); + String retSrc = EntityUtils.toString(responseEntity); + Map result = mapper.readValue(retSrc, Map.class); + + Assert.assertEquals("Quidditch", result.get("hobby")); + } +} diff --git a/spring-rest-shell/README.md b/spring-rest-shell/README.md index 06e18450c6..901d9a51ee 100644 --- a/spring-rest-shell/README.md +++ b/spring-rest-shell/README.md @@ -2,4 +2,4 @@ ### Relevant Articles -- [Spring REST Shell](http://www.baeldung.com/) \ No newline at end of file +- [Spring REST Shell](http://www.baeldung.com/spring-rest-shell) \ No newline at end of file diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index 3a8bc1f3aa..6566c0eea6 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -122,6 +122,25 @@ jstl-api ${jstl.version} + + + org.springframework.security + spring-security-acl + + + org.springframework.security + spring-security-config + + + org.springframework + spring-context-support + + + net.sf.ehcache + ehcache-core + 2.6.11 + jar + diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/ACLContext.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/ACLContext.java new file mode 100644 index 0000000000..63a4ea58ef --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/ACLContext.java @@ -0,0 +1,80 @@ +package org.baeldung.acl.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.cache.ehcache.EhCacheFactoryBean; +import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.acls.AclPermissionCacheOptimizer; +import org.springframework.security.acls.AclPermissionEvaluator; +import org.springframework.security.acls.domain.AclAuthorizationStrategy; +import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl; +import org.springframework.security.acls.domain.ConsoleAuditLogger; +import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; +import org.springframework.security.acls.domain.EhCacheBasedAclCache; +import org.springframework.security.acls.jdbc.BasicLookupStrategy; +import org.springframework.security.acls.jdbc.JdbcMutableAclService; +import org.springframework.security.acls.jdbc.LookupStrategy; +import org.springframework.security.acls.model.PermissionGrantingStrategy; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +@Configuration +@EnableAutoConfiguration +public class ACLContext { + + @Autowired + DataSource dataSource; + + @Bean + public EhCacheBasedAclCache aclCache() { + return new EhCacheBasedAclCache(aclEhCacheFactoryBean().getObject(), permissionGrantingStrategy(), aclAuthorizationStrategy()); + } + + @Bean + public EhCacheFactoryBean aclEhCacheFactoryBean() { + EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean(); + ehCacheFactoryBean.setCacheManager(aclCacheManager().getObject()); + ehCacheFactoryBean.setCacheName("aclCache"); + return ehCacheFactoryBean; + } + + @Bean + public EhCacheManagerFactoryBean aclCacheManager() { + return new EhCacheManagerFactoryBean(); + } + + @Bean + public PermissionGrantingStrategy permissionGrantingStrategy() { + return new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()); + } + + @Bean + public AclAuthorizationStrategy aclAuthorizationStrategy() { + return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN")); + } + + @Bean + public MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() { + DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); + AclPermissionEvaluator permissionEvaluator = new AclPermissionEvaluator(aclService()); + expressionHandler.setPermissionEvaluator(permissionEvaluator); + expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService())); + return expressionHandler; + } + + @Bean + public LookupStrategy lookupStrategy() { + return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger()); + } + + @Bean + public JdbcMutableAclService aclService() { + return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache()); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java new file mode 100644 index 0000000000..110c4a6d24 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java @@ -0,0 +1,21 @@ +package org.baeldung.acl.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; + +@Configuration +@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) +public class AclMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration { + + @Autowired + MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler; + + @Override + protected MethodSecurityExpressionHandler createExpressionHandler() { + return defaultMethodSecurityExpressionHandler; + } + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java new file mode 100644 index 0000000000..9b87efa92c --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java @@ -0,0 +1,16 @@ +package org.baeldung.acl.config; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = "org.baeldung.acl.persistence.dao") +@PropertySource("classpath:org.baeldung.acl.datasource.properties") +@EntityScan(basePackages={ "org.baeldung.acl.persistence.entity" }) +public class JPAPersistenceConfig { + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java new file mode 100644 index 0000000000..8662c88d6c --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java @@ -0,0 +1,24 @@ +package org.baeldung.acl.persistence.dao; + +import java.util.List; + +import org.baeldung.acl.persistence.entity.NoticeMessage; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.security.access.prepost.PostAuthorize; +import org.springframework.security.access.prepost.PostFilter; +import org.springframework.security.access.prepost.PreAuthorize; + +public interface NoticeMessageRepository extends JpaRepository{ + + @PostFilter("hasPermission(filterObject, 'READ')") + List findAll(); + + @PostAuthorize("hasPermission(returnObject, 'READ')") + NoticeMessage findById(Integer id); + + @SuppressWarnings("unchecked") + @PreAuthorize("hasPermission(#noticeMessage, 'WRITE')") + NoticeMessage save(@Param("noticeMessage")NoticeMessage noticeMessage); + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java new file mode 100644 index 0000000000..23f01a8edb --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java @@ -0,0 +1,29 @@ +package org.baeldung.acl.persistence.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="system_message") +public class NoticeMessage { + + @Id + @Column + private Integer id; + @Column + private String content; + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + public String getContent() { + return content; + } + public void setContent(String content) { + this.content = content; + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/acl-data.sql b/spring-security-mvc-boot/src/main/resources/acl-data.sql new file mode 100644 index 0000000000..6c01eaacc2 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/acl-data.sql @@ -0,0 +1,28 @@ +INSERT INTO system_message(id,content) VALUES (1,'First Level Message'); +INSERT INTO system_message(id,content) VALUES (2,'Second Level Message'); +INSERT INTO system_message(id,content) VALUES (3,'Third Level Message'); + +INSERT INTO acl_class (id, class) VALUES +(1, 'org.baeldung.acl.persistence.entity.NoticeMessage'); + +INSERT INTO acl_sid (id, principal, sid) VALUES +(1, 1, 'manager'), +(2, 1, 'hr'), +(3, 1, 'admin'), +(4, 0, 'ROLE_EDITOR'); + +INSERT INTO acl_object_identity (id, object_id_class, object_id_identity, parent_object, owner_sid, entries_inheriting) VALUES +(1, 1, 1, NULL, 3, 0), +(2, 1, 2, NULL, 3, 0), +(3, 1, 3, NULL, 3, 0) +; + +INSERT INTO acl_entry (id, acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_failure) VALUES +(1, 1, 1, 1, 1, 1, 1, 1), +(2, 1, 2, 1, 2, 1, 1, 1), +(3, 1, 3, 4, 1, 1, 1, 1), +(4, 2, 1, 2, 1, 1, 1, 1), +(5, 2, 2, 4, 1, 1, 1, 1), +(6, 3, 1, 4, 1, 1, 1, 1), +(7, 3, 2, 4, 2, 1, 1, 1) +; \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/acl-schema.sql b/spring-security-mvc-boot/src/main/resources/acl-schema.sql new file mode 100644 index 0000000000..58e9394b2b --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/acl-schema.sql @@ -0,0 +1,58 @@ +create table system_message (id integer not null, content varchar(255), primary key (id)); + +CREATE TABLE IF NOT EXISTS acl_sid ( + id bigint(20) NOT NULL AUTO_INCREMENT, + principal tinyint(1) NOT NULL, + sid varchar(100) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_1 (sid,principal) +); + +CREATE TABLE IF NOT EXISTS acl_class ( + id bigint(20) NOT NULL AUTO_INCREMENT, + class varchar(255) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_2 (class) +); + +CREATE TABLE IF NOT EXISTS acl_entry ( + id bigint(20) NOT NULL AUTO_INCREMENT, + acl_object_identity bigint(20) NOT NULL, + ace_order int(11) NOT NULL, + sid bigint(20) NOT NULL, + mask int(11) NOT NULL, + granting tinyint(1) NOT NULL, + audit_success tinyint(1) NOT NULL, + audit_failure tinyint(1) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_4 (acl_object_identity,ace_order) +); + +CREATE TABLE IF NOT EXISTS acl_object_identity ( + id bigint(20) NOT NULL AUTO_INCREMENT, + object_id_class bigint(20) NOT NULL, + object_id_identity bigint(20) NOT NULL, + parent_object bigint(20) DEFAULT NULL, + owner_sid bigint(20) DEFAULT NULL, + entries_inheriting tinyint(1) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_3 (object_id_class,object_id_identity) +); + +ALTER TABLE acl_entry +ADD FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity(id); + +ALTER TABLE acl_entry +ADD FOREIGN KEY (sid) REFERENCES acl_sid(id); + +-- +-- Constraints for table acl_object_identity +-- +ALTER TABLE acl_object_identity +ADD FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id); + +ALTER TABLE acl_object_identity +ADD FOREIGN KEY (object_id_class) REFERENCES acl_class (id); + +ALTER TABLE acl_object_identity +ADD FOREIGN KEY (owner_sid) REFERENCES acl_sid (id); \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/org.baeldung.acl.datasource.properties b/spring-security-mvc-boot/src/main/resources/org.baeldung.acl.datasource.properties new file mode 100644 index 0000000000..739dd3f07c --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/org.baeldung.acl.datasource.properties @@ -0,0 +1,12 @@ +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.driverClassName=org.h2.Driver +spring.jpa.hibernate.ddl-auto=update +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect + +spring.h2.console.path=/myconsole +spring.h2.console.enabled=true +spring.datasource.initialize=true +spring.datasource.schema=classpath:acl-schema.sql +spring.datasource.data=classpath:acl-data.sql \ No newline at end of file diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclIntegrationTest.java new file mode 100644 index 0000000000..38e1a2a9e7 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclIntegrationTest.java @@ -0,0 +1,119 @@ +package org.baeldung.acl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + +import org.baeldung.acl.persistence.dao.NoticeMessageRepository; +import org.baeldung.acl.persistence.entity.NoticeMessage; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; +import org.springframework.test.context.transaction.TransactionalTestExecutionListener; +import org.springframework.test.context.web.ServletTestExecutionListener; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +@TestExecutionListeners(listeners={ServletTestExecutionListener.class, + DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + TransactionalTestExecutionListener.class, + WithSecurityContextTestExecutionListener.class}) +public class SpringAclIntegrationTest extends AbstractJUnit4SpringContextTests{ + + private static Integer FIRST_MESSAGE_ID = 1; + private static Integer SECOND_MESSAGE_ID = 2; + private static Integer THIRD_MESSAGE_ID = 3; + private static String EDITTED_CONTENT = "EDITED"; + + @Configuration + @ComponentScan("org.baeldung.acl.*") + public static class SpringConfig { + + } + + @Autowired + NoticeMessageRepository repo; + + @Test + @WithMockUser(username="manager") + public void givenUsernameManager_whenFindAllMessage_thenReturnFirstMessage(){ + List details = repo.findAll(); + assertNotNull(details); + assertEquals(1,details.size()); + assertEquals(FIRST_MESSAGE_ID,details.get(0).getId()); + } + + @Test + @WithMockUser(username="manager") + public void givenUsernameManager_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenOK(){ + NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID); + assertNotNull(firstMessage); + assertEquals(FIRST_MESSAGE_ID,firstMessage.getId()); + + firstMessage.setContent(EDITTED_CONTENT); + repo.save(firstMessage); + + NoticeMessage editedFirstMessage = repo.findById(FIRST_MESSAGE_ID); + assertNotNull(editedFirstMessage); + assertEquals(FIRST_MESSAGE_ID,editedFirstMessage.getId()); + assertEquals(EDITTED_CONTENT,editedFirstMessage.getContent()); + } + + @Test + @WithMockUser(username="hr") + public void givenUsernameHr_whenFindMessageById2_thenOK(){ + NoticeMessage secondMessage = repo.findById(SECOND_MESSAGE_ID); + assertNotNull(secondMessage); + assertEquals(SECOND_MESSAGE_ID,secondMessage.getId()); + } + + @Test(expected=AccessDeniedException.class) + @WithMockUser(username="hr") + public void givenUsernameHr_whenUpdateMessageWithId2_thenFail(){ + NoticeMessage secondMessage = new NoticeMessage(); + secondMessage.setId(SECOND_MESSAGE_ID); + secondMessage.setContent(EDITTED_CONTENT); + repo.save(secondMessage); + } + + @Test + @WithMockUser(roles={"EDITOR"}) + public void givenRoleEditor_whenFindAllMessage_thenReturnThreeMessage(){ + List details = repo.findAll(); + assertNotNull(details); + assertEquals(3,details.size()); + } + + @Test + @WithMockUser(roles={"EDITOR"}) + public void givenRoleEditor_whenUpdateThirdMessage_thenOK(){ + NoticeMessage thirdMessage = new NoticeMessage(); + thirdMessage.setId(THIRD_MESSAGE_ID); + thirdMessage.setContent(EDITTED_CONTENT); + repo.save(thirdMessage); + } + + @Test(expected=AccessDeniedException.class) + @WithMockUser(roles={"EDITOR"}) + public void givenRoleEditor_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenFail(){ + NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID); + assertNotNull(firstMessage); + assertEquals(FIRST_MESSAGE_ID,firstMessage.getId()); + firstMessage.setContent(EDITTED_CONTENT); + repo.save(firstMessage); + } +} + \ No newline at end of file diff --git a/struts2/README.md b/struts-2/README.md similarity index 100% rename from struts2/README.md rename to struts-2/README.md diff --git a/struts2/WebContent/WEB-INF/web.xml b/struts-2/WebContent/WEB-INF/web.xml similarity index 100% rename from struts2/WebContent/WEB-INF/web.xml rename to struts-2/WebContent/WEB-INF/web.xml diff --git a/struts2/WebContent/input.jsp b/struts-2/WebContent/input.jsp similarity index 100% rename from struts2/WebContent/input.jsp rename to struts-2/WebContent/input.jsp diff --git a/struts2/WebContent/result.jsp b/struts-2/WebContent/result.jsp similarity index 100% rename from struts2/WebContent/result.jsp rename to struts-2/WebContent/result.jsp diff --git a/struts2/pom.xml b/struts-2/pom.xml similarity index 100% rename from struts2/pom.xml rename to struts-2/pom.xml diff --git a/struts2/src/main/java/com/baeldung/struts/CarAction.java b/struts-2/src/main/java/com/baeldung/struts/CarAction.java similarity index 100% rename from struts2/src/main/java/com/baeldung/struts/CarAction.java rename to struts-2/src/main/java/com/baeldung/struts/CarAction.java diff --git a/struts2/src/main/java/com/baeldung/struts/CarMessageService.java b/struts-2/src/main/java/com/baeldung/struts/CarMessageService.java similarity index 100% rename from struts2/src/main/java/com/baeldung/struts/CarMessageService.java rename to struts-2/src/main/java/com/baeldung/struts/CarMessageService.java diff --git a/struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java b/struts-2/src/test/java/com/baeldung/struts/test/CarActionTest.java similarity index 100% rename from struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java rename to struts-2/src/test/java/com/baeldung/struts/test/CarActionTest.java diff --git a/testing-modules/README.md b/testing-modules/README.md new file mode 100644 index 0000000000..3fbeea6188 --- /dev/null +++ b/testing-modules/README.md @@ -0,0 +1,3 @@ + +## Testing Modules + diff --git a/gatling/README.md b/testing-modules/gatling/README.md similarity index 100% rename from gatling/README.md rename to testing-modules/gatling/README.md diff --git a/gatling/pom.xml b/testing-modules/gatling/pom.xml similarity index 100% rename from gatling/pom.xml rename to testing-modules/gatling/pom.xml diff --git a/gatling/src/test/resources/gatling.conf b/testing-modules/gatling/src/test/resources/gatling.conf similarity index 100% rename from gatling/src/test/resources/gatling.conf rename to testing-modules/gatling/src/test/resources/gatling.conf diff --git a/gatling/src/test/resources/logback.xml b/testing-modules/gatling/src/test/resources/logback.xml similarity index 100% rename from gatling/src/test/resources/logback.xml rename to testing-modules/gatling/src/test/resources/logback.xml diff --git a/gatling/src/test/resources/recorder.conf b/testing-modules/gatling/src/test/resources/recorder.conf similarity index 100% rename from gatling/src/test/resources/recorder.conf rename to testing-modules/gatling/src/test/resources/recorder.conf diff --git a/gatling/src/test/scala/Engine.scala b/testing-modules/gatling/src/test/scala/Engine.scala similarity index 100% rename from gatling/src/test/scala/Engine.scala rename to testing-modules/gatling/src/test/scala/Engine.scala diff --git a/gatling/src/test/scala/IDEPathHelper.scala b/testing-modules/gatling/src/test/scala/IDEPathHelper.scala similarity index 100% rename from gatling/src/test/scala/IDEPathHelper.scala rename to testing-modules/gatling/src/test/scala/IDEPathHelper.scala diff --git a/gatling/src/test/scala/Recorder.scala b/testing-modules/gatling/src/test/scala/Recorder.scala similarity index 100% rename from gatling/src/test/scala/Recorder.scala rename to testing-modules/gatling/src/test/scala/Recorder.scala diff --git a/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala b/testing-modules/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala similarity index 100% rename from gatling/src/test/scala/org/baeldung/RecordedSimulation.scala rename to testing-modules/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala diff --git a/groovy-spock/README.md b/testing-modules/groovy-spock/README.md similarity index 100% rename from groovy-spock/README.md rename to testing-modules/groovy-spock/README.md diff --git a/groovy-spock/pom.xml b/testing-modules/groovy-spock/pom.xml similarity index 97% rename from groovy-spock/pom.xml rename to testing-modules/groovy-spock/pom.xml index d9b51c5e1a..f4e61e6786 100644 --- a/groovy-spock/pom.xml +++ b/testing-modules/groovy-spock/pom.xml @@ -17,6 +17,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/groovy-spock/src/test/groovy/FirstSpecification.groovy b/testing-modules/groovy-spock/src/test/groovy/FirstSpecification.groovy similarity index 100% rename from groovy-spock/src/test/groovy/FirstSpecification.groovy rename to testing-modules/groovy-spock/src/test/groovy/FirstSpecification.groovy diff --git a/groovy-spock/src/test/groovy/Notifier.groovy b/testing-modules/groovy-spock/src/test/groovy/Notifier.groovy similarity index 100% rename from groovy-spock/src/test/groovy/Notifier.groovy rename to testing-modules/groovy-spock/src/test/groovy/Notifier.groovy diff --git a/groovy-spock/src/test/groovy/PaymentGateway.groovy b/testing-modules/groovy-spock/src/test/groovy/PaymentGateway.groovy similarity index 100% rename from groovy-spock/src/test/groovy/PaymentGateway.groovy rename to testing-modules/groovy-spock/src/test/groovy/PaymentGateway.groovy diff --git a/junit5/README.md b/testing-modules/junit-5/README.md similarity index 91% rename from junit5/README.md rename to testing-modules/junit-5/README.md index d0fa19bd83..20ecb1eeab 100644 --- a/junit5/README.md +++ b/testing-modules/junit-5/README.md @@ -7,3 +7,4 @@ - [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) - [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) - [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) +- [JUnit 5 – @RunWith](http://www.baeldung.com/junit-5-runwith) diff --git a/junit5/pom.xml b/testing-modules/junit-5/pom.xml similarity index 96% rename from junit5/pom.xml rename to testing-modules/junit-5/pom.xml index b8a7622b3d..2be8937d04 100644 --- a/junit5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -4,22 +4,23 @@ 4.0.0 - junit5 + junit-5 1.0-SNAPSHOT - junit5 + junit-5 Intro to JUnit 5 com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ UTF-8 1.8 - 5.0.1 + 5.0.2 1.0.1 4.12.1 2.8.2 @@ -126,4 +127,4 @@
- \ No newline at end of file + diff --git a/junit5/src/main/java/com/baeldung/junit5/Greetings.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/Greetings.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/User.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/User.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/User.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/User.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java diff --git a/junit5/src/test/java/com/baeldung/AssertionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/AssertionUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/AssumptionUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/AssumptionUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/AssumptionUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/DynamicTestsExample.java b/testing-modules/junit-5/src/test/java/com/baeldung/DynamicTestsExample.java similarity index 100% rename from junit5/src/test/java/com/baeldung/DynamicTestsExample.java rename to testing-modules/junit-5/src/test/java/com/baeldung/DynamicTestsExample.java diff --git a/junit5/src/test/java/com/baeldung/EmployeesTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/EmployeesTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java diff --git a/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/ExceptionUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/FirstUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/FirstUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/GreetingsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java similarity index 99% rename from junit5/src/test/java/com/baeldung/GreetingsTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java index e894d5857c..efde4e7404 100644 --- a/junit5/src/test/java/com/baeldung/GreetingsTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java @@ -16,4 +16,4 @@ public class GreetingsTest { assertTrue("Hello".equals(Greetings.sayHello())); } -} +} \ No newline at end of file diff --git a/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/LiveTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/LiveTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java diff --git a/junit5/src/test/java/com/baeldung/NestedUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/NestedUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/NestedUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/NestedUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/RepeatedTestExample.java b/testing-modules/junit-5/src/test/java/com/baeldung/RepeatedTestExample.java similarity index 100% rename from junit5/src/test/java/com/baeldung/RepeatedTestExample.java rename to testing-modules/junit-5/src/test/java/com/baeldung/RepeatedTestExample.java diff --git a/junit5/src/test/java/com/baeldung/StringUtils.java b/testing-modules/junit-5/src/test/java/com/baeldung/StringUtils.java similarity index 100% rename from junit5/src/test/java/com/baeldung/StringUtils.java rename to testing-modules/junit-5/src/test/java/com/baeldung/StringUtils.java diff --git a/junit5/src/test/java/com/baeldung/TaggedUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/TaggedUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/TaggedUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/TaggedUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/TestLauncher.java b/testing-modules/junit-5/src/test/java/com/baeldung/TestLauncher.java similarity index 100% rename from junit5/src/test/java/com/baeldung/TestLauncher.java rename to testing-modules/junit-5/src/test/java/com/baeldung/TestLauncher.java diff --git a/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java diff --git a/junit5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java diff --git a/junit5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java diff --git a/junit5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java diff --git a/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/LoggingExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/LoggingExtension.java diff --git a/junit5/src/test/java/com/baeldung/helpers/Employee.java b/testing-modules/junit-5/src/test/java/com/baeldung/helpers/Employee.java similarity index 100% rename from junit5/src/test/java/com/baeldung/helpers/Employee.java rename to testing-modules/junit-5/src/test/java/com/baeldung/helpers/Employee.java diff --git a/junit5/src/test/java/com/baeldung/helpers/EmployeeDao.java b/testing-modules/junit-5/src/test/java/com/baeldung/helpers/EmployeeDao.java similarity index 100% rename from junit5/src/test/java/com/baeldung/helpers/EmployeeDao.java rename to testing-modules/junit-5/src/test/java/com/baeldung/helpers/EmployeeDao.java diff --git a/junit5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java b/testing-modules/junit-5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java similarity index 100% rename from junit5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java rename to testing-modules/junit-5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java diff --git a/junit5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java b/testing-modules/junit-5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java similarity index 100% rename from junit5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java rename to testing-modules/junit-5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java diff --git a/junit5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java diff --git a/junit5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java similarity index 99% rename from junit5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java index e7a8a1c1e7..3b89508c88 100644 --- a/junit5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java @@ -18,4 +18,4 @@ public class GreetingsSpringTest { assertTrue("Hello".equals(Greetings.sayHello())); } -} +} \ No newline at end of file diff --git a/junit5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java similarity index 100% rename from junit5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java diff --git a/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java diff --git a/junit5/src/test/java/com/baeldung/param/Person.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/Person.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/Person.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/Person.java diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidator.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidator.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/PersonValidator.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidator.java diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java diff --git a/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java diff --git a/junit5/src/test/java/com/baeldung/suites/AllTests.java b/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java similarity index 100% rename from junit5/src/test/java/com/baeldung/suites/AllTests.java rename to testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java diff --git a/junit5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/testing-modules/junit-5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension similarity index 100% rename from junit5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension rename to testing-modules/junit-5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension diff --git a/junit5/src/test/resources/com/baeldung/extensions/application.properties b/testing-modules/junit-5/src/test/resources/com/baeldung/extensions/application.properties similarity index 100% rename from junit5/src/test/resources/com/baeldung/extensions/application.properties rename to testing-modules/junit-5/src/test/resources/com/baeldung/extensions/application.properties diff --git a/junit5/src/test/resources/com/baeldung/helpers/jdbc.properties b/testing-modules/junit-5/src/test/resources/com/baeldung/helpers/jdbc.properties similarity index 100% rename from junit5/src/test/resources/com/baeldung/helpers/jdbc.properties rename to testing-modules/junit-5/src/test/resources/com/baeldung/helpers/jdbc.properties diff --git a/mockito2/.gitignore b/testing-modules/mockito-2/.gitignore similarity index 100% rename from mockito2/.gitignore rename to testing-modules/mockito-2/.gitignore diff --git a/mockito2/README.md b/testing-modules/mockito-2/README.md similarity index 100% rename from mockito2/README.md rename to testing-modules/mockito-2/README.md diff --git a/mockito2/pom.xml b/testing-modules/mockito-2/pom.xml similarity index 96% rename from mockito2/pom.xml rename to testing-modules/mockito-2/pom.xml index a7c4683c30..0291ac4ec1 100644 --- a/mockito2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.baeldung - mockito2 + mockito-2 0.0.1-SNAPSHOT jar mockito-2-with-java8 @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/JobPosition.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/JobPosition.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/JobPosition.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/JobPosition.java diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/JobService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/JobService.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/JobService.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/JobService.java diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/Person.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/Person.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/Person.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/Person.java diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/UnemploymentService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/UnemploymentService.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/UnemploymentService.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/UnemploymentService.java diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/UnemploymentServiceImpl.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/UnemploymentServiceImpl.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/UnemploymentServiceImpl.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/UnemploymentServiceImpl.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java new file mode 100644 index 0000000000..43b39d6859 --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.mockito.java8; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.util.List; + +import org.junit.Test; +import org.mockito.exceptions.base.MockitoAssertionError; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.VerificationCollector; + +public class LazyVerificationTest { + + @Test + public void whenLazilyVerified_thenReportsMultipleFailures() { + VerificationCollector collector = MockitoJUnit.collector() + .assertLazily(); + + List mockList = mock(List.class); + verify(mockList).add("one"); + verify(mockList).clear(); + + try { + collector.collectAndReport(); + } catch (MockitoAssertionError error) { + assertTrue(error.getMessage() + .contains("1. Wanted but not invoked:")); + assertTrue(error.getMessage() + .contains("2. Wanted but not invoked:")); + } + } +} diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java diff --git a/mockito/.gitignore b/testing-modules/mockito/.gitignore similarity index 100% rename from mockito/.gitignore rename to testing-modules/mockito/.gitignore diff --git a/mockito/README.md b/testing-modules/mockito/README.md similarity index 87% rename from mockito/README.md rename to testing-modules/mockito/README.md index 2407a5c3c5..0d6f69a64f 100644 --- a/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -11,3 +11,4 @@ - [Mockito’s Mock Methods](http://www.baeldung.com/mockito-mock-methods) - [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock) - [Mocking Exception Throwing using Mockito](http://www.baeldung.com/mockito-exceptions) +- [Mocking Void Methods with Mockito](http://www.baeldung.com/mockito-void-methods) diff --git a/mockito/pom.xml b/testing-modules/mockito/pom.xml similarity index 97% rename from mockito/pom.xml rename to testing-modules/mockito/pom.xml index 19dd2f6468..aa3dd9b20a 100644 --- a/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/mockito/src/main/resources/logback.xml b/testing-modules/mockito/src/main/resources/logback.xml similarity index 100% rename from mockito/src/main/resources/logback.xml rename to testing-modules/mockito/src/main/resources/logback.xml diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java new file mode 100644 index 0000000000..3824de619c --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java @@ -0,0 +1,10 @@ +package org.baeldung.mockito; + +public class FinalList extends MyList { + + @Override + public int size() { + return 1; + } + +} diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockFinals.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockFinals.java new file mode 100644 index 0000000000..5f064e1355 --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockFinals.java @@ -0,0 +1,35 @@ +package org.baeldung.mockito; + +import org.junit.Test; + +import static org.junit.Assert.assertNotEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class MockFinals { + + @Test + public void whenMockFinalClassMockWorks() { + + FinalList finalList = new FinalList(); + + FinalList mock = mock(FinalList.class); + when(mock.size()).thenReturn(2); + + assertNotEquals(mock.size(), finalList.size()); + + } + + @Test + public void whenMockFinalMethodMockWorks() { + + MyList myList = new MyList(); + + MyList mock = mock(MyList.class); + when(mock.finalMethod()).thenReturn(1); + + assertNotEquals(mock.finalMethod(), myList.finalMethod()); + } + + + } diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MyDictionary.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MyList.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyList.java similarity index 84% rename from mockito/src/test/java/org/baeldung/mockito/MyList.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MyList.java index 0b501225ad..4fcddb3164 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MyList.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyList.java @@ -19,4 +19,7 @@ class MyList extends AbstractList { // no-op } + final public int finalMethod() { + return 0; + } } diff --git a/testing-modules/mockito/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/testing-modules/mockito/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 0000000000..ca6ee9cea8 --- /dev/null +++ b/testing-modules/mockito/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file diff --git a/mocks/README.md b/testing-modules/mocks/README.md similarity index 82% rename from mocks/README.md rename to testing-modules/mocks/README.md index 15370b812b..d7b817c518 100644 --- a/mocks/README.md +++ b/testing-modules/mocks/README.md @@ -1,6 +1,5 @@ ## Relevant articles: -- [Introduction to MockServer](http://www.baeldung.com/mockserver) - [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage) - [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) - [JMockit 101](http://www.baeldung.com/jmockit-101) diff --git a/mocks/jmockit/README.md b/testing-modules/mocks/jmockit/README.md similarity index 100% rename from mocks/jmockit/README.md rename to testing-modules/mocks/jmockit/README.md diff --git a/mocks/jmockit/pom.xml b/testing-modules/mocks/jmockit/pom.xml similarity index 94% rename from mocks/jmockit/pom.xml rename to testing-modules/mocks/jmockit/pom.xml index 173a981e09..d998cb6918 100644 --- a/mocks/jmockit/pom.xml +++ b/testing-modules/mocks/jmockit/pom.xml @@ -6,7 +6,7 @@ com.baeldung mocks 1.0.0-SNAPSHOT - ../pom.xml + ../ jmockit diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/ExpectationsCollaborator.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/ExpectationsCollaborator.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/ExpectationsCollaborator.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/ExpectationsCollaborator.java diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorIntegrationTest.java b/testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorIntegrationTest.java similarity index 100% rename from mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorIntegrationTest.java rename to testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorIntegrationTest.java diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsIntegrationTest.java b/testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsIntegrationTest.java similarity index 100% rename from mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsIntegrationTest.java rename to testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsIntegrationTest.java diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerIntegrationTest.java b/testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerIntegrationTest.java similarity index 100% rename from mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerIntegrationTest.java rename to testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerIntegrationTest.java diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingIntegrationTest.java b/testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingIntegrationTest.java similarity index 100% rename from mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingIntegrationTest.java rename to testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingIntegrationTest.java diff --git a/mocks/mock-comparisons/README.md b/testing-modules/mocks/mock-comparisons/README.md similarity index 100% rename from mocks/mock-comparisons/README.md rename to testing-modules/mocks/mock-comparisons/README.md diff --git a/mocks/mock-comparisons/pom.xml b/testing-modules/mocks/mock-comparisons/pom.xml similarity index 96% rename from mocks/mock-comparisons/pom.xml rename to testing-modules/mocks/mock-comparisons/pom.xml index 11bc59d710..84f1d20401 100644 --- a/mocks/mock-comparisons/pom.xml +++ b/testing-modules/mocks/mock-comparisons/pom.xml @@ -6,7 +6,7 @@ com.baeldung mocks 1.0.0-SNAPSHOT - ../pom.xml + ../ mock-comparisons diff --git a/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java b/testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java similarity index 100% rename from mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java rename to testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java diff --git a/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java b/testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java similarity index 100% rename from mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java rename to testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java diff --git a/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java b/testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java similarity index 100% rename from mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java rename to testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java diff --git a/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java b/testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java similarity index 100% rename from mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java rename to testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerIntegrationTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerIntegrationTest.java similarity index 100% rename from mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerIntegrationTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerIntegrationTest.java diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerIntegrationTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerIntegrationTest.java similarity index 100% rename from mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerIntegrationTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerIntegrationTest.java diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java similarity index 100% rename from mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java diff --git a/mocks/pom.xml b/testing-modules/mocks/pom.xml similarity index 92% rename from mocks/pom.xml rename to testing-modules/mocks/pom.xml index 84243a25d2..959c1851d6 100644 --- a/mocks/pom.xml +++ b/testing-modules/mocks/pom.xml @@ -6,7 +6,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - ../pom.xml + ../ mocks diff --git a/mockserver/README.md b/testing-modules/mockserver/README.md similarity index 100% rename from mockserver/README.md rename to testing-modules/mockserver/README.md diff --git a/mockserver/pom.xml b/testing-modules/mockserver/pom.xml similarity index 100% rename from mockserver/pom.xml rename to testing-modules/mockserver/pom.xml diff --git a/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java b/testing-modules/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java similarity index 100% rename from mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java rename to testing-modules/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java diff --git a/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java b/testing-modules/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java similarity index 100% rename from mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java rename to testing-modules/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java diff --git a/rest-assured/.gitignore b/testing-modules/rest-assured/.gitignore similarity index 100% rename from rest-assured/.gitignore rename to testing-modules/rest-assured/.gitignore diff --git a/rest-assured/README.md b/testing-modules/rest-assured/README.md similarity index 100% rename from rest-assured/README.md rename to testing-modules/rest-assured/README.md diff --git a/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml similarity index 99% rename from rest-assured/pom.xml rename to testing-modules/rest-assured/pom.xml index 3fca54c80f..0c0826c5c3 100644 --- a/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -10,6 +10,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java diff --git a/rest-assured/src/test/java/com/baeldung/restassured/Util.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/Util.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/Util.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/Util.java diff --git a/rest-assured/src/test/resources/employees.xml b/testing-modules/rest-assured/src/test/resources/employees.xml similarity index 100% rename from rest-assured/src/test/resources/employees.xml rename to testing-modules/rest-assured/src/test/resources/employees.xml diff --git a/rest-assured/src/test/resources/event_0.json b/testing-modules/rest-assured/src/test/resources/event_0.json similarity index 100% rename from rest-assured/src/test/resources/event_0.json rename to testing-modules/rest-assured/src/test/resources/event_0.json diff --git a/rest-assured/src/test/resources/logback.xml b/testing-modules/rest-assured/src/test/resources/logback.xml similarity index 100% rename from rest-assured/src/test/resources/logback.xml rename to testing-modules/rest-assured/src/test/resources/logback.xml diff --git a/rest-assured/src/test/resources/odds.json b/testing-modules/rest-assured/src/test/resources/odds.json similarity index 100% rename from rest-assured/src/test/resources/odds.json rename to testing-modules/rest-assured/src/test/resources/odds.json diff --git a/rest-assured/src/test/resources/teachers.xml b/testing-modules/rest-assured/src/test/resources/teachers.xml similarity index 100% rename from rest-assured/src/test/resources/teachers.xml rename to testing-modules/rest-assured/src/test/resources/teachers.xml diff --git a/rest-testing/.gitignore b/testing-modules/rest-testing/.gitignore similarity index 100% rename from rest-testing/.gitignore rename to testing-modules/rest-testing/.gitignore diff --git a/rest-testing/README.md b/testing-modules/rest-testing/README.md similarity index 85% rename from rest-testing/README.md rename to testing-modules/rest-testing/README.md index 37a53dd815..c6185de05f 100644 --- a/rest-testing/README.md +++ b/testing-modules/rest-testing/README.md @@ -10,3 +10,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock) - [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing) - [Testing a REST API with JBehave](http://www.baeldung.com/jbehave-rest-testing) +- [REST API Testing with Karate](http://www.baeldung.com/karate-rest-api-testing) diff --git a/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml similarity index 99% rename from rest-testing/pom.xml rename to testing-modules/rest-testing/pom.xml index 74ea5760c4..4b838720da 100644 --- a/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/rest-testing/src/main/resources/cucumber.json b/testing-modules/rest-testing/src/main/resources/cucumber.json similarity index 100% rename from rest-testing/src/main/resources/cucumber.json rename to testing-modules/rest-testing/src/main/resources/cucumber.json diff --git a/rest-testing/src/main/resources/karate/cucumber.feature b/testing-modules/rest-testing/src/main/resources/karate/cucumber.feature similarity index 100% rename from rest-testing/src/main/resources/karate/cucumber.feature rename to testing-modules/rest-testing/src/main/resources/karate/cucumber.feature diff --git a/rest-testing/src/main/resources/logback.xml b/testing-modules/rest-testing/src/main/resources/logback.xml similarity index 100% rename from rest-testing/src/main/resources/logback.xml rename to testing-modules/rest-testing/src/main/resources/logback.xml diff --git a/rest-testing/src/main/resources/wiremock_intro.json b/testing-modules/rest-testing/src/main/resources/wiremock_intro.json similarity index 100% rename from rest-testing/src/main/resources/wiremock_intro.json rename to testing-modules/rest-testing/src/main/resources/wiremock_intro.json diff --git a/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/AbstractStory.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/AbstractStory.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/AbstractStory.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/AbstractStory.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundSteps.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundSteps.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundSteps.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundSteps.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundStoryLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundStoryLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundStoryLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundStoryLiveTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeSteps.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeSteps.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeSteps.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeSteps.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeStoryLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeStoryLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeStoryLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeStoryLiveTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadSteps.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadSteps.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadSteps.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadSteps.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadStoryLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadStoryLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadStoryLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadStoryLiveTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseSteps.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseSteps.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseSteps.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseSteps.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseStoryLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseStoryLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseStoryLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseStoryLiveTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManagedLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManagedLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManagedLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManagedLiveTest.java diff --git a/rest-testing/src/test/java/org/baeldung/rest/GitHubUser.java b/testing-modules/rest-testing/src/test/java/org/baeldung/rest/GitHubUser.java similarity index 100% rename from rest-testing/src/test/java/org/baeldung/rest/GitHubUser.java rename to testing-modules/rest-testing/src/test/java/org/baeldung/rest/GitHubUser.java diff --git a/rest-testing/src/test/java/org/baeldung/rest/GithubBasicLiveTest.java b/testing-modules/rest-testing/src/test/java/org/baeldung/rest/GithubBasicLiveTest.java similarity index 100% rename from rest-testing/src/test/java/org/baeldung/rest/GithubBasicLiveTest.java rename to testing-modules/rest-testing/src/test/java/org/baeldung/rest/GithubBasicLiveTest.java diff --git a/rest-testing/src/test/java/org/baeldung/rest/RetrieveUtil.java b/testing-modules/rest-testing/src/test/java/org/baeldung/rest/RetrieveUtil.java similarity index 100% rename from rest-testing/src/test/java/org/baeldung/rest/RetrieveUtil.java rename to testing-modules/rest-testing/src/test/java/org/baeldung/rest/RetrieveUtil.java diff --git a/rest-testing/src/test/resources/github_user_not_found.story b/testing-modules/rest-testing/src/test/resources/github_user_not_found.story similarity index 100% rename from rest-testing/src/test/resources/github_user_not_found.story rename to testing-modules/rest-testing/src/test/resources/github_user_not_found.story diff --git a/rest-testing/src/test/resources/github_user_response_mediatype.story b/testing-modules/rest-testing/src/test/resources/github_user_response_mediatype.story similarity index 100% rename from rest-testing/src/test/resources/github_user_response_mediatype.story rename to testing-modules/rest-testing/src/test/resources/github_user_response_mediatype.story diff --git a/rest-testing/src/test/resources/github_user_response_payload.story b/testing-modules/rest-testing/src/test/resources/github_user_response_payload.story similarity index 100% rename from rest-testing/src/test/resources/github_user_response_payload.story rename to testing-modules/rest-testing/src/test/resources/github_user_response_payload.story diff --git a/rest-testing/src/test/resources/increase.story b/testing-modules/rest-testing/src/test/resources/increase.story similarity index 100% rename from rest-testing/src/test/resources/increase.story rename to testing-modules/rest-testing/src/test/resources/increase.story diff --git a/rest-testing/src/test/resources/karate/user.feature b/testing-modules/rest-testing/src/test/resources/karate/user.feature similarity index 100% rename from rest-testing/src/test/resources/karate/user.feature rename to testing-modules/rest-testing/src/test/resources/karate/user.feature diff --git a/selenium-junit-testng/README.md b/testing-modules/selenium-junit-testng/README.md similarity index 77% rename from selenium-junit-testng/README.md rename to testing-modules/selenium-junit-testng/README.md index 29393b956b..0137212290 100644 --- a/selenium-junit-testng/README.md +++ b/testing-modules/selenium-junit-testng/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: - [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng) -- [Testing a Site with Selenium / Webdriver](http://www.baeldung.com) - [Testing with Selenium/WebDriver and the Page Object Pattern](http://www.baeldung.com/selenium-webdriver-page-object) diff --git a/selenium-junit-testng/geckodriver.mac b/testing-modules/selenium-junit-testng/geckodriver.mac similarity index 100% rename from selenium-junit-testng/geckodriver.mac rename to testing-modules/selenium-junit-testng/geckodriver.mac diff --git a/selenium-junit-testng/pom.xml b/testing-modules/selenium-junit-testng/pom.xml similarity index 97% rename from selenium-junit-testng/pom.xml rename to testing-modules/selenium-junit-testng/pom.xml index faad194b59..14169e5749 100644 --- a/selenium-junit-testng/pom.xml +++ b/testing-modules/selenium-junit-testng/pom.xml @@ -9,6 +9,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/config/SeleniumConfig.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/config/SeleniumConfig.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/config/SeleniumConfig.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/config/SeleniumConfig.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/models/BaeldungAbout.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/models/BaeldungAbout.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/models/BaeldungAbout.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/models/BaeldungAbout.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungAboutPage.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungAboutPage.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungAboutPage.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungAboutPage.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungHomePage.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungHomePage.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungHomePage.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungHomePage.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/StartHerePage.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/StartHerePage.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/StartHerePage.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/StartHerePage.java diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumPageObjectLiveTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumPageObjectLiveTest.java similarity index 100% rename from selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumPageObjectLiveTest.java rename to testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumPageObjectLiveTest.java diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java similarity index 100% rename from selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java rename to testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java similarity index 100% rename from selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java rename to testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java diff --git a/testing/README.md b/testing-modules/testing/README.md similarity index 92% rename from testing/README.md rename to testing-modules/testing/README.md index 889f6706d4..143cb792cf 100644 --- a/testing/README.md +++ b/testing-modules/testing/README.md @@ -15,3 +15,4 @@ - [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support) - [Introduction to Lambda Behave](http://www.baeldung.com/lambda-behave) - [Introduction to Jukito](http://www.baeldung.com/jukito) +- [Custom JUnit 4 Test Runners](http://www.baeldung.com/junit-4-custom-runners) diff --git a/testing/pom.xml b/testing-modules/testing/pom.xml similarity index 99% rename from testing/pom.xml rename to testing-modules/testing/pom.xml index 8f5c6ddb3d..3ad503558f 100644 --- a/testing/pom.xml +++ b/testing-modules/testing/pom.xml @@ -10,6 +10,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/testing/src/main/java/com/baeldung/cucumber/Calculator.java b/testing-modules/testing/src/main/java/com/baeldung/cucumber/Calculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/cucumber/Calculator.java rename to testing-modules/testing/src/main/java/com/baeldung/cucumber/Calculator.java diff --git a/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java b/testing-modules/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/introductionjukito/Calculator.java rename to testing-modules/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java diff --git a/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java b/testing-modules/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java rename to testing-modules/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java diff --git a/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java b/testing-modules/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java rename to testing-modules/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java diff --git a/testing/src/main/java/com/baeldung/junit/Calculator.java b/testing-modules/testing/src/main/java/com/baeldung/junit/Calculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/junit/Calculator.java rename to testing-modules/testing/src/main/java/com/baeldung/junit/Calculator.java diff --git a/testing/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java b/testing-modules/testing/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java similarity index 100% rename from testing/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java rename to testing-modules/testing/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java diff --git a/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java b/testing-modules/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/lambdabehave/Calculator.java rename to testing-modules/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java diff --git a/testing/src/main/java/com/baeldung/testing/assertj/Dog.java b/testing-modules/testing/src/main/java/com/baeldung/testing/assertj/Dog.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/assertj/Dog.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/assertj/Dog.java diff --git a/testing/src/main/java/com/baeldung/testing/assertj/Person.java b/testing-modules/testing/src/main/java/com/baeldung/testing/assertj/Person.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/assertj/Person.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/assertj/Person.java diff --git a/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java b/testing-modules/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java diff --git a/testing/src/main/java/com/baeldung/testing/truth/User.java b/testing-modules/testing/src/main/java/com/baeldung/testing/truth/User.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/truth/User.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/truth/User.java diff --git a/testing/src/main/java/com/baeldung/testing/truth/UserSubject.java b/testing-modules/testing/src/main/java/com/baeldung/testing/truth/UserSubject.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/truth/UserSubject.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/truth/UserSubject.java diff --git a/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java rename to testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java diff --git a/testing/src/test/java/com/baeldung/junit/AdditionTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/AdditionTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java diff --git a/testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java b/testing-modules/testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java diff --git a/testing/src/test/java/com/baeldung/junit/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/CalculatorTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java diff --git a/testing/src/test/java/com/baeldung/junit/SubstractionTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/SubstractionTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java diff --git a/testing/src/test/java/com/baeldung/junit/SuiteTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/SuiteTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java diff --git a/testing/src/test/java/com/baeldung/junit/TestRunner.java b/testing-modules/testing/src/test/java/com/baeldung/junit/TestRunner.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/TestRunner.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/TestRunner.java diff --git a/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java diff --git a/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java b/testing-modules/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java similarity index 100% rename from testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java rename to testing-modules/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java diff --git a/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java rename to testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java diff --git a/testing/src/test/java/com/baeldung/mutation/test/PalindromeUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/mutation/test/PalindromeUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/mutation/test/PalindromeUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/mutation/test/PalindromeUnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/assertj/AssertJCoreUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJCoreUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/assertj/AssertJCoreUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJCoreUnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/assertj/AssertJGuavaUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJGuavaUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/assertj/AssertJGuavaUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJGuavaUnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/assertj/AssertJJava8UnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJJava8UnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/assertj/AssertJJava8UnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJJava8UnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java diff --git a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorRunSteps.java b/testing-modules/testing/src/test/java/com/baeldung/testing/calculator/CalculatorRunSteps.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/calculator/CalculatorRunSteps.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/calculator/CalculatorRunSteps.java diff --git a/testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java b/testing-modules/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java diff --git a/testing/src/test/java/com/baeldung/testing/truth/GoogleTruthUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/truth/GoogleTruthUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/truth/GoogleTruthUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/truth/GoogleTruthUnitTest.java diff --git a/testing/src/test/resources/JunitParamsTestParameters.csv b/testing-modules/testing/src/test/resources/JunitParamsTestParameters.csv similarity index 100% rename from testing/src/test/resources/JunitParamsTestParameters.csv rename to testing-modules/testing/src/test/resources/JunitParamsTestParameters.csv diff --git a/testing/src/test/resources/features/calculator-scenario-outline.feature b/testing-modules/testing/src/test/resources/features/calculator-scenario-outline.feature similarity index 100% rename from testing/src/test/resources/features/calculator-scenario-outline.feature rename to testing-modules/testing/src/test/resources/features/calculator-scenario-outline.feature diff --git a/testing/src/test/resources/features/calculator.feature b/testing-modules/testing/src/test/resources/features/calculator.feature similarity index 100% rename from testing/src/test/resources/features/calculator.feature rename to testing-modules/testing/src/test/resources/features/calculator.feature diff --git a/testing/src/test/resources/features/shopping.feature b/testing-modules/testing/src/test/resources/features/shopping.feature similarity index 100% rename from testing/src/test/resources/features/shopping.feature rename to testing-modules/testing/src/test/resources/features/shopping.feature diff --git a/testng/README.md b/testing-modules/testng/README.md similarity index 100% rename from testng/README.md rename to testing-modules/testng/README.md diff --git a/testng/pom.xml b/testing-modules/testng/pom.xml similarity index 94% rename from testng/pom.xml rename to testing-modules/testng/pom.xml index 0ca775a00c..f7a50954fc 100644 --- a/testng/pom.xml +++ b/testing-modules/testng/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/testng/src/test/java/com/baeldung/DependentLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/DependentLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/DependentLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/DependentLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/GroupIntegrationTest.java b/testing-modules/testng/src/test/java/com/baeldung/GroupIntegrationTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/GroupIntegrationTest.java rename to testing-modules/testng/src/test/java/com/baeldung/GroupIntegrationTest.java diff --git a/testng/src/test/java/com/baeldung/MultiThreadedIntegrationTest.java b/testing-modules/testng/src/test/java/com/baeldung/MultiThreadedIntegrationTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/MultiThreadedIntegrationTest.java rename to testing-modules/testng/src/test/java/com/baeldung/MultiThreadedIntegrationTest.java diff --git a/testng/src/test/java/com/baeldung/ParametrizedLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/ParametrizedLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/ParametrizedLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/ParametrizedLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/PriorityLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/PriorityLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/PriorityLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/PriorityLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/RegistrationLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/RegistrationLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/RegistrationLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/RegistrationLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/SignInLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/SignInLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/SignInLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/SignInLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/SimpleLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/SimpleLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/SimpleLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/SimpleLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/SummationServiceIntegrationTest.java b/testing-modules/testng/src/test/java/com/baeldung/SummationServiceIntegrationTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/SummationServiceIntegrationTest.java rename to testing-modules/testng/src/test/java/com/baeldung/SummationServiceIntegrationTest.java diff --git a/testng/src/test/java/com/baeldung/TimeOutIntegrationTest.java b/testing-modules/testng/src/test/java/com/baeldung/TimeOutIntegrationTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/TimeOutIntegrationTest.java rename to testing-modules/testng/src/test/java/com/baeldung/TimeOutIntegrationTest.java diff --git a/testng/src/test/java/com/baeldung/reports/CustomisedListener.java b/testing-modules/testng/src/test/java/com/baeldung/reports/CustomisedListener.java similarity index 100% rename from testng/src/test/java/com/baeldung/reports/CustomisedListener.java rename to testing-modules/testng/src/test/java/com/baeldung/reports/CustomisedListener.java diff --git a/testng/src/test/java/com/baeldung/reports/CustomisedReports.java b/testing-modules/testng/src/test/java/com/baeldung/reports/CustomisedReports.java similarity index 100% rename from testng/src/test/java/com/baeldung/reports/CustomisedReports.java rename to testing-modules/testng/src/test/java/com/baeldung/reports/CustomisedReports.java diff --git a/testng/src/test/resources/logback.xml b/testing-modules/testng/src/test/resources/logback.xml similarity index 100% rename from testng/src/test/resources/logback.xml rename to testing-modules/testng/src/test/resources/logback.xml diff --git a/testng/src/test/resources/parametrized_testng.xml b/testing-modules/testng/src/test/resources/parametrized_testng.xml similarity index 100% rename from testng/src/test/resources/parametrized_testng.xml rename to testing-modules/testng/src/test/resources/parametrized_testng.xml diff --git a/testng/src/test/resources/reportTemplate.html b/testing-modules/testng/src/test/resources/reportTemplate.html similarity index 100% rename from testng/src/test/resources/reportTemplate.html rename to testing-modules/testng/src/test/resources/reportTemplate.html diff --git a/testng/src/test/resources/test_group.xml b/testing-modules/testng/src/test/resources/test_group.xml similarity index 100% rename from testng/src/test/resources/test_group.xml rename to testing-modules/testng/src/test/resources/test_group.xml diff --git a/testng/src/test/resources/test_setup.xml b/testing-modules/testng/src/test/resources/test_setup.xml similarity index 100% rename from testng/src/test/resources/test_setup.xml rename to testing-modules/testng/src/test/resources/test_setup.xml diff --git a/testng/src/test/resources/test_suite.xml b/testing-modules/testng/src/test/resources/test_suite.xml similarity index 100% rename from testng/src/test/resources/test_suite.xml rename to testing-modules/testng/src/test/resources/test_suite.xml diff --git a/xmlunit2/README.md b/xmlunit-2/README.md similarity index 100% rename from xmlunit2/README.md rename to xmlunit-2/README.md diff --git a/xmlunit2/pom.xml b/xmlunit-2/pom.xml similarity index 96% rename from xmlunit2/pom.xml rename to xmlunit-2/pom.xml index dd9fe9ac27..591cb70ec8 100644 --- a/xmlunit2/pom.xml +++ b/xmlunit-2/pom.xml @@ -2,7 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung - xmlunit2 + xmlunit-2 1.0 XMLUnit-2 diff --git a/xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java b/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java similarity index 100% rename from xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java rename to xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java diff --git a/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java similarity index 100% rename from xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java rename to xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java diff --git a/xmlunit2/src/test/resources/control.xml b/xmlunit-2/src/test/resources/control.xml similarity index 100% rename from xmlunit2/src/test/resources/control.xml rename to xmlunit-2/src/test/resources/control.xml diff --git a/xmlunit2/src/test/resources/students.xml b/xmlunit-2/src/test/resources/students.xml similarity index 100% rename from xmlunit2/src/test/resources/students.xml rename to xmlunit-2/src/test/resources/students.xml diff --git a/xmlunit2/src/test/resources/students.xsd b/xmlunit-2/src/test/resources/students.xsd similarity index 100% rename from xmlunit2/src/test/resources/students.xsd rename to xmlunit-2/src/test/resources/students.xsd diff --git a/xmlunit2/src/test/resources/students_with_error.xml b/xmlunit-2/src/test/resources/students_with_error.xml similarity index 100% rename from xmlunit2/src/test/resources/students_with_error.xml rename to xmlunit-2/src/test/resources/students_with_error.xml diff --git a/xmlunit2/src/test/resources/teachers.xml b/xmlunit-2/src/test/resources/teachers.xml similarity index 100% rename from xmlunit2/src/test/resources/teachers.xml rename to xmlunit-2/src/test/resources/teachers.xml diff --git a/xmlunit2/src/test/resources/test.xml b/xmlunit-2/src/test/resources/test.xml similarity index 100% rename from xmlunit2/src/test/resources/test.xml rename to xmlunit-2/src/test/resources/test.xml
" + user.getUsername() + "" + user.getEmail() + "