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/cas-secured-app/README.md b/cas-secured-app/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/cas-secured-app/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/cas-server/etc/cas/thekeystore b/cas-server/etc/cas/thekeystore deleted file mode 100644 index 15f9af2dae..0000000000 Binary files a/cas-server/etc/cas/thekeystore and /dev/null differ diff --git a/cas-server/etc/cas/thekeystore.crt b/cas-server/etc/cas/thekeystore.crt deleted file mode 100644 index 5c7543f0c6..0000000000 Binary files a/cas-server/etc/cas/thekeystore.crt and /dev/null differ diff --git a/cas/cas-secured-app/.gitignore b/cas/cas-secured-app/.gitignore new file mode 100644 index 0000000000..cd4878159f --- /dev/null +++ b/cas/cas-secured-app/.gitignore @@ -0,0 +1,27 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ +/.mvn/ +/mvnw +/mvnw.cmd \ No newline at end of file diff --git a/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml similarity index 63% rename from cas-secured-app/pom.xml rename to cas/cas-secured-app/pom.xml index 0548e0c315..f66d54ae67 100644 --- a/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -106,75 +106,5 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/AutoconfigurationTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java similarity index 94% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java index fc05e3b38f..25cbb9bc9b 100644 --- a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java @@ -40,14 +40,14 @@ public class CasSecuredAppApplication { @Primary public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) { CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); - entryPoint.setLoginUrl("https://localhost:8443/cas/login"); + entryPoint.setLoginUrl("https://localhost:6443/cas/login"); entryPoint.setServiceProperties(sP); return entryPoint; } @Bean public TicketValidator ticketValidator() { - return new Cas30ServiceTicketValidator("https://localhost:8443/cas"); + return new Cas30ServiceTicketValidator("https://localhost:6443/cas"); } @Bean @@ -71,7 +71,7 @@ public class CasSecuredAppApplication { @Bean public LogoutFilter logoutFilter() { LogoutFilter logoutFilter = new LogoutFilter( - "https://localhost:8443/cas/logout", securityContextLogoutHandler()); + "https://localhost:6443/cas/logout", securityContextLogoutHandler()); logoutFilter.setFilterProcessesUrl("/logout/cas"); return logoutFilter; } @@ -79,7 +79,7 @@ public class CasSecuredAppApplication { @Bean public SingleSignOutFilter singleSignOutFilter() { SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); - singleSignOutFilter.setCasServerUrlPrefix("https://localhost:8443/cas"); + singleSignOutFilter.setCasServerUrlPrefix("https://localhost:6443/cas"); singleSignOutFilter.setIgnoreInitConfiguration(true); return singleSignOutFilter; } diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java similarity index 100% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java similarity index 100% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java similarity index 100% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java similarity index 100% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java diff --git a/cas-secured-app/src/main/resources/application.properties b/cas/cas-secured-app/src/main/resources/application.properties similarity index 100% rename from cas-secured-app/src/main/resources/application.properties rename to cas/cas-secured-app/src/main/resources/application.properties diff --git a/cas-secured-app/src/main/resources/templates/auth/logout.ftl b/cas/cas-secured-app/src/main/resources/templates/auth/logout.ftl similarity index 100% rename from cas-secured-app/src/main/resources/templates/auth/logout.ftl rename to cas/cas-secured-app/src/main/resources/templates/auth/logout.ftl diff --git a/cas-secured-app/src/main/resources/templates/index.ftl b/cas/cas-secured-app/src/main/resources/templates/index.ftl similarity index 100% rename from cas-secured-app/src/main/resources/templates/index.ftl rename to cas/cas-secured-app/src/main/resources/templates/index.ftl diff --git a/cas-secured-app/src/main/resources/templates/secure/index.ftl b/cas/cas-secured-app/src/main/resources/templates/secure/index.ftl similarity index 100% rename from cas-secured-app/src/main/resources/templates/secure/index.ftl rename to cas/cas-secured-app/src/main/resources/templates/secure/index.ftl diff --git a/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java similarity index 84% rename from cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java rename to cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java index 2f2644e2ea..09dbaf0c61 100644 --- a/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java +++ b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class CasSecuredAppApplicationIntegrationTest { +public class CasSecuredAppApplicationTests { @Test public void contextLoads() { diff --git a/cas-server/.gitignore b/cas/cas-server/.gitignore similarity index 100% rename from cas-server/.gitignore rename to cas/cas-server/.gitignore diff --git a/cas-server/LICENSE.txt b/cas/cas-server/LICENSE.txt similarity index 100% rename from cas-server/LICENSE.txt rename to cas/cas-server/LICENSE.txt diff --git a/cas-server/README.md b/cas/cas-server/README.md similarity index 100% rename from cas-server/README.md rename to cas/cas-server/README.md diff --git a/cas-server/build.cmd b/cas/cas-server/build.cmd similarity index 100% rename from cas-server/build.cmd rename to cas/cas-server/build.cmd diff --git a/cas-server/build.sh b/cas/cas-server/build.sh similarity index 100% rename from cas-server/build.sh rename to cas/cas-server/build.sh diff --git a/cas-server/etc/cas/config/application.yml b/cas/cas-server/etc/cas/config/application.yml similarity index 100% rename from cas-server/etc/cas/config/application.yml rename to cas/cas-server/etc/cas/config/application.yml diff --git a/cas-server/etc/cas/config/cas.properties b/cas/cas-server/etc/cas/config/cas.properties similarity index 100% rename from cas-server/etc/cas/config/cas.properties rename to cas/cas-server/etc/cas/config/cas.properties diff --git a/cas-server/etc/cas/config/log4j2.xml b/cas/cas-server/etc/cas/config/log4j2.xml similarity index 100% rename from cas-server/etc/cas/config/log4j2.xml rename to cas/cas-server/etc/cas/config/log4j2.xml diff --git a/cas-server/maven/maven-wrapper.properties b/cas/cas-server/maven/maven-wrapper.properties similarity index 100% rename from cas-server/maven/maven-wrapper.properties rename to cas/cas-server/maven/maven-wrapper.properties diff --git a/cas-server/mvnw b/cas/cas-server/mvnw similarity index 100% rename from cas-server/mvnw rename to cas/cas-server/mvnw diff --git a/cas-server/mvnw.bat b/cas/cas-server/mvnw.bat similarity index 100% rename from cas-server/mvnw.bat rename to cas/cas-server/mvnw.bat diff --git a/cas-server/pom.xml b/cas/cas-server/pom.xml similarity index 100% rename from cas-server/pom.xml rename to cas/cas-server/pom.xml diff --git a/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties similarity index 91% rename from cas-server/src/main/resources/application.properties rename to cas/cas-server/src/main/resources/application.properties index 2d5e9a7277..afacd4cbc1 100644 --- a/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -2,9 +2,9 @@ # CAS Server Context Configuration # server.context-path=/cas -server.port=8443 +server.port=6443 -server.ssl.key-store=file:/etc/cas/thekeystore +server.ssl.key-store=classpath:/etc/cas/thekeystore server.ssl.key-store-password=changeit server.ssl.key-password=changeit # server.ssl.ciphers= @@ -40,6 +40,12 @@ spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true +## +#CAS CONFIG LOCATION +# +cas.standalone.config=classpath:/etc/cas/config + + ## # CAS Cloud Bus Configuration # @@ -82,6 +88,7 @@ spring.thymeleaf.mode=HTML # CAS Log4j Configuration # # logging.config=file:/etc/cas/log4j2.xml + server.context-parameters.isLog4jAutoInitializationDisabled=true ## @@ -104,9 +111,10 @@ cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].user=root cas.authn.jdbc.query[0].password= cas.authn.jdbc.query[0].ddlAuto=none -cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver +#cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver +cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver cas.authn.jdbc.query[0].fieldPassword=password -cas.authn.jdbc.query[0].passwordEncoder.type=BCRYPT +cas.authn.jdbc.query[0].passwordEncoder.type=NONE ## diff --git a/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties similarity index 92% rename from cas-server/src/main/resources/cas.properties rename to cas/cas-server/src/main/resources/cas.properties index be2babcd14..f80f22fc11 100644 --- a/cas-server/src/main/resources/cas.properties +++ b/cas/cas-server/src/main/resources/cas.properties @@ -1,16 +1,15 @@ -cas.server.name: https://localhost:8443 -cas.server.prefix: https://localhost:8443/cas +cas.server.name: https://localhost:6443 +cas.server.prefix: https://localhost:643/cas cas.adminPagesSecurity.ip=127\.0\.0\.1 -logging.config: file:/etc/cas/config/log4j2.xml - cas.serviceRegistry.initFromJson=true cas.serviceRegistry.config.location=classpath:/services cas.authn.accept.users= cas.authn.accept.name= + #CAS Database Authentication Property # cas.authn.jdbc.query[0].healthQuery= diff --git a/cas/cas-server/src/main/resources/etc/cas/config/application.yml b/cas/cas-server/src/main/resources/etc/cas/config/application.yml new file mode 100644 index 0000000000..be1f7c3edd --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/config/application.yml @@ -0,0 +1,2 @@ +info: + description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties new file mode 100644 index 0000000000..47a1477308 --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties @@ -0,0 +1,7 @@ +cas.server.name: https://cas.example.org:8443 +cas.server.prefix: https://cas.example.org:8443/cas + +cas.adminPagesSecurity.ip=127\.0\.0\.1 + +logging.config: file:/etc/cas/config/log4j2.xml +# cas.serviceRegistry.config.location: classpath:/services diff --git a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml new file mode 100644 index 0000000000..53b30b4228 --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml @@ -0,0 +1,117 @@ + + + + + + . + + warn + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore b/cas/cas-server/src/main/resources/etc/cas/thekeystore new file mode 100644 index 0000000000..86170dff16 Binary files /dev/null and b/cas/cas-server/src/main/resources/etc/cas/thekeystore differ diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt new file mode 100644 index 0000000000..5bd9d5baba Binary files /dev/null and b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt differ diff --git a/cas-server/src/main/resources/services/casSecuredApp.json b/cas/cas-server/src/main/resources/services/casSecuredApp.json similarity index 100% rename from cas-server/src/main/resources/services/casSecuredApp.json rename to cas/cas-server/src/main/resources/services/casSecuredApp.json 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/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-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java index 6ddcb954a1..4d87978070 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java @@ -3,8 +3,17 @@ package com.baeldung.concurrent.daemon; public class NewThread extends Thread { public void run() { - while (true) - for (int i = 0; i < 10; i++) - System.out.println("New Thread is running..."); + long startTime = System.currentTimeMillis(); + while (true) { + for (int i = 0; i < 10; i++) { + System.out.println("New Thread is running..." + i); + } + + // prevent the Thread to run forever. It will finish it's execution after 2 seconds + if (System.currentTimeMillis() - startTime > 2000) { + Thread.currentThread().interrupt(); + break; + } + } } } diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/DelayedCallable.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/DelayedCallable.java new file mode 100644 index 0000000000..16d9aa4c9f --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/DelayedCallable.java @@ -0,0 +1,39 @@ +package com.baeldung.concurrent.executorservice; + +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; + +public class DelayedCallable implements Callable { + + private String name; + private long period; + private CountDownLatch latch; + + public DelayedCallable(String name, long period, CountDownLatch latch) { + this(name, period); + this.latch = latch; + } + + public DelayedCallable(String name, long period) { + this.name = name; + this.period = period; + } + + public String call() { + + try { + Thread.sleep(period); + + if (latch != null) { + latch.countDown(); + } + + } catch (InterruptedException ex) { + // handle exception + ex.printStackTrace(); + Thread.currentThread().interrupt(); + } + + return name; + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java index 2c4eeb63d6..f0150578ae 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java @@ -3,11 +3,16 @@ package com.baeldung.concurrent.daemon; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +<<<<<<< HEAD +======= +import org.junit.Ignore; +>>>>>>> d54917c7e9f0f74c40982571af8ac9f61782b7cb import org.junit.Test; public class DaemonThreadTest { @Test + @Ignore public void whenCallIsDaemon_thenCorrect() { NewThread daemonThread = new NewThread(); NewThread userThread = new NewThread(); @@ -20,6 +25,7 @@ public class DaemonThreadTest { } @Test(expected = IllegalThreadStateException.class) + @Ignore public void givenUserThread_whenSetDaemonWhileRunning_thenIllegalThreadStateException() { NewThread daemonThread = new NewThread(); daemonThread.start(); diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishTest.java new file mode 100644 index 0000000000..17b71aa35b --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishTest.java @@ -0,0 +1,215 @@ +package com.baeldung.concurrent.executorservice; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.*; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.fail; + +public class WaitingForThreadsToFinishTest { + + private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishTest.class); + private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10); + + public void awaitTerminationAfterShutdown(ExecutorService threadPool) { + threadPool.shutdown(); + try { + if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) { + threadPool.shutdownNow(); + } + } catch (InterruptedException ex) { + threadPool.shutdownNow(); + Thread.currentThread().interrupt(); + } + } + + @Test + public void givenMultipleThreads_whenUsingCountDownLatch_thenMainShoudWaitForAllToFinish() { + + ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10); + + try { + long startTime = System.currentTimeMillis(); + + // create a CountDownLatch that waits for the 2 threads to finish + CountDownLatch latch = new CountDownLatch(2); + + for (int i = 0; i < 2; i++) { + WORKER_THREAD_POOL.submit(new Runnable() { + @Override + public void run() { + try { + Thread.sleep(1000); + latch.countDown(); + } catch (InterruptedException e) { + e.printStackTrace(); + Thread.currentThread().interrupt(); + } + } + }); + } + + // wait for the latch to be decremented by the two threads + latch.await(); + + long processingTime = System.currentTimeMillis() - startTime; + assertTrue(processingTime >= 1000); + + } catch (InterruptedException e) { + e.printStackTrace(); + } + + awaitTerminationAfterShutdown(WORKER_THREAD_POOL); + } + + @Test + public void givenMultipleThreads_whenInvokeAll_thenMainThreadShouldWaitForAllToFinish() { + + ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10); + + List> callables = Arrays.asList( + new DelayedCallable("fast thread", 100), + new DelayedCallable("slow thread", 3000)); + + try { + long startProcessingTime = System.currentTimeMillis(); + List> futures = WORKER_THREAD_POOL.invokeAll(callables); + + awaitTerminationAfterShutdown(WORKER_THREAD_POOL); + + try { + WORKER_THREAD_POOL.submit(new Callable() { + @Override + public String call() throws Exception { + fail("This thread should have been rejected !"); + Thread.sleep(1000000); + return null; + } + }); + } catch (RejectedExecutionException ex) { + // + } + + long totalProcessingTime = System.currentTimeMillis() - startProcessingTime; + assertTrue(totalProcessingTime >= 3000); + + String firstThreadResponse = futures.get(0) + .get(); + assertTrue("First response should be from the fast thread", "fast thread".equals(firstThreadResponse)); + + String secondThreadResponse = futures.get(1) + .get(); + assertTrue("Last response should be from the slow thread", "slow thread".equals(secondThreadResponse)); + + } catch (ExecutionException | InterruptedException ex) { + ex.printStackTrace(); + } + } + + @Test + public void givenMultipleThreads_whenUsingCompletionService_thenMainThreadShouldWaitForAllToFinish() { + + CompletionService service = new ExecutorCompletionService<>(WORKER_THREAD_POOL); + + List> callables = Arrays.asList( + new DelayedCallable("fast thread", 100), + new DelayedCallable("slow thread", 3000)); + + for (Callable callable : callables) { + service.submit(callable); + } + + try { + + long startProcessingTime = System.currentTimeMillis(); + + Future future = service.take(); + String firstThreadResponse = future.get(); + long totalProcessingTime = System.currentTimeMillis() - startProcessingTime; + + assertTrue("First response should be from the fast thread", "fast thread".equals(firstThreadResponse)); + assertTrue(totalProcessingTime >= 100 && totalProcessingTime < 1000); + LOG.debug("Thread finished after: " + totalProcessingTime + " milliseconds"); + + future = service.take(); + String secondThreadResponse = future.get(); + totalProcessingTime = System.currentTimeMillis() - startProcessingTime; + + assertTrue("Last response should be from the slow thread", "slow thread".equals(secondThreadResponse)); + assertTrue(totalProcessingTime >= 3000 && totalProcessingTime < 4000); + LOG.debug("Thread finished after: " + totalProcessingTime + " milliseconds"); + + } catch (ExecutionException | InterruptedException ex) { + ex.printStackTrace(); + } finally { + awaitTerminationAfterShutdown(WORKER_THREAD_POOL); + } + } + + @Test + public void givenMultipleThreads_whenUsingCompletableFutures_thenMainThreadShouldWaitForAllToFinish() { + + CompletableFuture future1 = CompletableFuture.supplyAsync(() -> { + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return "Hello"; + }); + + CompletableFuture future2 = CompletableFuture.supplyAsync(() -> { + + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return "Beautiful"; + }); + + CompletableFuture future3 = CompletableFuture.supplyAsync(() -> { + + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return "World"; + }); + + long startProcessingTime = System.currentTimeMillis(); + CompletableFuture combinedFuture = CompletableFuture.allOf(future1, future2, future3); + combinedFuture.join(); + + long totalProcessingTime = System.currentTimeMillis() - startProcessingTime; + assertTrue(totalProcessingTime >= 5000 && totalProcessingTime < 6000); + + LOG.debug("Responses from all threads are available after " + totalProcessingTime + " milliseconds"); + + try { + String thread1Response = future1.get(); + assertTrue(thread1Response.equals("Hello")); + + String thread2Response = future2.get(); + assertTrue(thread2Response.equals("Beautiful")); + + String thread3Response = future3.get(); + assertTrue(thread3Response.equals("World")); + + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + + awaitTerminationAfterShutdown(WORKER_THREAD_POOL); + } +} 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 61% 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 d0f4460f51..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,39 +1,50 @@ 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.Before; +import org.junit.AfterClass; +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; + + @BeforeClass + public static void setup() { + executorService = Executors.newCachedThreadPool(); + } + @Test public void givenARunnable_whenRunIt_thenResult() throws Exception{ Thread thread = new Thread(new SimpleRunnable( "SimpleRunnable executed using Thread")); thread.start(); thread.join(); - - ExecutorService executorService = - Executors.newCachedThreadPool(); + } + + @Test + public void givenARunnable_whenSubmitToES_thenResult() throws Exception{ executorService.submit(new SimpleRunnable( "SimpleRunnable executed using ExecutorService")).get(); + } + + @Test + public void givenARunnableLambda_whenSubmitToES_thenResult() + throws Exception{ executorService.submit(()-> log.info("Lambda runnable executed!!!")).get(); - executorService.shutdown(); } @Test @@ -42,26 +53,37 @@ public class RunnableVsThreadTest { "SimpleThread executed using Thread"); thread.start(); thread.join(); + } + + @Test + public void givenAThread_whenSubmitToES_thenResult() throws Exception{ - ExecutorService executorService = - Executors.newCachedThreadPool(); executorService.submit(new SimpleThread( "SimpleThread executed using ExecutorService")).get(); } @Test - public void givenACallable_whenRunIt_thenResult() throws Exception { - ExecutorService executorService = - Executors.newCachedThreadPool(); + public void givenACallable_whenSubmitToES_thenResult() throws Exception { - Future future = executorService.submit(new SimpleCallable()); + Future future = executorService.submit( + new SimpleCallable()); log.info("Result from callable: {}", future.get()); + } + + @Test + public void givenACallableAsLambda_whenSubmitToES_thenResult() + throws Exception { + + Future future = executorService.submit(() -> RandomUtils.nextInt(0, 100)); - future = executorService.submit(() -> { - return RandomUtils.nextInt(0, 100); - }); log.info("Result from callable: {}", future.get()); - + } + + @AfterClass + public static void tearDown() { + if ( executorService != null && !executorService.isShutdown()) { + executorService.shutdown(); + } } } @@ -72,7 +94,7 @@ class SimpleThread extends Thread{ private String message; - public SimpleThread(String message) { + SimpleThread(String message) { this.message = message; } @@ -89,7 +111,7 @@ class SimpleRunnable implements Runnable { private String message; - public SimpleRunnable(String message) { + SimpleRunnable(String message) { this.message = message; } @@ -107,4 +129,5 @@ class SimpleCallable implements Callable { return RandomUtils.nextInt(0, 100); } -} \ No newline at end of file +} + diff --git a/core-java/README.md b/core-java/README.md index b4b8d9062e..dcf77ff536 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -114,4 +114,5 @@ - [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) diff --git a/core-java/pom.xml b/core-java/pom.xml index bb3958f36c..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 + @@ -249,7 +256,7 @@ **/*LongRunningUnitTest.java **/*ManualTest.java - true + 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/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java index 2ed9a27c4c..7c1e291646 100644 --- a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java @@ -13,6 +13,8 @@ import java.util.Set; public class EchoServer { + private static final String POISON_PILL = "POISON_PILL"; + public static void main(String[] args) throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); @@ -30,23 +32,36 @@ public class EchoServer { SelectionKey key = iter.next(); if (key.isAcceptable()) { - SocketChannel client = serverSocket.accept(); - client.configureBlocking(false); - client.register(selector, SelectionKey.OP_READ); + register(selector, serverSocket); } if (key.isReadable()) { - SocketChannel client = (SocketChannel) key.channel(); - client.read(buffer); - buffer.flip(); - client.write(buffer); - buffer.clear(); + answerWithEcho(buffer, key); } iter.remove(); } } } + private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException { + SocketChannel client = (SocketChannel) key.channel(); + client.read(buffer); + if (new String(buffer.array()).trim().equals(POISON_PILL)) { + client.close(); + System.out.println("Not accepting client messages anymore"); + } + + buffer.flip(); + client.write(buffer); + buffer.clear(); + } + + private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException { + SocketChannel client = serverSocket.accept(); + client.configureBlocking(false); + client.register(selector, SelectionKey.OP_READ); + } + public static Process start() throws IOException, InterruptedException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; 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/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/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/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java new file mode 100644 index 0000000000..6f15ee510b --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java @@ -0,0 +1,30 @@ +package com.baeldung.drools.backward_chaining; + +import org.kie.api.runtime.KieSession; + +import com.baeldung.drools.config.DroolsBeanFactory; +import com.baeldung.drools.model.Fact; +import com.baeldung.drools.model.Result; + +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); + } + + public Result backwardChaining() { + Result result = new Result(); + 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("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/src/main/java/com/baeldung/drools/model/Fact.java b/drools/src/main/java/com/baeldung/drools/model/Fact.java new file mode 100644 index 0000000000..62b44b9d92 --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/model/Fact.java @@ -0,0 +1,69 @@ +package com.baeldung.drools.model; + +import org.kie.api.definition.type.Position; + +public class Fact { + + @Position(0) + private String element; + + @Position(1) + private String place; + + public Fact(String element, String place) { + this.element = element; + this.place = place; + } + + public String getElement() { + return element; + } + + public void setElement(String element) { + this.element = element; + } + + public String getPlace() { + return place; + } + + public void setPlace(String place) { + this.place = place; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((element == null) ? 0 : element.hashCode()); + result = prime * result + ((place == null) ? 0 : place.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; + Fact other = (Fact) obj; + if (element == null) { + if (other.element != null) + return false; + } else if (!element.equals(other.element)) + return false; + if (place == null) { + if (other.place != null) + return false; + } else if (!place.equals(other.place)) + return false; + return true; + } + + @Override + public String toString() { + return "Fact{" + "element='" + element + '\'' + ", place='" + place + '\'' + '}'; + } +} \ No newline at end of file diff --git a/drools/src/main/java/com/baeldung/drools/model/Result.java b/drools/src/main/java/com/baeldung/drools/model/Result.java new file mode 100644 index 0000000000..b22557832b --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/model/Result.java @@ -0,0 +1,31 @@ +package com.baeldung.drools.model; + +import java.util.ArrayList; +import java.util.List; + +public class Result { + private String value; + private List facts = new ArrayList<>(); + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public List getFacts() { + return facts; + } + + public void setFacts(List facts) { + this.facts = facts; + } + + public void addFact(String fact) { + this.facts.add(fact); + } + + +} diff --git a/drools/src/main/resources/com/baeldung/drools/rules/BackwardChaining.drl b/drools/src/main/resources/com/baeldung/drools/rules/BackwardChaining.drl new file mode 100644 index 0000000000..975be84fb4 --- /dev/null +++ b/drools/src/main/resources/com/baeldung/drools/rules/BackwardChaining.drl @@ -0,0 +1,27 @@ +package com.baeldung.drools.rules + +import com.baeldung.drools.model.Fact; + +global com.baeldung.drools.model.Result result; + +dialect "mvel" + +query belongsTo(String x, String y) + Fact(x, y;) + or + (Fact(z, y;) and belongsTo(x, z;)) +end + +rule "Great Wall of China BELONGS TO Planet Earth" +when + belongsTo("Great Wall of China", "Planet Earth";) +then + result.setValue("Decision one taken: Great Wall of China BELONGS TO Planet Earth"); +end + +rule "print all facts" +when + belongsTo(element, place;) +then + result.addFact(element + " IS ELEMENT OF " + place); +end 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 62feb6b4b9..a27f0efe51 100644 --- a/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java +++ b/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java @@ -1,5 +1,6 @@ import java.io.IOException; +import java.io.PrintWriter; import java.util.List; import javax.ejb.EJB; @@ -15,7 +16,6 @@ import wildfly.beans.UserBeanLocal; * Servlet implementation class TestEJBServlet */ public class TestEJBServlet extends HttpServlet { - private static final long serialVersionUID = 1L; @EJB private UserBeanLocal userBean; @@ -23,8 +23,19 @@ public class TestEJBServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List users = userBean.getUsers(); - response.getWriter() - .append("The number of users is: " + users.size()); + 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(""); + } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { diff --git a/ejb/wildfly/wildfly-jpa/src/main/resources/META-INF/persistence.xml b/ejb/wildfly/wildfly-jpa/src/main/resources/META-INF/persistence.xml index 1a3fc32381..2aa6bc2cd7 100644 --- a/ejb/wildfly/wildfly-jpa/src/main/resources/META-INF/persistence.xml +++ b/ejb/wildfly/wildfly-jpa/src/main/resources/META-INF/persistence.xml @@ -3,7 +3,13 @@ xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> - java:/PostgresDS + java:/H2DS model.User + + + + + + diff --git a/ejb/wildfly/wildfly-jpa/src/main/resources/data.sql b/ejb/wildfly/wildfly-jpa/src/main/resources/data.sql new file mode 100644 index 0000000000..03eafa534e --- /dev/null +++ b/ejb/wildfly/wildfly-jpa/src/main/resources/data.sql @@ -0,0 +1 @@ +INSERT INTO users (username, email, postal_number) VALUES ('user1', 'user1@baeldung.com', 1000), ('user2', 'user2@baeldung.com', 2); \ No newline at end of file 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 90% 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 91% 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 91% 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-mvc/README.md b/guest/spring-mvc/README.md new file mode 100644 index 0000000000..9e5cd64a04 --- /dev/null +++ b/guest/spring-mvc/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-mvc/pom.xml b/guest/spring-mvc/pom.xml index 9974a76e8a..1f695a75a7 100644 --- a/guest/spring-mvc/pom.xml +++ b/guest/spring-mvc/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.forketyfork.guest + com.stackify.guest spring-mvc 0.0.1-SNAPSHOT jar diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/Spring5Application.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/Spring5Application.java similarity index 76% rename from guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/Spring5Application.java rename to guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/Spring5Application.java index d9af7c8ac9..42d40fa02d 100644 --- a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/Spring5Application.java +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/Spring5Application.java @@ -1,11 +1,11 @@ -package com.forketyfork.guest.springmvc; +package com.stackify.guest.springmvc; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.boot.SpringApplication; @SpringBootApplication -@ComponentScan(basePackages = {"com.forketyfork.guest.springmvc"}) +@ComponentScan(basePackages = {"com.stackify.guest.springmvc"}) public class Spring5Application { public static void main(String[] args) { diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/model/LoginData.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/model/LoginData.java similarity index 89% rename from guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/model/LoginData.java rename to guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/model/LoginData.java index a9140da4f9..b1a0e86ef4 100644 --- a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/model/LoginData.java +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/model/LoginData.java @@ -1,4 +1,4 @@ -package com.forketyfork.guest.springmvc.model; +package com.stackify.guest.springmvc.model; public class LoginData { diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/InternalsController.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/InternalsController.java similarity index 92% rename from guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/InternalsController.java rename to guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/InternalsController.java index 04adb9211e..0bd8570eed 100644 --- a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/InternalsController.java +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/InternalsController.java @@ -1,6 +1,5 @@ -package com.forketyfork.guest.springmvc.web; +package com.stackify.guest.springmvc.web; -import com.forketyfork.guest.springmvc.model.LoginData; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @@ -8,6 +7,8 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; +import com.stackify.guest.springmvc.model.LoginData; + import java.util.Collections; @Controller diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/MyInputResource.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyInputResource.java similarity index 85% rename from guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/MyInputResource.java rename to guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyInputResource.java index 4c30cfb842..cf5815840a 100644 --- a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/MyInputResource.java +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyInputResource.java @@ -1,4 +1,4 @@ -package com.forketyfork.guest.springmvc.web; +package com.stackify.guest.springmvc.web; public class MyInputResource { diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/MyOutputResource.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyOutputResource.java similarity index 85% rename from guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/MyOutputResource.java rename to guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyOutputResource.java index bcb76056a4..2d0e174243 100644 --- a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/MyOutputResource.java +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyOutputResource.java @@ -1,4 +1,4 @@ -package com.forketyfork.guest.springmvc.web; +package com.stackify.guest.springmvc.web; public class MyOutputResource { diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/RestfulWebServiceController.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/RestfulWebServiceController.java similarity index 87% rename from guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/RestfulWebServiceController.java rename to guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/RestfulWebServiceController.java index 820c80db7a..edb35e6ecf 100644 --- a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/RestfulWebServiceController.java +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/RestfulWebServiceController.java @@ -1,4 +1,4 @@ -package com.forketyfork.guest.springmvc.web; +package com.stackify.guest.springmvc.web; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; 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 ff12555376..4690ebbe76 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -1 +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/pom.xml b/hibernate5/pom.xml index c501b7f11d..8543d1dae3 100644 --- a/hibernate5/pom.xml +++ b/hibernate5/pom.xml @@ -22,13 +22,19 @@ org.hibernate hibernate-core - 5.2.9.Final + 5.2.12.Final junit junit 4.12 + + org.assertj + assertj-core + 3.8.0 + test + com.h2database h2 diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java index 5a10b2ba56..30f3c3cf53 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java @@ -68,7 +68,7 @@ public class HibernateMultiTenantUtil { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() - .getResource("hibernate.properties"); + .getResource("hibernate-multitenancy.properties"); FileInputStream inputStream = new FileInputStream(propertiesURL.getFile()); properties.load(inputStream); System.out.println("LOADED PROPERTIES FROM hibernate.properties"); diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index c1f7301d46..c44a80cbd9 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,24 +1,77 @@ 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.cfg.Configuration; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; public class HibernateUtil { + private static SessionFactory sessionFactory; - private static final SessionFactory sessionFactory; - - static { - try { - Configuration configuration = new Configuration().configure(); - sessionFactory = configuration.buildSessionFactory(); - - } catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - throw new ExceptionInInitializerError(ex); + public static SessionFactory getSessionFactory() throws IOException { + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = makeSessionFactory(serviceRegistry); } - } - - public static SessionFactory getSessionFactory() { return sessionFactory; } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Employee.class); + metadataSources.addAnnotatedClass(Phone.class); + metadataSources.addAnnotatedClass(EntityDescription.class); + metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(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() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource("hibernate.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } + } \ No newline at end of file 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/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java new file mode 100644 index 0000000000..e9732b2b67 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java @@ -0,0 +1,87 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.*; + +import javax.persistence.Entity; +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Where(clause = "deleted = false") +@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int")) +@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit") +public class Employee implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private long grossIncome; + + private int taxInPercents; + + private boolean deleted; + + public long getTaxJavaWay() { + return grossIncome * taxInPercents / 100; + } + + @Formula("grossIncome * taxInPercents / 100") + private long tax; + + @OneToMany + @JoinColumn(name = "employee_id") + @Where(clause = "deleted = false") + private Set phones = new HashSet<>(0); + + public Employee() { + } + + public Employee(long grossIncome, int taxInPercents) { + this.grossIncome = grossIncome; + this.taxInPercents = taxInPercents; + } + + public Integer getId() { + return id; + } + + public long getGrossIncome() { + return grossIncome; + } + + public int getTaxInPercents() { + return taxInPercents; + } + + public long getTax() { + return tax; + } + + public void setId(Integer id) { + this.id = id; + } + + public void setGrossIncome(long grossIncome) { + this.grossIncome = grossIncome; + } + + public void setTaxInPercents(int taxInPercents) { + this.taxInPercents = taxInPercents; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public Set getPhones() { + return phones; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java new file mode 100644 index 0000000000..131bb73a80 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java @@ -0,0 +1,55 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.Any; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class EntityDescription implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private String description; + + @Any( + metaDef = "EntityDescriptionMetaDef", + metaColumn = @Column(name = "entity_type") + ) + @JoinColumn(name = "entity_id") + private Serializable entity; + + public EntityDescription() { + } + + public EntityDescription(String description, Serializable entity) { + this.description = description; + this.entity = entity; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Serializable getEntity() { + return entity; + } + + public void setEntity(Serializable entity) { + this.entity = entity; + } +} diff --git a/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/Phone.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/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/TemporalValues.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java new file mode 100644 index 0000000000..f3fe095cae --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java @@ -0,0 +1,195 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.*; +import java.io.Serializable; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.*; +import java.util.Calendar; + +@Entity +public class TemporalValues implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @Basic + private java.sql.Date sqlDate; + + @Basic + private java.sql.Time sqlTime; + + @Basic + private java.sql.Timestamp sqlTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Date utilDate; + + @Basic + @Temporal(TemporalType.TIME) + private java.util.Date utilTime; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Date utilTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Calendar calendarDate; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Calendar calendarTimestamp; + + @Basic + private java.time.LocalDate localDate; + + @Basic + private java.time.LocalTime localTime; + + @Basic + private java.time.OffsetTime offsetTime; + + @Basic + private java.time.Instant instant; + + @Basic + private java.time.LocalDateTime localDateTime; + + @Basic + private java.time.OffsetDateTime offsetDateTime; + + @Basic + private java.time.ZonedDateTime zonedDateTime; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(Date sqlDate) { + this.sqlDate = sqlDate; + } + + public Time getSqlTime() { + return sqlTime; + } + + public void setSqlTime(Time sqlTime) { + this.sqlTime = sqlTime; + } + + public Timestamp getSqlTimestamp() { + return sqlTimestamp; + } + + public void setSqlTimestamp(Timestamp sqlTimestamp) { + this.sqlTimestamp = sqlTimestamp; + } + + public java.util.Date getUtilDate() { + return utilDate; + } + + public void setUtilDate(java.util.Date utilDate) { + this.utilDate = utilDate; + } + + public java.util.Date getUtilTime() { + return utilTime; + } + + public void setUtilTime(java.util.Date utilTime) { + this.utilTime = utilTime; + } + + public java.util.Date getUtilTimestamp() { + return utilTimestamp; + } + + public void setUtilTimestamp(java.util.Date utilTimestamp) { + this.utilTimestamp = utilTimestamp; + } + + public Calendar getCalendarDate() { + return calendarDate; + } + + public void setCalendarDate(Calendar calendarDate) { + this.calendarDate = calendarDate; + } + + public Calendar getCalendarTimestamp() { + return calendarTimestamp; + } + + public void setCalendarTimestamp(Calendar calendarTimestamp) { + this.calendarTimestamp = calendarTimestamp; + } + + public LocalDate getLocalDate() { + return localDate; + } + + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } + + public LocalTime getLocalTime() { + return localTime; + } + + public void setLocalTime(LocalTime localTime) { + this.localTime = localTime; + } + + public OffsetTime getOffsetTime() { + return offsetTime; + } + + public void setOffsetTime(OffsetTime offsetTime) { + this.offsetTime = offsetTime; + } + + public Instant getInstant() { + return instant; + } + + public void setInstant(Instant instant) { + this.instant = instant; + } + + public LocalDateTime getLocalDateTime() { + return localDateTime; + } + + public void setLocalDateTime(LocalDateTime localDateTime) { + this.localDateTime = localDateTime; + } + + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } + + public void setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } + + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + + public void setZonedDateTime(ZonedDateTime zonedDateTime) { + this.zonedDateTime = zonedDateTime; + } +} diff --git a/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/main/java/com/baeldung/hibernate/pojo/package-info.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java new file mode 100644 index 0000000000..992cda7c1d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java @@ -0,0 +1,9 @@ +@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int", + metaValues = { + @MetaValue(value = "Employee", targetEntity = Employee.class), + @MetaValue(value = "Phone", targetEntity = Phone.class) + }) +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.AnyMetaDef; +import org.hibernate.annotations.MetaValue; \ No newline at end of file diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java new file mode 100644 index 0000000000..b207d6630a --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java @@ -0,0 +1,164 @@ +package com.baeldung.hibernate; + +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DynamicMappingIntegrationTest { + + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + + session.createNativeQuery("delete from phone").executeUpdate(); + session.createNativeQuery("delete from employee").executeUpdate(); + + transaction.commit(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenEntity_whenFieldMappedWithFormula_thenFieldIsCalculated() { + Employee employee = new Employee(10_000L, 25); + assertThat(employee.getTaxJavaWay()).isEqualTo(2_500L); + + session.save(employee); + session.flush(); + session.clear(); + + employee = session.get(Employee.class, employee.getId()); + assertThat(employee.getTax()).isEqualTo(2_500L); + } + + @Test + public void givenEntityMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() { + Employee employee = new Employee(); + + session.save(employee); + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee).isNotNull(); + + employee.setDeleted(true); + session.flush(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee).isNotNull(); + + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee).isNull(); + + } + + @Test + public void givenCollectionMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() { + Employee employee = new Employee(); + Phone phone1 = new Phone("555-45-67"); + Phone phone2 = new Phone("555-89-01"); + employee.getPhones().add(phone1); + employee.getPhones().add(phone2); + + session.save(phone1); + session.save(phone2); + session.save(employee); + session.flush(); + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee.getPhones()).hasSize(2); + + employee.getPhones().iterator().next().setDeleted(true); + session.flush(); + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee.getPhones()).hasSize(1); + + List fullPhoneList = session.createQuery("from Phone").getResultList(); + assertThat(fullPhoneList).hasSize(2); + + } + + @Test + public void givenFilterByIncome_whenIncomeLimitSet_thenFilterIsApplied() throws IOException { + session.save(new Employee(10_000, 25)); + session.save(new Employee(12_000, 25)); + session.save(new Employee(15_000, 25)); + + session.flush(); + session.clear(); + + session.enableFilter("incomeLevelFilter") + .setParameter("incomeLimit", 11_000); + + List employees = session.createQuery("from Employee").getResultList(); + + assertThat(employees).hasSize(2); + + Employee employee = session.get(Employee.class, 1); + assertThat(employee.getGrossIncome()).isEqualTo(10_000); + + session.close(); + + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + + employees = session.createQuery("from Employee").getResultList(); + + assertThat(employees).hasSize(3); + + } + + @Test + public void givenMappingWithAny_whenDescriptionAddedToEntity_thenDescriptionCanReferAnyEntity() { + Employee employee = new Employee(); + Phone phone1 = new Phone("555-45-67"); + Phone phone2 = new Phone("555-89-01"); + employee.getPhones().add(phone1); + employee.getPhones().add(phone2); + + EntityDescription employeeDescription = new EntityDescription("Send to conference next year", employee); + EntityDescription phone1Description = new EntityDescription("Home phone (do not call after 10PM)", phone1); + EntityDescription phone2Description = new EntityDescription("Work phone", phone1); + + session.save(phone1); + session.save(phone2); + session.save(employee); + session.save(employeeDescription); + session.save(phone1Description); + session.save(phone2Description); + session.flush(); + session.clear(); + + List descriptions = session.createQuery("from EntityDescription").getResultList(); + + assertThat(Employee.class.isAssignableFrom(descriptions.get(0).getEntity().getClass())).isTrue(); + assertThat(Phone.class.isAssignableFrom(descriptions.get(1).getEntity().getClass())).isTrue(); + assertThat(Phone.class.isAssignableFrom(descriptions.get(2).getEntity().getClass())).isTrue(); + } + +} 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/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesTest.java new file mode 100644 index 0000000000..ec8afc8db2 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesTest.java @@ -0,0 +1,126 @@ +package com.baeldung.hibernate; + +import com.baeldung.hibernate.pojo.TemporalValues; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.time.*; +import java.util.Calendar; +import java.util.TimeZone; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TemporalValuesTest { + + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().withOptions() + .jdbcTimeZone(TimeZone.getTimeZone("UTC")) + .openSession(); + transaction = session.beginTransaction(); + session.createNativeQuery("delete from temporalvalues").executeUpdate(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenEntity_whenMappingSqlTypes_thenTemporalIsSelectedAutomatically() { + TemporalValues temporalValues = new TemporalValues(); + temporalValues.setSqlDate(java.sql.Date.valueOf("2017-11-15")); + temporalValues.setSqlTime(java.sql.Time.valueOf("15:30:14")); + temporalValues.setSqlTimestamp(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getSqlDate()).isEqualTo(java.sql.Date.valueOf("2017-11-15")); + assertThat(temporalValues.getSqlTime()).isEqualTo(java.sql.Time.valueOf("15:30:14")); + assertThat(temporalValues.getSqlTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + } + + @Test + public void givenEntity_whenMappingUtilDateType_thenTemporalIsSpecifiedExplicitly() throws Exception { + TemporalValues temporalValues = new TemporalValues(); + temporalValues.setUtilDate(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + temporalValues.setUtilTime(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); + temporalValues.setUtilTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getUtilDate()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + assertThat(temporalValues.getUtilTime()).isEqualTo(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); + assertThat(temporalValues.getUtilTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + } + + @Test + public void givenEntity_whenMappingCalendarType_thenTemporalIsSpecifiedExplicitly() throws Exception { + TemporalValues temporalValues = new TemporalValues(); + + Calendar calendarDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendarDate.set(Calendar.YEAR, 2017); + calendarDate.set(Calendar.MONTH, 10); + calendarDate.set(Calendar.DAY_OF_MONTH, 15); + temporalValues.setCalendarDate(calendarDate); + + Calendar calendarTimestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendarTimestamp.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); + temporalValues.setCalendarTimestamp(calendarTimestamp); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getCalendarDate().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + assertThat(temporalValues.getCalendarTimestamp().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); + + } + + @Test + public void givenEntity_whenMappingJavaTimeTypes_thenTemporalIsSelectedAutomatically() { + TemporalValues temporalValues = new TemporalValues(); + + temporalValues.setLocalDate(LocalDate.parse("2017-11-15")); + temporalValues.setLocalTime(LocalTime.parse("15:30:18")); + temporalValues.setOffsetTime(OffsetTime.parse("08:22:12+01:00")); + temporalValues.setInstant(Instant.parse("2017-11-15T08:22:12Z")); + temporalValues.setLocalDateTime(LocalDateTime.parse("2017-11-15T08:22:12")); + temporalValues.setOffsetDateTime(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); + temporalValues.setZonedDateTime(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getLocalDate()).isEqualTo(LocalDate.parse("2017-11-15")); + assertThat(temporalValues.getLocalTime()).isEqualTo(LocalTime.parse("15:30:18")); + assertThat(temporalValues.getOffsetTime()).isEqualTo(OffsetTime.parse("08:22:12+01:00")); + assertThat(temporalValues.getInstant()).isEqualTo(Instant.parse("2017-11-15T08:22:12Z")); + assertThat(temporalValues.getLocalDateTime()).isEqualTo(LocalDateTime.parse("2017-11-15T08:22:12")); + assertThat(temporalValues.getOffsetDateTime()).isEqualTo(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); + assertThat(temporalValues.getZonedDateTime()).isEqualTo(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); + + } + +} diff --git a/hibernate5/src/test/resources/hibernate-multitenancy.properties b/hibernate5/src/test/resources/hibernate-multitenancy.properties new file mode 100644 index 0000000000..298ecd05d3 --- /dev/null +++ b/hibernate5/src/test/resources/hibernate-multitenancy.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.multiTenancy=DATABASE diff --git a/hibernate5/src/test/resources/hibernate.properties b/hibernate5/src/test/resources/hibernate.properties index 298ecd05d3..7b8764637b 100644 --- a/hibernate5/src/test/resources/hibernate.properties +++ b/hibernate5/src/test/resources/hibernate.properties @@ -6,4 +6,4 @@ jdbc.password= hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true -hibernate.multiTenancy=DATABASE +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file 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/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/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java index 18488f9380..e95b63aa96 100644 --- a/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java @@ -51,7 +51,6 @@ public class MemberStatusIntegrationTest { /** * This test should fail, comment out @Ignore to see how failed test can be reflected in Serenity report.
- * Remember to add <testFailureIgnore>true</testFailureIgnore> under maven-surefire-plugin configuration. */ @Test @Ignore 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 91% rename from log4j/pom.xml rename to logging-modules/log4j/pom.xml index 2e73baac49..a3bfb0a33a 100644 --- a/log4j/pom.xml +++ b/logging-modules/log4j/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ @@ -26,12 +27,6 @@ ${log4j.version} - - log4j - apache-log4j-extras - ${log4j.version} - - org.apache.logging.log4j 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/mustache/pom.xml b/mustache/pom.xml index 8aab038313..230aeecd60 100644 --- a/mustache/pom.xml +++ b/mustache/pom.xml @@ -85,7 +85,6 @@ **/JdbcTest.java **/*LiveTest.java - true 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/parent-boot-4/pom.xml b/parent-boot-4/pom.xml index 2af36e9365..608e57ddaf 100644 --- a/parent-boot-4/pom.xml +++ b/parent-boot-4/pom.xml @@ -63,7 +63,7 @@ **/JdbcTest.java **/*LiveTest.java - true + diff --git a/parent-boot-5/pom.xml b/parent-boot-5/pom.xml index 57e9ed3c67..2fa397f298 100644 --- a/parent-boot-5/pom.xml +++ b/parent-boot-5/pom.xml @@ -65,7 +65,6 @@ **/*EntryPointsTest.java **/*LiveTest.java - true diff --git a/patterns/template-method/pom.xml b/patterns/template-method/pom.xml new file mode 100644 index 0000000000..c3b6a084ac --- /dev/null +++ b/patterns/template-method/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + com.baeldung.templatemethodpattern + templatemethodpattern + 1.0 + jar + + UTF-8 + 1.8 + 1.8 + + + + junit + junit + 4.12 + test + + + \ 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 new file mode 100644 index 0000000000..5570c2e1dd --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java @@ -0,0 +1,21 @@ +package com.baeldung.templatemethodpattern.application; + +import com.baeldung.templatemethodpattern.model.Computer; +import com.baeldung.templatemethodpattern.model.ComputerBuilder; +import com.baeldung.templatemethodpattern.model.HighEndComputerBuilder; +import com.baeldung.templatemethodpattern.model.StandardComputerBuilder; +import com.baeldung.templatemethodpattern.model.HighEndComputer; +import com.baeldung.templatemethodpattern.model.StandardComputer; + +public class Application { + + public static void main(String[] args) { + ComputerBuilder standardComputerBuilder = new StandardComputerBuilder(); + Computer standardComputer = standardComputerBuilder.buildComputer(); + standardComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v)); + + 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 new file mode 100644 index 0000000000..d422204b82 --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java @@ -0,0 +1,37 @@ +package com.baeldung.templatemethodpattern.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.ArrayList; +import java.util.List; + +public abstract class ComputerBuilder { + + protected Map computerParts = new HashMap<>(); + protected List moterboardSetupStatus = 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 moterboardSetupStatus; + } + + 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/ComputerBuilder.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/ComputerBuilder.java new file mode 100644 index 0000000000..9d8eae7f80 --- /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 moterboardSetupStatus = 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 moterboardSetupStatus; + } + + 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 new file mode 100644 index 0000000000..8d80e1e108 --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java @@ -0,0 +1,26 @@ +package com.baeldung.templatemethodpattern.model; + +public class HighEndComputer extends Computer { + + @Override + public void addMotherboard() { + computerParts.put("Motherboard", "High-end Motherboard"); + } + + @Override + public void setupMotherboard() { + moterboardSetupStatus.add("Screwing the high-end motherboard to the case."); + moterboardSetupStatus.add("Pluging in the power supply connectors."); + moterboardSetupStatus.forEach(step -> System.out.println(step)); + } + + @Override + public void addProcessor() { + computerParts.put("Processor", "High-end Processor"); + } + + @Override + public void addMotherboard() { + computerParts.put("Motherboard", "High End Motherboard"); + } +} 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..cf53a2ae6c --- /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() { + moterboardSetupStatus.add("Screwing the high-end motherboard to the case."); + moterboardSetupStatus.add("Pluging in the power supply connectors."); + moterboardSetupStatus.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 new file mode 100644 index 0000000000..8410ad88ee --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java @@ -0,0 +1,25 @@ +package com.baeldung.templatemethodpattern.model; + +public class StandardComputer extends Computer { + + public void addMotherboard() { + computerParts.put("Motherboard", "Standard Motherboard"); + } + + @Override + public void setupMotherboard() { + moterboardSetupStatus.add("Screwing the standard motherboard to the case."); + moterboardSetupStatus.add("Pluging in the power supply connectors."); + moterboardSetupStatus.forEach(step -> System.out.println(step)); + } + + @Override + public void addProcessor() { + computerParts.put("Processor", "Standard Processor"); + } + + @Override + public void addMotherboard() { + computerParts.put("Motherboard", "Standard Motherboard"); + } +} 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..1d9bd0e00f --- /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() { + moterboardSetupStatus.add("Screwing the standard motherboard to the case."); + moterboardSetupStatus.add("Pluging in the power supply connectors."); + moterboardSetupStatus.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 new file mode 100644 index 0000000000..39888d5ad5 --- /dev/null +++ b/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java @@ -0,0 +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 StandardComputerBuilder standardComputerBuilder; + private static HighEndComputerBuilder highEndComputerBuilder; + + @BeforeClass + public static void setUpStandardComputerBuilderInstance() { + standardComputerBuilder = new StandardComputerBuilder(); + } + + @BeforeClass + public static void setUpHighEndComputerBuilderInstance() { + highEndComputerBuilder = new HighEndComputerBuilder(); + } + + @Test + public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + standardComputer.addMotherboard(); + assertEquals("Standard Motherboard", standardComputer.getComputerParts().get("Motherboard")); + } + + @Test + public void givenStandardMotheroboard_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 givenAllStandardParts_whenComputerisBuilt_thenComputerInstance() { + assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); + } + + @Test + public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + 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 givenAllHighEndParts_whenBuildingComputer_thenTwoParts() { + highEndComputerBuilder.buildComputer(); + assertEquals(2, highEndComputerBuilder.getComputerParts().size()); + } + + @Test + public void givenAllHighEndParts_whenComputerisBuilt_thenComputerInstance() { + assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); + } +} 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/java-cassandra/README.md b/persistence-modules/java-cassandra/README.md similarity index 100% rename from java-cassandra/README.md rename to persistence-modules/java-cassandra/README.md diff --git a/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml similarity index 98% rename from java-cassandra/pom.xml rename to persistence-modules/java-cassandra/pom.xml index 12df920e7d..faaabb9e2e 100644 --- a/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java diff --git a/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java b/persistence-modules/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java similarity index 100% rename from java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java rename to persistence-modules/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java diff --git a/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java b/persistence-modules/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java similarity index 100% rename from java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java rename to persistence-modules/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java diff --git a/java-mongodb/.gitignore b/persistence-modules/java-mongodb/.gitignore similarity index 100% rename from java-mongodb/.gitignore rename to persistence-modules/java-mongodb/.gitignore diff --git a/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md similarity index 100% rename from java-mongodb/README.md rename to persistence-modules/java-mongodb/README.md diff --git a/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml similarity index 97% rename from java-mongodb/pom.xml rename to persistence-modules/java-mongodb/pom.xml index 304d961b0a..aab48921a6 100644 --- a/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/java-mongodb/src/main/java/com/baeldung/MongoExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java similarity index 100% rename from java-mongodb/src/main/java/com/baeldung/MongoExample.java rename to persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java diff --git a/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java similarity index 100% rename from java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java rename to persistence-modules/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java diff --git a/liquibase/README.md b/persistence-modules/liquibase/README.md similarity index 100% rename from liquibase/README.md rename to persistence-modules/liquibase/README.md diff --git a/liquibase/pom.xml b/persistence-modules/liquibase/pom.xml similarity index 97% rename from liquibase/pom.xml rename to persistence-modules/liquibase/pom.xml index d26acc8c98..020c2516a2 100644 --- a/liquibase/pom.xml +++ b/persistence-modules/liquibase/pom.xml @@ -6,6 +6,7 @@ parent-modules com.baeldung 1.0.0-SNAPSHOT + ../ 4.0.0 diff --git a/liquibase/src/main/resources/liquibase/db-changelog.xml b/persistence-modules/liquibase/src/main/resources/liquibase/db-changelog.xml similarity index 100% rename from liquibase/src/main/resources/liquibase/db-changelog.xml rename to persistence-modules/liquibase/src/main/resources/liquibase/db-changelog.xml diff --git a/liquibase/src/main/resources/liquibase/liquibase.properties b/persistence-modules/liquibase/src/main/resources/liquibase/liquibase.properties similarity index 100% rename from liquibase/src/main/resources/liquibase/liquibase.properties rename to persistence-modules/liquibase/src/main/resources/liquibase/liquibase.properties diff --git a/querydsl/README.md b/persistence-modules/querydsl/README.md similarity index 100% rename from querydsl/README.md rename to persistence-modules/querydsl/README.md diff --git a/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml similarity index 99% rename from querydsl/pom.xml rename to persistence-modules/querydsl/pom.xml index 6c968f01e4..27f383e0c6 100644 --- a/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -15,6 +15,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/querydsl/src/main/java/org/baeldung/dao/PersonDao.java b/persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDao.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/dao/PersonDao.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDao.java diff --git a/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java b/persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java diff --git a/querydsl/src/main/java/org/baeldung/entity/Person.java b/persistence-modules/querydsl/src/main/java/org/baeldung/entity/Person.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/entity/Person.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/entity/Person.java diff --git a/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java b/persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java diff --git a/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java b/persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java diff --git a/querydsl/src/main/resources/META-INF/persistence.xml b/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml similarity index 100% rename from querydsl/src/main/resources/META-INF/persistence.xml rename to persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml diff --git a/mockito/src/main/resources/logback.xml b/persistence-modules/querydsl/src/main/resources/logback.xml similarity index 100% rename from mockito/src/main/resources/logback.xml rename to persistence-modules/querydsl/src/main/resources/logback.xml diff --git a/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java b/persistence-modules/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java similarity index 100% rename from querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java rename to persistence-modules/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java diff --git a/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java b/persistence-modules/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java similarity index 100% rename from querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java rename to persistence-modules/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java diff --git a/querydsl/src/test/resources/db.properties b/persistence-modules/querydsl/src/test/resources/db.properties similarity index 100% rename from querydsl/src/test/resources/db.properties rename to persistence-modules/querydsl/src/test/resources/db.properties diff --git a/querydsl/src/test/resources/test-context.xml b/persistence-modules/querydsl/src/test/resources/test-context.xml similarity index 100% rename from querydsl/src/test/resources/test-context.xml rename to persistence-modules/querydsl/src/test/resources/test-context.xml diff --git a/querydsl/src/test/resources/test-db.xml b/persistence-modules/querydsl/src/test/resources/test-db.xml similarity index 100% rename from querydsl/src/test/resources/test-db.xml rename to persistence-modules/querydsl/src/test/resources/test-db.xml diff --git a/redis/README.md b/persistence-modules/redis/README.md similarity index 100% rename from redis/README.md rename to persistence-modules/redis/README.md diff --git a/redis/pom.xml b/persistence-modules/redis/pom.xml similarity index 96% rename from redis/pom.xml rename to persistence-modules/redis/pom.xml index db454188a7..ef081a2c69 100644 --- a/redis/pom.xml +++ b/persistence-modules/redis/pom.xml @@ -15,6 +15,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/redis/src/main/java/com/baeldung/CustomMessage.java b/persistence-modules/redis/src/main/java/com/baeldung/CustomMessage.java similarity index 100% rename from redis/src/main/java/com/baeldung/CustomMessage.java rename to persistence-modules/redis/src/main/java/com/baeldung/CustomMessage.java diff --git a/redis/src/main/java/com/baeldung/Ledger.java b/persistence-modules/redis/src/main/java/com/baeldung/Ledger.java similarity index 100% rename from redis/src/main/java/com/baeldung/Ledger.java rename to persistence-modules/redis/src/main/java/com/baeldung/Ledger.java diff --git a/redis/src/main/java/com/baeldung/LedgerLiveObject.java b/persistence-modules/redis/src/main/java/com/baeldung/LedgerLiveObject.java similarity index 100% rename from redis/src/main/java/com/baeldung/LedgerLiveObject.java rename to persistence-modules/redis/src/main/java/com/baeldung/LedgerLiveObject.java diff --git a/redis/src/main/java/com/baeldung/LedgerServiceImpl.java b/persistence-modules/redis/src/main/java/com/baeldung/LedgerServiceImpl.java similarity index 100% rename from redis/src/main/java/com/baeldung/LedgerServiceImpl.java rename to persistence-modules/redis/src/main/java/com/baeldung/LedgerServiceImpl.java diff --git a/redis/src/main/java/com/baeldung/LedgerServiceInterface.java b/persistence-modules/redis/src/main/java/com/baeldung/LedgerServiceInterface.java similarity index 100% rename from redis/src/main/java/com/baeldung/LedgerServiceInterface.java rename to persistence-modules/redis/src/main/java/com/baeldung/LedgerServiceInterface.java diff --git a/redis/src/main/resources/singleNodeConfig.json b/persistence-modules/redis/src/main/resources/singleNodeConfig.json similarity index 100% rename from redis/src/main/resources/singleNodeConfig.json rename to persistence-modules/redis/src/main/resources/singleNodeConfig.json diff --git a/redis/src/main/resources/singleNodeConfig.yaml b/persistence-modules/redis/src/main/resources/singleNodeConfig.yaml similarity index 100% rename from redis/src/main/resources/singleNodeConfig.yaml rename to persistence-modules/redis/src/main/resources/singleNodeConfig.yaml diff --git a/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java similarity index 100% rename from redis/src/test/java/com/baeldung/JedisIntegrationTest.java rename to persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java diff --git a/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java similarity index 100% rename from redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java rename to persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java diff --git a/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java similarity index 100% rename from redis/src/test/java/com/baeldung/RedissonIntegrationTest.java rename to persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java diff --git a/solr/README.md b/persistence-modules/solr/README.md similarity index 100% rename from solr/README.md rename to persistence-modules/solr/README.md diff --git a/solr/pom.xml b/persistence-modules/solr/pom.xml similarity index 94% rename from solr/pom.xml rename to persistence-modules/solr/pom.xml index 1b26a21edc..2fd0bdd721 100644 --- a/solr/pom.xml +++ b/persistence-modules/solr/pom.xml @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/solr/src/main/java/com/baeldung/solr/fulltext/search/model/Item.java b/persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/model/Item.java similarity index 100% rename from solr/src/main/java/com/baeldung/solr/fulltext/search/model/Item.java rename to persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/model/Item.java diff --git a/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchService.java b/persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchService.java similarity index 100% rename from solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchService.java rename to persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchService.java diff --git a/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceImpl.java b/persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceImpl.java similarity index 100% rename from solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceImpl.java rename to persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceImpl.java diff --git a/solr/src/test/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceLiveTest.java b/persistence-modules/solr/src/test/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceLiveTest.java similarity index 100% rename from solr/src/test/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceLiveTest.java rename to persistence-modules/solr/src/test/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceLiveTest.java diff --git a/spring-data-cassandra/README.md b/persistence-modules/spring-data-cassandra/README.md similarity index 100% rename from spring-data-cassandra/README.md rename to persistence-modules/spring-data-cassandra/README.md diff --git a/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml similarity index 99% rename from spring-data-cassandra/pom.xml rename to persistence-modules/spring-data-cassandra/pom.xml index fbc2071134..607d7b90ba 100644 --- a/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -13,6 +13,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java b/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java similarity index 100% rename from spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java rename to persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java b/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java similarity index 100% rename from spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java rename to persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java b/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java similarity index 100% rename from spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java rename to persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java diff --git a/spring-data-cassandra/src/main/resources/cassandra.properties b/persistence-modules/spring-data-cassandra/src/main/resources/cassandra.properties similarity index 100% rename from spring-data-cassandra/src/main/resources/cassandra.properties rename to persistence-modules/spring-data-cassandra/src/main/resources/cassandra.properties diff --git a/querydsl/src/main/resources/logback.xml b/persistence-modules/spring-data-cassandra/src/main/resources/logback.xml similarity index 100% rename from querydsl/src/main/resources/logback.xml rename to persistence-modules/spring-data-cassandra/src/main/resources/logback.xml diff --git a/spring-data-cassandra/src/main/resources/test.png b/persistence-modules/spring-data-cassandra/src/main/resources/test.png similarity index 100% rename from spring-data-cassandra/src/main/resources/test.png rename to persistence-modules/spring-data-cassandra/src/main/resources/test.png diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java similarity index 100% rename from spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java rename to persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java similarity index 100% rename from spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java rename to persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java similarity index 100% rename from spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java rename to persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java diff --git a/spring-data-dynamodb/.gitignore b/persistence-modules/spring-data-dynamodb/.gitignore similarity index 100% rename from spring-data-dynamodb/.gitignore rename to persistence-modules/spring-data-dynamodb/.gitignore diff --git a/spring-data-dynamodb/README.MD b/persistence-modules/spring-data-dynamodb/README.MD similarity index 100% rename from spring-data-dynamodb/README.MD rename to persistence-modules/spring-data-dynamodb/README.MD diff --git a/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml similarity index 96% rename from spring-data-dynamodb/pom.xml rename to persistence-modules/spring-data-dynamodb/pom.xml index 11bbbdf40f..bf90779c29 100644 --- a/spring-data-dynamodb/pom.xml +++ b/persistence-modules/spring-data-dynamodb/pom.xml @@ -12,7 +12,7 @@ parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../../parent-boot-5 diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/Application.java similarity index 100% rename from spring-data-dynamodb/src/main/java/com/baeldung/Application.java rename to persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/Application.java diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java similarity index 100% rename from spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java rename to persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java similarity index 100% rename from spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java rename to persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java similarity index 100% rename from spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java rename to persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java diff --git a/spring-data-dynamodb/src/main/resources/application.properties b/persistence-modules/spring-data-dynamodb/src/main/resources/application.properties similarity index 100% rename from spring-data-dynamodb/src/main/resources/application.properties rename to persistence-modules/spring-data-dynamodb/src/main/resources/application.properties diff --git a/spring-data-dynamodb/src/main/resources/demo.properties b/persistence-modules/spring-data-dynamodb/src/main/resources/demo.properties similarity index 100% rename from spring-data-dynamodb/src/main/resources/demo.properties rename to persistence-modules/spring-data-dynamodb/src/main/resources/demo.properties diff --git a/rest-assured/src/test/resources/logback.xml b/persistence-modules/spring-data-dynamodb/src/main/resources/logback.xml similarity index 100% rename from rest-assured/src/test/resources/logback.xml rename to persistence-modules/spring-data-dynamodb/src/main/resources/logback.xml diff --git a/spring-data-dynamodb/src/main/resources/templates/index.html b/persistence-modules/spring-data-dynamodb/src/main/resources/templates/index.html similarity index 100% rename from spring-data-dynamodb/src/main/resources/templates/index.html rename to persistence-modules/spring-data-dynamodb/src/main/resources/templates/index.html diff --git a/spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java b/persistence-modules/spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java similarity index 100% rename from spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java rename to persistence-modules/spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java diff --git a/spring-data-dynamodb/src/test/resources/application.properties b/persistence-modules/spring-data-dynamodb/src/test/resources/application.properties similarity index 100% rename from spring-data-dynamodb/src/test/resources/application.properties rename to persistence-modules/spring-data-dynamodb/src/test/resources/application.properties diff --git a/spring-data-dynamodb/src/test/resources/exception-hibernate.properties b/persistence-modules/spring-data-dynamodb/src/test/resources/exception-hibernate.properties similarity index 100% rename from spring-data-dynamodb/src/test/resources/exception-hibernate.properties rename to persistence-modules/spring-data-dynamodb/src/test/resources/exception-hibernate.properties diff --git a/spring-data-dynamodb/src/test/resources/exception.properties b/persistence-modules/spring-data-dynamodb/src/test/resources/exception.properties similarity index 100% rename from spring-data-dynamodb/src/test/resources/exception.properties rename to persistence-modules/spring-data-dynamodb/src/test/resources/exception.properties diff --git a/spring-data-gemfire/README.md b/persistence-modules/spring-data-gemfire/README.md similarity index 100% rename from spring-data-gemfire/README.md rename to persistence-modules/spring-data-gemfire/README.md diff --git a/spring-data-gemfire/pom.xml b/persistence-modules/spring-data-gemfire/pom.xml similarity index 98% rename from spring-data-gemfire/pom.xml rename to persistence-modules/spring-data-gemfire/pom.xml index ae7612d719..9108865b4c 100644 --- a/spring-data-gemfire/pom.xml +++ b/persistence-modules/spring-data-gemfire/pom.xml @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionExecution.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionExecution.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionExecution.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionExecution.java diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionImpl.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionImpl.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionImpl.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionImpl.java diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/GemfireConfiguration.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/GemfireConfiguration.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/GemfireConfiguration.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/GemfireConfiguration.java diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/model/Employee.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/model/Employee.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/model/Employee.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/model/Employee.java diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepository.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepository.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepository.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepository.java diff --git a/spring-data-gemfire/src/main/resources/application-context.xml b/persistence-modules/spring-data-gemfire/src/main/resources/application-context.xml similarity index 100% rename from spring-data-gemfire/src/main/resources/application-context.xml rename to persistence-modules/spring-data-gemfire/src/main/resources/application-context.xml diff --git a/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java b/persistence-modules/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java similarity index 100% rename from spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java rename to persistence-modules/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java diff --git a/spring-data-neo4j/README.md b/persistence-modules/spring-data-neo4j/README.md similarity index 100% rename from spring-data-neo4j/README.md rename to persistence-modules/spring-data-neo4j/README.md diff --git a/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml similarity index 99% rename from spring-data-neo4j/pom.xml rename to persistence-modules/spring-data-neo4j/pom.xml index e01e7d7294..0055850ec3 100644 --- a/spring-data-neo4j/pom.xml +++ b/persistence-modules/spring-data-neo4j/pom.xml @@ -10,6 +10,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java diff --git a/rest-testing/src/main/resources/logback.xml b/persistence-modules/spring-data-neo4j/src/main/resources/logback.xml similarity index 100% rename from rest-testing/src/main/resources/logback.xml rename to persistence-modules/spring-data-neo4j/src/main/resources/logback.xml diff --git a/spring-data-neo4j/src/main/resources/test.png b/persistence-modules/spring-data-neo4j/src/main/resources/test.png similarity index 100% rename from spring-data-neo4j/src/main/resources/test.png rename to persistence-modules/spring-data-neo4j/src/main/resources/test.png diff --git a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerLiveTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerLiveTest.java similarity index 100% rename from spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerLiveTest.java rename to persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerLiveTest.java diff --git a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java similarity index 100% rename from spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java rename to persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java diff --git a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java similarity index 100% rename from spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java rename to persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java diff --git a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java similarity index 100% rename from spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java rename to persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java diff --git a/spring-data-cassandra/src/main/resources/logback.xml b/persistence-modules/spring-data-neo4j/src/test/resources/logback.xml similarity index 100% rename from spring-data-cassandra/src/main/resources/logback.xml rename to persistence-modules/spring-data-neo4j/src/test/resources/logback.xml diff --git a/spring-data-redis/README.md b/persistence-modules/spring-data-redis/README.md similarity index 100% rename from spring-data-redis/README.md rename to persistence-modules/spring-data-redis/README.md diff --git a/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml similarity index 98% rename from spring-data-redis/pom.xml rename to persistence-modules/spring-data-redis/pom.xml index d2835595da..b184d7e369 100644 --- a/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java diff --git a/spring-data-dynamodb/src/main/resources/logback.xml b/persistence-modules/spring-data-redis/src/main/resources/logback.xml similarity index 100% rename from spring-data-dynamodb/src/main/resources/logback.xml rename to persistence-modules/spring-data-redis/src/main/resources/logback.xml diff --git a/spring-data-redis/src/main/resources/test.png b/persistence-modules/spring-data-redis/src/main/resources/test.png similarity index 100% rename from spring-data-redis/src/main/resources/test.png rename to persistence-modules/spring-data-redis/src/main/resources/test.png diff --git a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java similarity index 100% rename from spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java rename to persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java diff --git a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java similarity index 100% rename from spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java rename to persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java diff --git a/spring-data-solr/README.md b/persistence-modules/spring-data-solr/README.md similarity index 100% rename from spring-data-solr/README.md rename to persistence-modules/spring-data-solr/README.md diff --git a/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml similarity index 97% rename from spring-data-solr/pom.xml rename to persistence-modules/spring-data-solr/pom.xml index 48ddaa7085..0759c1dbc0 100644 --- a/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java b/persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java similarity index 100% rename from spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java rename to persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java b/persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java similarity index 100% rename from spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java rename to persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java b/persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java similarity index 100% rename from spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java rename to persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java diff --git a/spring-data-solr/src/main/resources/solr-named-queries.properties b/persistence-modules/spring-data-solr/src/main/resources/solr-named-queries.properties similarity index 100% rename from spring-data-solr/src/main/resources/solr-named-queries.properties rename to persistence-modules/spring-data-solr/src/main/resources/solr-named-queries.properties diff --git a/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java similarity index 100% rename from spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java rename to persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java diff --git a/mockito/.gitignore b/persistence-modules/spring-hibernate-3/.gitignore similarity index 100% rename from mockito/.gitignore rename to persistence-modules/spring-hibernate-3/.gitignore diff --git a/spring-hibernate3/README.md b/persistence-modules/spring-hibernate-3/README.md similarity index 100% rename from spring-hibernate3/README.md rename to persistence-modules/spring-hibernate-3/README.md diff --git a/spring-hibernate3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml similarity index 96% rename from spring-hibernate3/pom.xml rename to persistence-modules/spring-hibernate-3/pom.xml index c36b1c0522..8eee819572 100644 --- a/spring-hibernate3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -2,15 +2,16 @@ 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-hibernate3 + spring-hibernate-3 0.1-SNAPSHOT - spring-hibernate3 + spring-hibernate-3 com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ @@ -87,7 +88,7 @@ - spring-hibernate3 + spring-hibernate-3 src/main/resources diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/EventDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/EventDao.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/EventDao.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/EventDao.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/FooDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/FooDao.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/FooDao.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/FooDao.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IEventDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IEventDao.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IEventDao.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IEventDao.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IFooDao.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IFooDao.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IFooDao.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IOperations.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IOperations.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IOperations.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IOperations.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/model/Event.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Event.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/model/Event.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Event.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/model/Foo.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Foo.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/model/Foo.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Foo.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/service/EventService.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/EventService.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/service/EventService.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/EventService.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/service/FooService.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/FooService.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/service/FooService.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/FooService.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfig.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfig.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java diff --git a/spring-hibernate3/src/main/resources/exceptionDemo.cfg.xml b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemo.cfg.xml similarity index 100% rename from spring-hibernate3/src/main/resources/exceptionDemo.cfg.xml rename to persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemo.cfg.xml diff --git a/spring-hibernate3/src/main/resources/exceptionDemoPersistenceConfig.xml b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml similarity index 100% rename from spring-hibernate3/src/main/resources/exceptionDemoPersistenceConfig.xml rename to persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml diff --git a/spring-data-neo4j/src/main/resources/logback.xml b/persistence-modules/spring-hibernate-3/src/main/resources/logback.xml similarity index 100% rename from spring-data-neo4j/src/main/resources/logback.xml rename to persistence-modules/spring-hibernate-3/src/main/resources/logback.xml diff --git a/spring-hibernate3/src/main/resources/persistence-h2.properties b/persistence-modules/spring-hibernate-3/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-hibernate3/src/main/resources/persistence-h2.properties rename to persistence-modules/spring-hibernate-3/src/main/resources/persistence-h2.properties diff --git a/spring-hibernate3/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-hibernate-3/src/main/resources/persistence-mysql.properties similarity index 100% rename from spring-hibernate3/src/main/resources/persistence-mysql.properties rename to persistence-modules/spring-hibernate-3/src/main/resources/persistence-mysql.properties diff --git a/spring-hibernate3/src/main/resources/persistenceConfig.xml b/persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml similarity index 100% rename from spring-hibernate3/src/main/resources/persistenceConfig.xml rename to persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml diff --git a/spring-hibernate3/src/main/webapp/WEB-INF/view/sample.jsp b/persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/view/sample.jsp similarity index 100% rename from spring-hibernate3/src/main/webapp/WEB-INF/view/sample.jsp rename to persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/view/sample.jsp diff --git a/spring-hibernate3/src/main/webapp/WEB-INF/web.xml b/persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-hibernate3/src/main/webapp/WEB-INF/web.xml rename to persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/web.xml diff --git a/spring-hibernate3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java similarity index 100% rename from spring-hibernate3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java diff --git a/spring-hibernate3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java similarity index 100% rename from spring-hibernate3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java diff --git a/spring-hibernate3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java similarity index 100% rename from spring-hibernate3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java diff --git a/spring-hibernate3/.gitignore b/persistence-modules/spring-hibernate-3/src/test/resources/.gitignore similarity index 100% rename from spring-hibernate3/.gitignore rename to persistence-modules/spring-hibernate-3/src/test/resources/.gitignore diff --git a/spring-hibernate3/src/test/resources/.gitignore b/persistence-modules/spring-hibernate-5/.gitignore similarity index 100% rename from spring-hibernate3/src/test/resources/.gitignore rename to persistence-modules/spring-hibernate-5/.gitignore diff --git a/spring-hibernate5/README.md b/persistence-modules/spring-hibernate-5/README.md similarity index 100% rename from spring-hibernate5/README.md rename to persistence-modules/spring-hibernate-5/README.md diff --git a/spring-hibernate5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml similarity index 97% rename from spring-hibernate5/pom.xml rename to persistence-modules/spring-hibernate-5/pom.xml index dac43c4dd3..f1f3d10347 100644 --- a/spring-hibernate5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -2,15 +2,16 @@ 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-hibernate5 + spring-hibernate-5 0.1-SNAPSHOT - spring-hibernate5 + spring-hibernate-5 com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ @@ -136,7 +137,7 @@ - spring-hibernate5 + spring-hibernate-5 src/main/resources diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/IFooDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/IFooDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/IFooDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/IOperations.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/IOperations.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/IOperations.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/impl/FooHibernateDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/impl/FooHibernateDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/impl/FooHibernateDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/impl/FooHibernateDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/model/Foo.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/model/Foo.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/model/Foo.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/spring/PersistenceConfig.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java diff --git a/spring-hibernate5/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Config.xml similarity index 100% rename from spring-hibernate5/src/main/resources/hibernate5Config.xml rename to persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Config.xml diff --git a/spring-hibernate5/src/main/resources/immutable.cfg.xml b/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml similarity index 100% rename from spring-hibernate5/src/main/resources/immutable.cfg.xml rename to persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml diff --git a/spring-data-neo4j/src/test/resources/logback.xml b/persistence-modules/spring-hibernate-5/src/main/resources/logback.xml similarity index 100% rename from spring-data-neo4j/src/test/resources/logback.xml rename to persistence-modules/spring-hibernate-5/src/main/resources/logback.xml diff --git a/spring-hibernate5/src/main/resources/manytomany.cfg.xml b/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml similarity index 100% rename from spring-hibernate5/src/main/resources/manytomany.cfg.xml rename to persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml diff --git a/spring-hibernate5/src/main/resources/persistence-h2.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-hibernate5/src/main/resources/persistence-h2.properties rename to persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties diff --git a/spring-hibernate5/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-mysql.properties similarity index 100% rename from spring-hibernate5/src/main/resources/persistence-mysql.properties rename to persistence-modules/spring-hibernate-5/src/main/resources/persistence-mysql.properties diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java similarity index 100% rename from spring-hibernate5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java similarity index 100% rename from spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java similarity index 100% rename from spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java diff --git a/spring-hibernate5/src/test/java/com/baeldung/persistence/dao/common/HibernateDaoIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/dao/common/HibernateDaoIntegrationTest.java similarity index 100% rename from spring-hibernate5/src/test/java/com/baeldung/persistence/dao/common/HibernateDaoIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/dao/common/HibernateDaoIntegrationTest.java diff --git a/spring-hibernate5/.gitignore b/persistence-modules/spring-hibernate-5/src/test/resources/.gitignore similarity index 100% rename from spring-hibernate5/.gitignore rename to persistence-modules/spring-hibernate-5/src/test/resources/.gitignore diff --git a/pom.xml b/pom.xml index d537adf08e..20f7c4ffad 100644 --- a/pom.xml +++ b/pom.xml @@ -49,8 +49,8 @@ core-java-8 core-java-concurrency couchbase - cas-server - cas-secured-app + cas/cas-server + cas/cas-secured-app deltaspike dozer @@ -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 @@ -85,12 +85,12 @@ immutables jackson - + vavr javax-servlets javaxval jaxb - jee7 + jee-7 jjwt jpa-storedprocedure @@ -98,45 +98,46 @@ 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 pdf protobuffer - querydsl + persistence-modules/querydsl reactor-core - redis - rest-assured - rest-testing + persistence-modules/redis + testing-modules/rest-assured + testing-modules/rest-testing resteasy rxjava spring-swagger-codegen - selenium-junit-testng - solr + testing-modules/selenium-junit-testng + persistence-modules/solr spark-java spring-5-mvc @@ -149,26 +150,28 @@ spring-batch spring-bom spring-boot + spring-boot-keycloak + spring-boot-bootstrap spring-cloud-data-flow spring-cloud spring-core spring-cucumber spring-aop - spring-data-cassandra + persistence-modules/spring-data-cassandra spring-data-couchbase-2 - spring-data-dynamodb + persistence-modules/spring-data-dynamodb spring-data-elasticsearch spring-data-mongodb - spring-data-neo4j - spring-data-redis + persistence-modules/spring-data-neo4j + persistence-modules/spring-data-redis spring-data-rest - spring-data-solr + persistence-modules/spring-data-solr spring-dispatcher-servlet spring-exceptions spring-freemarker - spring-hibernate3 + persistence-modules/spring-hibernate-3 spring-hibernate4 - spring-hibernate5 + persistence-modules/spring-hibernate-5 spring-integration spring-jersey spring-jmeter-jenkins @@ -229,32 +232,36 @@ 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 rabbitmq vertx - spring-data-gemfire + persistence-modules/spring-data-gemfire mybatis spring-drools drools - liquibase + persistence-modules/liquibase spring-boot-property-exp - mockserver + testing-modules/mockserver undertow vertx-and-rxjava saas deeplearning4j + spring-boot-admin + lucene @@ -337,7 +344,7 @@ **/JdbcTest.java **/*LiveTest.java - true + diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 7b7ddcba88..b188ee590a 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -152,7 +152,7 @@ org.apache.maven.plugins maven-surefire-plugin - true + false **/*IntegrationTest.java diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 4dfede4dab..e9a65232d2 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -49,6 +49,18 @@ javax.json.bind-api ${jsonb-api.version} + + + + + + + + + + + + org.apache.geronimo.specs geronimo-json_1.1_spec @@ -88,6 +100,13 @@ test + + org.apache.commons + commons-collections4 + 4.1 + test + + org.junit.jupiter junit-jupiter-api diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java index 7bab288bab..a218c6b7cf 100644 --- a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java +++ b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -43,7 +43,8 @@ public class WebClientController { WebClient.RequestHeadersSpec requestSpec2 = uri2.body(BodyInserters.fromObject("data")); // inserters - BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); + BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters + .fromPublisher(Subscriber::onComplete, String.class); LinkedMultiValueMap map = new LinkedMultiValueMap<>(); map.add("key1", "value1"); 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-activiti/README.md b/spring-activiti/README.md index 3580e29a52..5007b03ec7 100644 --- a/spring-activiti/README.md +++ b/spring-activiti/README.md @@ -2,4 +2,4 @@ - [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) diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index c5289b20a6..92d9618b65 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -19,9 +19,11 @@ + com.example.activitiwithspring.ActivitiWithSpringApplication UTF-8 UTF-8 1.8 + 6.0.0 @@ -30,9 +32,14 @@ activiti-spring-boot-starter-basic 6.0.0 + + org.activiti + activiti-spring-boot-starter-security + ${activiti.version} + org.springframework.boot - spring-boot-starter-web + spring-boot-starter-thymeleaf @@ -67,7 +74,7 @@ **/JdbcTest.java **/*LiveTest.java - true + diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security.rar b/spring-activiti/src/main/java/com/baeldung/activiti/security.rar new file mode 100644 index 0000000000..38c4946168 Binary files /dev/null and b/spring-activiti/src/main/java/com/baeldung/activiti/security.rar differ diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java new file mode 100644 index 0000000000..f9394742cd --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.activiti.security.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login") + .setViewName("login"); + registry.addViewController("/homepage") + .setViewName("homepage"); + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java new file mode 100644 index 0000000000..671b246328 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java @@ -0,0 +1,54 @@ +package com.baeldung.activiti.security.config; + +import java.util.List; + +import org.activiti.engine.IdentityService; +import org.activiti.engine.RuntimeService; +import org.activiti.engine.TaskService; +import org.activiti.engine.runtime.ProcessInstance; +import org.activiti.engine.task.Task; +import org.activiti.spring.SpringProcessEngineConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ProcessController { + + @Autowired + private RuntimeService runtimeService; + + @Autowired + private TaskService taskService; + + @Autowired + private IdentityService identityService; + + @Autowired + SpringProcessEngineConfiguration config; + + @GetMapping("/protected-process") + public String startProcess() { + + String userId = SecurityContextHolder.getContext() + .getAuthentication() + .getName(); + + identityService.setAuthenticatedUserId(userId); + + ProcessInstance pi = runtimeService.startProcessInstanceByKey("protected-process"); + + List usertasks = taskService.createTaskQuery() + .processInstanceId(pi.getId()) + .list(); + + taskService.complete(usertasks.iterator() + .next() + .getId()); + + return "Process started. Number of currently running process instances = " + runtimeService.createProcessInstanceQuery() + .count(); + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityGroupManager.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityGroupManager.java new file mode 100644 index 0000000000..00fc674e22 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityGroupManager.java @@ -0,0 +1,86 @@ +package com.baeldung.activiti.security.config; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.activiti.engine.identity.Group; +import org.activiti.engine.identity.GroupQuery; +import org.activiti.engine.impl.GroupQueryImpl; +import org.activiti.engine.impl.Page; +import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.activiti.engine.impl.persistence.entity.GroupEntityImpl; +import org.activiti.engine.impl.persistence.entity.GroupEntityManagerImpl; +import org.activiti.engine.impl.persistence.entity.data.GroupDataManager; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +public class SpringSecurityGroupManager extends GroupEntityManagerImpl { + + private JdbcUserDetailsManager userManager; + + public SpringSecurityGroupManager(ProcessEngineConfigurationImpl processEngineConfiguration, GroupDataManager groupDataManager) { + super(processEngineConfiguration, groupDataManager); + } + + @Override + public List findGroupByQueryCriteria(GroupQueryImpl query, Page page) { + + if (query.getUserId() != null) { + return findGroupsByUser(query.getUserId()); + } + return null; + } + + @Override + public long findGroupCountByQueryCriteria(GroupQueryImpl query) { + return findGroupByQueryCriteria(query, null).size(); + } + + @Override + public List findGroupsByUser(String userId) { + UserDetails userDetails = userManager.loadUserByUsername(userId); + System.out.println("group manager"); + if (userDetails != null) { + List groups = userDetails.getAuthorities() + .stream() + .map(a -> a.getAuthority()) + .map(a -> { + Group g = new GroupEntityImpl(); + g.setId(a); + return g; + }) + .collect(Collectors.toList()); + return groups; + } + return null; + } + + public void setUserManager(JdbcUserDetailsManager userManager) { + this.userManager = userManager; + } + + public Group createNewGroup(String groupId) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + @Override + public void delete(String groupId) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + public GroupQuery createNewGroupQuery() { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public List findGroupsByNativeQuery(Map parameterMap, int firstResult, int maxResults) { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public long findGroupCountByNativeQuery(Map parameterMap) { + throw new UnsupportedOperationException("This operation is not supported!"); + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityUserManager.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityUserManager.java new file mode 100644 index 0000000000..ce9863eb6c --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityUserManager.java @@ -0,0 +1,144 @@ +package com.baeldung.activiti.security.config; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.activiti.engine.identity.Group; +import org.activiti.engine.identity.User; +import org.activiti.engine.identity.UserQuery; +import org.activiti.engine.impl.Page; +import org.activiti.engine.impl.UserQueryImpl; +import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.activiti.engine.impl.persistence.entity.GroupEntityImpl; +import org.activiti.engine.impl.persistence.entity.UserEntity; +import org.activiti.engine.impl.persistence.entity.UserEntityImpl; +import org.activiti.engine.impl.persistence.entity.UserEntityManagerImpl; +import org.activiti.engine.impl.persistence.entity.data.UserDataManager; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +public class SpringSecurityUserManager extends UserEntityManagerImpl { + + private JdbcUserDetailsManager userManager; + + public SpringSecurityUserManager(ProcessEngineConfigurationImpl processEngineConfiguration, UserDataManager userDataManager, JdbcUserDetailsManager userManager) { + super(processEngineConfiguration, userDataManager); + this.userManager = userManager; + } + + @Override + public UserEntity findById(String userId) { + UserDetails userDetails = userManager.loadUserByUsername(userId); + if (userDetails != null) { + UserEntityImpl user = new UserEntityImpl(); + user.setId(userId); + return user; + } + return null; + + } + + @Override + public List findUserByQueryCriteria(UserQueryImpl query, Page page) { + List users = null; + if (query.getGroupId() != null) { + users = userManager.findUsersInGroup(query.getGroupId()) + .stream() + .map(username -> { + User user = new UserEntityImpl(); + user.setId(username); + return user; + }) + .collect(Collectors.toList()); + if (page != null) { + return users.subList(page.getFirstResult(), page.getFirstResult() + page.getMaxResults()); + + } + return users; + } + + if (query.getId() != null) { + UserDetails userDetails = userManager.loadUserByUsername(query.getId()); + if (userDetails != null) { + UserEntityImpl user = new UserEntityImpl(); + user.setId(query.getId()); + return Collections.singletonList(user); + } + } + return null; + } + + @Override + public Boolean checkPassword(String userId, String password) { + return true; + } + + public void setUserManager(JdbcUserDetailsManager userManager) { + this.userManager = userManager; + } + + public User createNewUser(String userId) { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public void updateUser(User updatedUser) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + public void delete(UserEntity userEntity) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + @Override + public void deletePicture(User user) { + UserEntity userEntity = (UserEntity) user; + if (userEntity.getPictureByteArrayRef() != null) { + userEntity.getPictureByteArrayRef() + .delete(); + } + } + + public void delete(String userId) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + public long findUserCountByQueryCriteria(UserQueryImpl query) { + return findUserByQueryCriteria(query, null).size(); + } + + public List findGroupsByUser(String userId) { + UserDetails userDetails = userManager.loadUserByUsername(userId); + if (userDetails != null) { + List groups = userDetails.getAuthorities() + .stream() + .map(a -> a.getAuthority()) + .map(a -> { + Group g = new GroupEntityImpl(); + g.setId(a); + return g; + }) + .collect(Collectors.toList()); + return groups; + } + return null; + } + + public UserQuery createNewUserQuery() { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public List findUsersByNativeQuery(Map parameterMap, int firstResult, int maxResults) { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public long findUserCountByNativeQuery(Map parameterMap) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SecurityConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SecurityConfig.java new file mode 100644 index 0000000000..f471600553 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SecurityConfig.java @@ -0,0 +1,47 @@ +package com.baeldung.activiti.security.withactiviti; + +import org.activiti.engine.IdentityService; +import org.activiti.spring.security.IdentityServiceUserDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/protected-process*") + .authenticated() + .anyRequest() + .permitAll() + .and() + .formLogin() + .loginPage("/login") + .defaultSuccessUrl("/homepage") + .failureUrl("/login?error=true") + .and() + .csrf() + .disable() + .logout() + .logoutSuccessUrl("/login"); + } + + @Autowired + private IdentityService identityService; + + @Bean + public IdentityServiceUserDetailsService userDetailsService() { + return new IdentityServiceUserDetailsService(identityService); + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService()); + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SpringSecurityActivitiApplication.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SpringSecurityActivitiApplication.java new file mode 100644 index 0000000000..2270a4d684 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SpringSecurityActivitiApplication.java @@ -0,0 +1,34 @@ +package com.baeldung.activiti.security.withactiviti; + +import org.activiti.engine.IdentityService; +import org.activiti.engine.identity.Group; +import org.activiti.engine.identity.User; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication(scanBasePackages = { "com.baeldung.activiti.security.config", "com.baeldung.activiti.security.withactiviti" }) +public class SpringSecurityActivitiApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringSecurityActivitiApplication.class, args); + } + + @Bean + InitializingBean usersAndGroupsInitializer(IdentityService identityService) { + return new InitializingBean() { + public void afterPropertiesSet() throws Exception { + User user = identityService.newUser("activiti_user"); + user.setPassword("pass"); + identityService.saveUser(user); + + Group group = identityService.newGroup("user"); + group.setName("ROLE_USER"); + group.setType("USER"); + identityService.saveGroup(group); + identityService.createMembership(user.getId(), group.getId()); + } + }; + } +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/ActivitiSpringSecurityApplication.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/ActivitiSpringSecurityApplication.java new file mode 100644 index 0000000000..5878a5d678 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/ActivitiSpringSecurityApplication.java @@ -0,0 +1,39 @@ +package com.baeldung.activiti.security.withspring; + +import org.activiti.engine.impl.persistence.entity.data.impl.MybatisGroupDataManager; +import org.activiti.engine.impl.persistence.entity.data.impl.MybatisUserDataManager; +import org.activiti.spring.SpringProcessEngineConfiguration; +import org.activiti.spring.boot.SecurityAutoConfiguration; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +import com.baeldung.activiti.security.config.SpringSecurityGroupManager; +import com.baeldung.activiti.security.config.SpringSecurityUserManager; + +@SpringBootApplication(exclude = SecurityAutoConfiguration.class, scanBasePackages = { "com.baeldung.activiti.security.config", "com.baeldung.activiti.security.withspring" }) +public class ActivitiSpringSecurityApplication { + + public static void main(String[] args) { + SpringApplication.run(ActivitiSpringSecurityApplication.class, args); + } + + @Autowired + private SpringProcessEngineConfiguration processEngineConfiguration; + + @Autowired + private JdbcUserDetailsManager userManager; + + @Bean + InitializingBean processEngineInitializer() { + return new InitializingBean() { + public void afterPropertiesSet() throws Exception { + processEngineConfiguration.setUserEntityManager(new SpringSecurityUserManager(processEngineConfiguration, new MybatisUserDataManager(processEngineConfiguration), userManager)); + processEngineConfiguration.setGroupEntityManager(new SpringSecurityGroupManager(processEngineConfiguration, new MybatisGroupDataManager(processEngineConfiguration))); + } + }; + } +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java new file mode 100644 index 0000000000..df1991c3e4 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java @@ -0,0 +1,50 @@ +package com.baeldung.activiti.security.withspring; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +@Configuration +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private DataSource dataSource; + + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/protected-process*") + .authenticated() + .anyRequest() + .permitAll() + .and() + .formLogin() + .loginPage("/login") + .defaultSuccessUrl("/homepage") + .failureUrl("/login?error=true") + .and() + .csrf() + .disable() + .logout() + .logoutSuccessUrl("/login"); + } + + @Bean + public JdbcUserDetailsManager userDetailsManager() { + JdbcUserDetailsManager manager = new JdbcUserDetailsManager(); + manager.setDataSource(dataSource); + return manager; + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsManager()); + } + +} diff --git a/spring-activiti/src/main/resources/data.sql b/spring-activiti/src/main/resources/data.sql new file mode 100644 index 0000000000..cb9b72617a --- /dev/null +++ b/spring-activiti/src/main/resources/data.sql @@ -0,0 +1,3 @@ +insert into users(username, password, enabled) values ('spring_user', 'pass', true); + +insert into authorities(username, authority) values ('spring_user','ROLE_USER'); \ No newline at end of file diff --git a/spring-activiti/src/main/resources/processes/protected-process.bpmn20.xml b/spring-activiti/src/main/resources/processes/protected-process.bpmn20.xml new file mode 100644 index 0000000000..b7e04515cd --- /dev/null +++ b/spring-activiti/src/main/resources/processes/protected-process.bpmn20.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + ROLE_USER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-activiti/src/main/resources/schema.sql b/spring-activiti/src/main/resources/schema.sql new file mode 100644 index 0000000000..bf882895fd --- /dev/null +++ b/spring-activiti/src/main/resources/schema.sql @@ -0,0 +1,3 @@ +create table users(username varchar(255), password varchar(255), enabled boolean); + +create table authorities(username varchar(255),authority varchar(255)); \ No newline at end of file diff --git a/spring-activiti/src/main/resources/templates/login.html b/spring-activiti/src/main/resources/templates/login.html new file mode 100644 index 0000000000..53077fd5f3 --- /dev/null +++ b/spring-activiti/src/main/resources/templates/login.html @@ -0,0 +1,21 @@ + + + +

Login

+
+
" + user.getUsername() + "" + user.getEmail() + "
+ + + + + + + + + + + +
User:
Password:
+ + + \ No newline at end of file diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java new file mode 100644 index 0000000000..c2eeb96555 --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java @@ -0,0 +1,31 @@ +package com.example.activitiwithspring; + +import org.activiti.engine.IdentityService; +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.security.core.userdetails.UsernameNotFoundException; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.activiti.security.withspring.ActivitiSpringSecurityApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ActivitiSpringSecurityApplication.class) +@WebAppConfiguration +public class ActivitiSpringSecurityIntegrationTest { + @Autowired + private IdentityService identityService; + + @Test + public void whenUserExists_thenOk() { + identityService.setUserPicture("spring_user", null); + } + + @Test(expected = UsernameNotFoundException.class) + public void whenUserNonExistent_thenSpringException() { + identityService.setUserPicture("user3", null); + } + +} diff --git a/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java b/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java index a5f36fb716..00026baf07 100644 --- a/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java +++ b/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java @@ -16,10 +16,10 @@ import java.time.Month; @EnableAspectJAutoProxy public class AopConfiguration { - @Pointcut("execution(public String com.baeldung.performancemonitor.PersonService.getFullName(..))") + @Pointcut("execution(public String org.baeldung.performancemonitor.PersonService.getFullName(..))") public void monitor() { } - @Pointcut("execution(public int com.baeldung.performancemonitor.PersonService.getAge(..))") + @Pointcut("execution(public int org.baeldung.performancemonitor.PersonService.getAge(..))") public void myMonitor() { } @Bean @@ -30,7 +30,7 @@ public class AopConfiguration { @Bean public Advisor performanceMonitorAdvisor() { AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.monitor()"); + pointcut.setExpression("org.baeldung.performancemonitor.AopConfiguration.monitor()"); return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor()); } @@ -52,7 +52,7 @@ public class AopConfiguration { @Bean public Advisor myPerformanceMonitorAdvisor() { AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.myMonitor()"); + pointcut.setExpression("org.baeldung.performancemonitor.AopConfiguration.myMonitor()"); return new DefaultPointcutAdvisor(pointcut, myPerformanceMonitorInterceptor()); } diff --git a/spring-boot-admin/README.md b/spring-boot-admin/README.md new file mode 100644 index 0000000000..622533a6ad --- /dev/null +++ b/spring-boot-admin/README.md @@ -0,0 +1,17 @@ +## 1. Spring Boot Admin Server + +* mvn clean install +* mvn spring-boot:run +* starts on port 8080 +* login with admin/admin +* to activate mail notifications uncomment the starter mail dependency +and the mail configuration from application.properties +* add some real credentials if you want the app to send emails +* to activate Hipchat notifications proceed same as for email + +## 2. Spring Boot App Client + +* mvn clean install +* mvn spring-boot:run +* starts on port 8081 +* basic auth client/client \ No newline at end of file diff --git a/spring-boot-admin/pom.xml b/spring-boot-admin/pom.xml new file mode 100644 index 0000000000..9c1eeeabff --- /dev/null +++ b/spring-boot-admin/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + spring-boot-admin + 0.0.1-SNAPSHOT + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + UTF-8 + 1.5.8.RELEASE + + + + spring-boot-admin-server + spring-boot-admin-client + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + + + \ No newline at end of file diff --git a/cas-secured-app/.gitignore b/spring-boot-admin/spring-boot-admin-client/.gitignore similarity index 100% rename from cas-secured-app/.gitignore rename to spring-boot-admin/spring-boot-admin-client/.gitignore diff --git a/spring-boot-admin/spring-boot-admin-client/pom.xml b/spring-boot-admin/spring-boot-admin-client/pom.xml new file mode 100644 index 0000000000..d119450e0b --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/pom.xml @@ -0,0 +1,70 @@ + + + 4.0.0 + + spring-boot-admin-client + 0.0.1-SNAPSHOT + jar + + spring-boot-admin-client + Spring Boot Admin Client + + + spring-boot-admin + com.baeldung + 0.0.1-SNAPSHOT + ../../spring-boot-admin + + + + UTF-8 + UTF-8 + 1.8 + 1.5.4 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-security + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin-starter-client.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + build-info + + + + + + + + + diff --git a/spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java b/spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java new file mode 100644 index 0000000000..596da131a6 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.springbootadminclient; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootAdminClientApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootAdminClientApplication.class, args); + } +} diff --git a/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties b/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties new file mode 100644 index 0000000000..58c178ecd9 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties @@ -0,0 +1,16 @@ +#basic auth creddentials +security.user.name=client +security.user.password=client + +#configs to connect to a secured server +spring.boot.admin.url=http://localhost:8080 +spring.boot.admin.username=admin +spring.boot.admin.password=admin + +#configs to give secured server info +spring.boot.admin.client.metadata.user.name=${security.user.name} +spring.boot.admin.client.metadata.user.password=${security.user.password} + +#app config +spring.application.name=spring-boot-admin-client +server.port=8081 \ No newline at end of file diff --git a/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml b/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..ff96acae79 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + + %date [%thread] %-5level %logger{25} - %msg%n + + + + + + + \ No newline at end of file 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/SpringBootAdminClientApplicationTests.java new file mode 100644 index 0000000000..d70fb1c7cf --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java @@ -0,0 +1,55 @@ +package com.baeldung.springbootadminclient; + +import org.junit.Before; +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.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.junit.Assert.assertEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = RANDOM_PORT) +public class SpringBootAdminClientApplicationTests { + + @Autowired Environment environment; + + @Autowired WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders + .webAppContextSetup(wac) + .build(); + } + + @Test + public void whenEnvironmentAvailable_ThenAdminServerPropertiesExist() { + assertEquals(environment.getProperty("spring.boot.admin.url"), "http://localhost:8080"); + assertEquals(environment.getProperty("spring.boot.admin.username"), "admin"); + assertEquals(environment.getProperty("spring.boot.admin.password"), "admin"); + } + + @Test + public void whenHttpBasicAttempted_ThenSuccess() throws Exception { + mockMvc.perform(get("/env").with(httpBasic("client", "client"))); + } + + @Test + public void whenInvalidHttpBasicAttempted_ThenUnauthorized() throws Exception { + mockMvc + .perform(get("/env").with(httpBasic("client", "invalid"))) + .andExpect(status().isUnauthorized()); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/.gitignore b/spring-boot-admin/spring-boot-admin-server/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-admin/spring-boot-admin-server/pom.xml b/spring-boot-admin/spring-boot-admin-server/pom.xml new file mode 100644 index 0000000000..f28b7a3dc9 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + spring-boot-admin-server + 0.0.1-SNAPSHOT + jar + + spring-boot-admin-server + Spring Boot Admin Server + + + spring-boot-admin + com.baeldung + 0.0.1-SNAPSHOT + ../../spring-boot-admin + + + + UTF-8 + UTF-8 + 1.8 + 1.5.4 + 1.5.4 + + + + + org.springframework.boot + spring-boot-starter + + + + + de.codecentric + spring-boot-admin-server + ${spring-boot-admin-server.version} + + + de.codecentric + spring-boot-admin-server-ui + ${spring-boot-admin-server.version} + + + + + de.codecentric + spring-boot-admin-server-ui-login + ${spring-boot-admin-server.version} + + + org.springframework.boot + spring-boot-starter-security + + + com.hazelcast + hazelcast + + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin-starter-client.version} + + + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java new file mode 100644 index 0000000000..d1fb4e769b --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.springbootadminserver; + +import de.codecentric.boot.admin.config.EnableAdminServer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@EnableAdminServer +@SpringBootApplication +public class SpringBootAdminServerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootAdminServerApplication.class, args); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java new file mode 100644 index 0000000000..b19b7820af --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java @@ -0,0 +1,24 @@ +package com.baeldung.springbootadminserver.configs; + +import com.hazelcast.config.Config; +import com.hazelcast.config.EvictionPolicy; +import com.hazelcast.config.ListConfig; +import com.hazelcast.config.MapConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class HazelcastConfig { + + @Bean + public Config hazelcast() { + return new Config() + .setProperty("hazelcast.jmx", "true") + .addMapConfig(new MapConfig("spring-boot-admin-application-store") + .setBackupCount(1) + .setEvictionPolicy(EvictionPolicy.NONE)) + .addListConfig(new ListConfig("spring-boot-admin-event-store") + .setBackupCount(1) + .setMaxSize(1000)); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java new file mode 100644 index 0000000000..10a31464ab --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java @@ -0,0 +1,42 @@ +package com.baeldung.springbootadminserver.configs; + +import de.codecentric.boot.admin.notify.LoggingNotifier; +import de.codecentric.boot.admin.notify.RemindingNotifier; +import de.codecentric.boot.admin.notify.filter.FilteringNotifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; + +import java.util.concurrent.TimeUnit; + +@Configuration +@EnableScheduling +public class NotifierConfiguration { + + // @Autowired private Notifier notifier; + + @Bean + public LoggingNotifier notifier() { + return new LoggingNotifier(); + } + + @Bean + public FilteringNotifier filteringNotifier() { + return new FilteringNotifier(notifier()); + } + + @Bean + @Primary + public RemindingNotifier remindingNotifier() { + RemindingNotifier remindingNotifier = new RemindingNotifier(filteringNotifier()); + remindingNotifier.setReminderPeriod(TimeUnit.MINUTES.toMillis(5)); + return remindingNotifier; + } + + @Scheduled(fixedRate = 60_000L) + public void remind() { + remindingNotifier().sendReminders(); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java new file mode 100644 index 0000000000..4a7c8330b7 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.springbootadminserver.configs; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/login") + .permitAll(); + http + .logout() + .logoutUrl("/logout"); + http + .csrf() + .disable(); + http + .authorizeRequests() + .antMatchers("/login.html", "/**/*.css", "/img/**", "/third-party/**") + .permitAll(); + http + .authorizeRequests() + .antMatchers("/**") + .authenticated(); + http.httpBasic(); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties b/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties new file mode 100644 index 0000000000..362f6428e8 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties @@ -0,0 +1,28 @@ +spring.application.name=spring-boot-admin-server + +security.user.name=admin +security.user.password=admin + +#configs to connect to self register the admin server as a client +spring.boot.admin.url=http://localhost:8080 +spring.boot.admin.username=${security.user.name} +spring.boot.admin.password=${security.user.password} + +#configs to give secured server info +spring.boot.admin.client.metadata.user.name=${security.user.name} +spring.boot.admin.client.metadata.user.password=${security.user.password} + +#mail notifications +#spring.mail.host=smtp.gmail.com +#spring.mail.username=test@gmail.com +#spring.mail.password=password +#spring.mail.port=587 +#spring.mail.properties.mail.smtp.auth=true +#spring.mail.properties.mail.smtp.starttls.enable=true + +#spring.boot.admin.notify.mail.to=test@gmail.com + +#hipchat notifications +#spring.boot.admin.notify.hipchat.auth-token= +#spring.boot.admin.notify.hipchat.room-id= +#spring.boot.admin.notify.hipchat.url=https://youcompany.hipchat.com/v2/ \ No newline at end of file diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml b/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..ff96acae79 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + + %date [%thread] %-5level %logger{25} - %msg%n + + + + + + + \ No newline at end of file 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/HazelcastConfigTest.java new file mode 100644 index 0000000000..8ca50a6f75 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java @@ -0,0 +1,24 @@ +package com.baeldung.springbootadminserver; + +import com.baeldung.springbootadminserver.configs.HazelcastConfig; +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.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { HazelcastConfig.class }, webEnvironment = NONE) +public class HazelcastConfigTest { + + @Autowired private ApplicationContext applicationContext; + + @Test + public void whenApplicationContextStarts_HazelcastConfigBeanExists() { + assertNotEquals(applicationContext.getBean("hazelcast"), null); + } +} 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/NotifierConfigurationTest.java new file mode 100644 index 0000000000..85f6b374a4 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.springbootadminserver; + +import com.baeldung.springbootadminserver.configs.NotifierConfiguration; +import de.codecentric.boot.admin.notify.Notifier; +import de.codecentric.boot.admin.notify.RemindingNotifier; +import de.codecentric.boot.admin.notify.filter.FilteringNotifier; +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.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { NotifierConfiguration.class }, webEnvironment = NONE) +public class NotifierConfigurationTest { + + @Autowired private ApplicationContext applicationContext; + + @Test + public void whenApplicationContextStart_ThenNotifierBeanExists() { + Notifier notifier = (Notifier) applicationContext.getBean("notifier"); + assertNotEquals(notifier, null); + } + + @Test + public void whenApplicationContextStart_ThenFilteringNotifierBeanExists() { + FilteringNotifier filteringNotifier = (FilteringNotifier) applicationContext.getBean("filteringNotifier"); + assertNotEquals(filteringNotifier, null); + } + + @Test + public void whenApplicationContextStart_ThenRemindingNotifierBeanExists() { + RemindingNotifier remindingNotifier = (RemindingNotifier) applicationContext.getBean("remindingNotifier"); + assertNotEquals(remindingNotifier, null); + } + +} 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/WebSecurityConfigTest.java new file mode 100644 index 0000000000..40611f00f6 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java @@ -0,0 +1,71 @@ +package com.baeldung.springbootadminserver; + +import org.junit.Before; +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 org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class WebSecurityConfigTest { + + @Autowired WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders + .webAppContextSetup(wac) + .build(); + } + + @Test + public void whenApplicationStarts_ThenGetLoginPageWithSuccess() throws Exception { + mockMvc + .perform(get("/login.html")) + .andExpect(status().is2xxSuccessful()); + } + + @Test + public void whenFormLoginAttempted_ThenSuccess() throws Exception { + mockMvc.perform(formLogin("/login") + .user("admin") + .password("admin")); + } + + @Test + public void whenFormLoginWithSuccess_ThenApiEndpointsAreAccessible() throws Exception { + mockMvc.perform(formLogin("/login") + .user("admin") + .password("admin")); + + mockMvc + .perform(get("/api/applications/")) + .andExpect(status().is2xxSuccessful()); + + } + + @Test + public void whenHttpBasicAttempted_ThenSuccess() throws Exception { + mockMvc.perform(get("/env").with(httpBasic("admin", "admin"))); + } + + @Test + public void whenInvalidHttpBasicAttempted_ThenUnauthorized() throws Exception { + mockMvc + .perform(get("/env").with(httpBasic("admin", "invalid"))) + .andExpect(status().isUnauthorized()); + } + +} diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 9da37a3261..5ad8330a89 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - org.springframework.boot - spring-boot-starter-parent - 1.5.3.RELEASE - + parent-boot-5 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-5 + + diff --git a/spring-boot-keycloak/src/main/resources/templates/external.html b/spring-boot-keycloak/src/main/resources/templates/external.html new file mode 100644 index 0000000000..2f9cc76961 --- /dev/null +++ b/spring-boot-keycloak/src/main/resources/templates/external.html @@ -0,0 +1,31 @@ + + + + + +
+
+

Customer Portal

+
+
+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam + erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras + arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit + amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non + id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit + amet varius mauris. Nulla eu eros pharetra, tristique dui quis, + vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec + at leo.

+ +

Existing Customers

+
+ Enter the intranet: customers +
+
+ +
+ + + + diff --git a/spring-boot-keycloak/src/main/resources/templates/layout.html b/spring-boot-keycloak/src/main/resources/templates/layout.html new file mode 100644 index 0000000000..bab0c2982b --- /dev/null +++ b/spring-boot-keycloak/src/main/resources/templates/layout.html @@ -0,0 +1,18 @@ + + + +Customer Portal + + + + + \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java b/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java similarity index 99% rename from spring-boot/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java rename to spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java index 8e3436a8ef..41662e5c17 100644 --- a/spring-boot/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java +++ b/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java @@ -1,6 +1,5 @@ package com.baeldung.keycloak; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,6 +47,4 @@ public class KeycloakConfigurationTest { assertNotNull(keycloakPrincipal.getKeycloakSecurityContext()); } - - } diff --git a/spring-boot/.gitignore b/spring-boot/.gitignore index a64317df5e..88e3308e9d 100644 --- a/spring-boot/.gitignore +++ b/spring-boot/.gitignore @@ -2,4 +2,4 @@ .settings/ .classpath .project -/.apt_generated/ + 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/pom.xml b/spring-boot/pom.xml index 583aaf2984..d6ee022522 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -24,10 +24,6 @@ org.springframework.boot spring-boot-starter-web - - org.keycloak - keycloak-spring-boot-starter - org.springframework.boot spring-boot-starter-data-jpa @@ -76,7 +72,6 @@ tomcat-embed-core ${tomcat.version} - org.apache.tomcat.embed tomcat-embed-jasper @@ -173,17 +168,6 @@ artemis-server - - - - org.keycloak.bom - keycloak-adapter-bom - 3.3.0.CR2 - pom - import - - - spring-boot @@ -283,7 +267,7 @@ - org.baeldung.boot.DemoApplication + org.baeldung.demo.DemoApplication 4.3.4.RELEASE 2.2.1 3.1.1 @@ -294,4 +278,4 @@ 2.4.1.Final - + \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/Application.java b/spring-boot/src/main/java/org/baeldung/boot/Application.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/Application.java rename to spring-boot/src/main/java/org/baeldung/boot/Application.java index 1c1e466afc..78e95455b8 100644 --- a/spring-boot/src/main/java/org/baeldung/Application.java +++ b/spring-boot/src/main/java/org/baeldung/boot/Application.java @@ -1,4 +1,4 @@ -package org.baeldung; +package org.baeldung.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot/src/main/java/org/baeldung/client/Details.java b/spring-boot/src/main/java/org/baeldung/boot/client/Details.java similarity index 93% rename from spring-boot/src/main/java/org/baeldung/client/Details.java rename to spring-boot/src/main/java/org/baeldung/boot/client/Details.java index 2ae3adc38f..1e3ddf7b21 100644 --- a/spring-boot/src/main/java/org/baeldung/client/Details.java +++ b/spring-boot/src/main/java/org/baeldung/boot/client/Details.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package org.baeldung.boot.client; public class Details { diff --git a/spring-boot/src/main/java/org/baeldung/client/DetailsServiceClient.java b/spring-boot/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java similarity index 93% rename from spring-boot/src/main/java/org/baeldung/client/DetailsServiceClient.java rename to spring-boot/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java index 51fa7c6181..f2b9d6d030 100644 --- a/spring-boot/src/main/java/org/baeldung/client/DetailsServiceClient.java +++ b/spring-boot/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package org.baeldung.boot.client; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Service; diff --git a/spring-boot/src/main/java/org/baeldung/config/H2JpaConfig.java b/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java similarity index 89% rename from spring-boot/src/main/java/org/baeldung/config/H2JpaConfig.java rename to spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java index 62791bf180..4e4b2e06bd 100644 --- a/spring-boot/src/main/java/org/baeldung/config/H2JpaConfig.java +++ b/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package org.baeldung.boot.config; import java.util.Properties; @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.repository", "org.baeldung.boot.repository", "org.baeldung.boot.boottest" }) +@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest","org.baeldung.repository" }) @PropertySource("classpath:persistence-generic-entity.properties") @EnableTransactionManagement public class H2JpaConfig { @@ -41,7 +41,7 @@ public class H2JpaConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.model", "org.baeldung.boot.boottest" }); + em.setPackagesToScan(new String[] { "org.baeldung.boot.domain", "org.baeldung.boot.model", "org.baeldung.boot.boottest", "org.baeldung.model" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java new file mode 100644 index 0000000000..caf88c3be7 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java @@ -0,0 +1,28 @@ +package org.baeldung.boot.config; + +import org.baeldung.boot.converter.GenericBigDecimalConverter; +import org.baeldung.boot.converter.StringToEmployeeConverter; +import org.baeldung.boot.converter.StringToEnumConverterFactory; +import org.baeldung.boot.web.resolver.HeaderVersionArgumentResolver; +import org.springframework.context.annotation.Configuration; +import org.springframework.format.FormatterRegistry; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import java.util.List; + +@Configuration +public class WebConfig extends WebMvcConfigurerAdapter { + + @Override + public void addArgumentResolvers(final List argumentResolvers) { + argumentResolvers.add(new HeaderVersionArgumentResolver()); + } + + @Override + public void addFormatters(FormatterRegistry registry) { + registry.addConverter(new StringToEmployeeConverter()); + registry.addConverterFactory(new StringToEnumConverterFactory()); + registry.addConverter(new GenericBigDecimalConverter()); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java b/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java similarity index 92% rename from spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java rename to spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java index a9e7dee0b7..8b038e0335 100644 --- a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java +++ b/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java @@ -1,8 +1,8 @@ -package org.baeldung.controller; +package org.baeldung.boot.controller; -import org.baeldung.domain.GenericEntity; -import org.baeldung.domain.Modes; -import org.baeldung.web.resolver.Version; +import org.baeldung.boot.domain.GenericEntity; +import org.baeldung.boot.domain.Modes; +import org.baeldung.boot.web.resolver.Version; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-boot/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java b/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java similarity index 93% rename from spring-boot/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java rename to spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java index 9adaf7fd29..34ad11254c 100644 --- a/spring-boot/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java +++ b/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java @@ -1,43 +1,43 @@ -package org.baeldung.controller.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Objects; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -public class HelloWorldServlet extends HttpServlet { - private static final long serialVersionUID = 1L; - - public HelloWorldServlet() { - super(); - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - PrintWriter out = null; - try { - out = response.getWriter(); - out.println("HelloWorldServlet: GET METHOD"); - out.flush(); - } finally { - if (!Objects.isNull(out)) - out.close(); - } - } - - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - PrintWriter out = null; - try { - out = response.getWriter(); - out.println("HelloWorldServlet: POST METHOD"); - out.flush(); - } finally { - if (!Objects.isNull(out)) - out.close(); - } - } - -} +package org.baeldung.boot.controller.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Objects; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class HelloWorldServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + + public HelloWorldServlet() { + super(); + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + PrintWriter out = null; + try { + out = response.getWriter(); + out.println("HelloWorldServlet: GET METHOD"); + out.flush(); + } finally { + if (!Objects.isNull(out)) + out.close(); + } + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + PrintWriter out = null; + try { + out = response.getWriter(); + out.println("HelloWorldServlet: POST METHOD"); + out.flush(); + } finally { + if (!Objects.isNull(out)) + out.close(); + } + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java b/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java similarity index 93% rename from spring-boot/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java rename to spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java index 9a62bdbbf2..91547683c6 100644 --- a/spring-boot/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java +++ b/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java @@ -1,43 +1,43 @@ -package org.baeldung.controller.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Objects; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -public class SpringHelloWorldServlet extends HttpServlet { - private static final long serialVersionUID = 1L; - - public SpringHelloWorldServlet() { - super(); - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - PrintWriter out = null; - try { - out = response.getWriter(); - out.println("SpringHelloWorldServlet: GET METHOD"); - out.flush(); - } finally { - if (!Objects.isNull(out)) - out.close(); - } - } - - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - PrintWriter out = null; - try { - out = response.getWriter(); - out.println("SpringHelloWorldServlet: POST METHOD"); - out.flush(); - } finally { - if (!Objects.isNull(out)) - out.close(); - } - } - -} +package org.baeldung.boot.controller.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Objects; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class SpringHelloWorldServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + + public SpringHelloWorldServlet() { + super(); + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + PrintWriter out = null; + try { + out = response.getWriter(); + out.println("SpringHelloWorldServlet: GET METHOD"); + out.flush(); + } finally { + if (!Objects.isNull(out)) + out.close(); + } + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + PrintWriter out = null; + try { + out = response.getWriter(); + out.println("SpringHelloWorldServlet: POST METHOD"); + out.flush(); + } finally { + if (!Objects.isNull(out)) + out.close(); + } + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java new file mode 100644 index 0000000000..decd8ac5db --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java @@ -0,0 +1,38 @@ +package org.baeldung.boot.converter; + +import com.google.common.collect.ImmutableSet; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.GenericConverter; + +import java.math.BigDecimal; +import java.math.MathContext; +import java.util.Set; + +public class GenericBigDecimalConverter implements GenericConverter { + @Override + public Set getConvertibleTypes () { + + ConvertiblePair[] pairs = new ConvertiblePair[] { + new ConvertiblePair(Number.class, BigDecimal.class), + new ConvertiblePair(String.class, BigDecimal.class)}; + + return ImmutableSet.copyOf(pairs); + } + + @Override + public Object convert (Object source, TypeDescriptor sourceType, + TypeDescriptor targetType) { + if (sourceType.getType() == BigDecimal.class) { + return source; + } + + if(sourceType.getType() == String.class) { + String number = (String) source; + return new BigDecimal(number); + } else { + Number number = (Number) source; + BigDecimal converted = new BigDecimal(number.doubleValue()); + return converted.setScale(2, BigDecimal.ROUND_HALF_EVEN); + } + } +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java new file mode 100644 index 0000000000..de9cf3f55a --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java @@ -0,0 +1,14 @@ +package org.baeldung.boot.converter; + + +import com.baeldung.toggle.Employee; +import org.springframework.core.convert.converter.Converter; + +public class StringToEmployeeConverter implements Converter { + + @Override + public Employee convert(String from) { + String[] data = from.split(","); + return new Employee(Long.parseLong(data[0]), Double.parseDouble(data[1])); + } +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java rename to spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java index 17c6fd06de..6fa51bfdcc 100644 --- a/spring-boot/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java @@ -1,4 +1,4 @@ -package org.baeldung.converter; +package org.baeldung.boot.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; diff --git a/spring-boot/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java similarity index 92% rename from spring-boot/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java rename to spring-boot/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java index cbb9e6ddb4..8a08b438f2 100644 --- a/spring-boot/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java @@ -1,4 +1,4 @@ -package org.baeldung.converter; +package org.baeldung.boot.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java new file mode 100644 index 0000000000..ad921c2c43 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -0,0 +1,16 @@ +package org.baeldung.boot.converter.controller; + +import com.baeldung.toggle.Employee; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/string-to-employee") +public class StringToEmployeeConverterController { + + @GetMapping + public ResponseEntity getStringToEmployee(@RequestParam("employee") Employee employee) { + return ResponseEntity.ok(employee); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/domain/GenericEntity.java b/spring-boot/src/main/java/org/baeldung/boot/domain/GenericEntity.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/domain/GenericEntity.java rename to spring-boot/src/main/java/org/baeldung/boot/domain/GenericEntity.java index 7b1d27cb66..f1c936e432 100644 --- a/spring-boot/src/main/java/org/baeldung/domain/GenericEntity.java +++ b/spring-boot/src/main/java/org/baeldung/boot/domain/GenericEntity.java @@ -1,4 +1,4 @@ -package org.baeldung.domain; +package org.baeldung.boot.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot/src/main/java/org/baeldung/domain/Modes.java b/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java similarity index 54% rename from spring-boot/src/main/java/org/baeldung/domain/Modes.java rename to spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java index 473406ef26..dcba064e8c 100644 --- a/spring-boot/src/main/java/org/baeldung/domain/Modes.java +++ b/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java @@ -1,4 +1,4 @@ -package org.baeldung.domain; +package org.baeldung.boot.domain; public enum Modes { diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/User.java b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/User.java similarity index 86% rename from spring-boot/src/main/java/org/baeldung/jsoncomponent/User.java rename to spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/User.java index 8961874526..1f14131300 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/User.java +++ b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/User.java @@ -1,4 +1,4 @@ -package org.baeldung.jsoncomponent; +package org.baeldung.boot.jsoncomponent; import javafx.scene.paint.Color; diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java similarity index 97% rename from spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java rename to spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java index cb1b838ca4..4d3a2cf99e 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java +++ b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java @@ -1,4 +1,4 @@ -package org.baeldung.jsoncomponent; +package org.baeldung.boot.jsoncomponent; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java rename to spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java index a310dcba5a..ad82ca06c0 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java +++ b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java @@ -1,4 +1,4 @@ -package org.baeldung.jsoncomponent; +package org.baeldung.boot.jsoncomponent; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonSerializer.java similarity index 96% rename from spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java rename to spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonSerializer.java index 845bc3aac5..03330d81a4 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java +++ b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonSerializer.java @@ -1,4 +1,4 @@ -package org.baeldung.jsoncomponent; +package org.baeldung.boot.jsoncomponent; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java b/spring-boot/src/main/java/org/baeldung/boot/monitor/jmx/MonitoringConfig.java similarity index 90% rename from spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java rename to spring-boot/src/main/java/org/baeldung/boot/monitor/jmx/MonitoringConfig.java index 40f36ef924..d2e8fc228f 100644 --- a/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java +++ b/spring-boot/src/main/java/org/baeldung/boot/monitor/jmx/MonitoringConfig.java @@ -1,22 +1,22 @@ -package org.baeldung.monitor.jmx; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.codahale.metrics.JmxReporter; -import com.codahale.metrics.MetricRegistry; - -@Configuration -public class MonitoringConfig { - @Autowired - private MetricRegistry registry; - - @Bean - public JmxReporter jmxReporter() { - JmxReporter reporter = JmxReporter.forRegistry(registry) - .build(); - reporter.start(); - return reporter; - } -} +package org.baeldung.boot.monitor.jmx; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.codahale.metrics.JmxReporter; +import com.codahale.metrics.MetricRegistry; + +@Configuration +public class MonitoringConfig { + @Autowired + private MetricRegistry registry; + + @Bean + public JmxReporter jmxReporter() { + JmxReporter reporter = JmxReporter.forRegistry(registry) + .build(); + reporter.start(); + return reporter; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/repository/GenericEntityRepository.java b/spring-boot/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java similarity index 64% rename from spring-boot/src/main/java/org/baeldung/repository/GenericEntityRepository.java rename to spring-boot/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java index 7bb1e6dcdc..d897e17afe 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/GenericEntityRepository.java +++ b/spring-boot/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.repository; +package org.baeldung.boot.repository; -import org.baeldung.domain.GenericEntity; +import org.baeldung.boot.domain.GenericEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface GenericEntityRepository extends JpaRepository { diff --git a/spring-boot/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java b/spring-boot/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java similarity index 96% rename from spring-boot/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java rename to spring-boot/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java index 89a77f38d1..b3a0dba7e8 100644 --- a/spring-boot/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java +++ b/spring-boot/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java @@ -1,4 +1,4 @@ -package org.baeldung.web.resolver; +package org.baeldung.boot.web.resolver; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; diff --git a/spring-boot/src/main/java/org/baeldung/web/resolver/Version.java b/spring-boot/src/main/java/org/baeldung/boot/web/resolver/Version.java similarity index 86% rename from spring-boot/src/main/java/org/baeldung/web/resolver/Version.java rename to spring-boot/src/main/java/org/baeldung/boot/web/resolver/Version.java index 2a9e6e60b3..f69d40510e 100644 --- a/spring-boot/src/main/java/org/baeldung/web/resolver/Version.java +++ b/spring-boot/src/main/java/org/baeldung/boot/web/resolver/Version.java @@ -1,4 +1,4 @@ -package org.baeldung.web.resolver; +package org.baeldung.boot.web.resolver; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-boot/src/main/java/org/baeldung/config/WebConfig.java b/spring-boot/src/main/java/org/baeldung/config/WebConfig.java deleted file mode 100644 index 4ef407823e..0000000000 --- a/spring-boot/src/main/java/org/baeldung/config/WebConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.config; - -import org.baeldung.web.resolver.HeaderVersionArgumentResolver; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.method.support.HandlerMethodArgumentResolver; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -import java.util.List; - -@Configuration -public class WebConfig extends WebMvcConfigurerAdapter { - - @Override - public void addArgumentResolvers(final List argumentResolvers) { - argumentResolvers.add(new HeaderVersionArgumentResolver()); - } -} diff --git a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java b/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java rename to spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java index cb269f77f1..c4b0d48244 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.boot; +package org.baeldung.demo; import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; diff --git a/spring-boot/src/main/java/org/baeldung/boot/boottest/Employee.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/boot/boottest/Employee.java rename to spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java index a805e8f5fe..c1dd109f91 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/boottest/Employee.java +++ b/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeRepository.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java similarity index 91% rename from spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeRepository.java rename to spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java index 98d1c33212..d991d9a8a9 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeRepository.java +++ b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeRestController.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java similarity index 96% rename from spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeRestController.java rename to spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java index 1bfde0f0bd..516bff0e8c 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeRestController.java +++ b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeService.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java similarity index 89% rename from spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeService.java rename to spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java index 13b5ca56e0..07765a511c 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeService.java +++ b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeServiceImpl.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java similarity index 96% rename from spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeServiceImpl.java rename to spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java index 3fbfa92bc8..bd85234e02 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/boottest/EmployeeServiceImpl.java +++ b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java b/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java similarity index 76% rename from spring-boot/src/main/java/org/baeldung/boot/components/FooService.java rename to spring-boot/src/main/java/org/baeldung/demo/components/FooService.java index 4ff8e9fdd4..334730ccb0 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java +++ b/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java @@ -1,7 +1,7 @@ -package org.baeldung.boot.components; +package org.baeldung.demo.components; -import org.baeldung.boot.model.Foo; -import org.baeldung.boot.repository.FooRepository; +import org.baeldung.demo.model.Foo; +import org.baeldung.demo.repository.FooRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java b/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java similarity index 85% rename from spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java rename to spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java index e03b859eab..51dd7bbd44 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java +++ b/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.exceptions; +package org.baeldung.demo.exceptions; public class CommonException extends RuntimeException { diff --git a/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java b/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java similarity index 86% rename from spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java rename to spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java index 0b04bd2759..59796c58f0 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java +++ b/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.exceptions; +package org.baeldung.demo.exceptions; public class FooNotFoundException extends RuntimeException { diff --git a/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java b/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/boot/model/Foo.java rename to spring-boot/src/main/java/org/baeldung/demo/model/Foo.java index d373e25b85..e5638cfd3d 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java +++ b/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.model; +package org.baeldung.demo.model; import java.io.Serializable; diff --git a/spring-boot/src/main/java/org/baeldung/boot/repository/FooRepository.java b/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java similarity index 70% rename from spring-boot/src/main/java/org/baeldung/boot/repository/FooRepository.java rename to spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java index 09d6975dba..c04e0c7438 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/repository/FooRepository.java +++ b/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.boot.repository; +package org.baeldung.demo.repository; -import org.baeldung.boot.model.Foo; +import org.baeldung.demo.model.Foo; import org.springframework.data.jpa.repository.JpaRepository; public interface FooRepository extends JpaRepository { diff --git a/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java b/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java similarity index 85% rename from spring-boot/src/main/java/org/baeldung/boot/service/FooController.java rename to spring-boot/src/main/java/org/baeldung/demo/service/FooController.java index d400c3bf9e..c28dcde1a7 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java +++ b/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java @@ -1,7 +1,7 @@ -package org.baeldung.boot.service; +package org.baeldung.demo.service; -import org.baeldung.boot.components.FooService; -import org.baeldung.boot.model.Foo; +import org.baeldung.demo.components.FooService; +import org.baeldung.demo.model.Foo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDao.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDao.java new file mode 100644 index 0000000000..180f54326e --- /dev/null +++ b/spring-boot/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-boot/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java new file mode 100644 index 0000000000..997e461cde --- /dev/null +++ b/spring-boot/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-boot/src/main/java/org/baeldung/dsrouting/ClientDatabase.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabase.java new file mode 100644 index 0000000000..619b8707d8 --- /dev/null +++ b/spring-boot/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-boot/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java new file mode 100644 index 0000000000..c08559e877 --- /dev/null +++ b/spring-boot/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-boot/src/main/java/org/baeldung/dsrouting/ClientService.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientService.java new file mode 100644 index 0000000000..4b63c6333c --- /dev/null +++ b/spring-boot/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-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java b/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java index 790584644f..34b50a2c0a 100644 --- a/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java +++ b/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java @@ -3,7 +3,7 @@ package org.baeldung.endpoints.info; import java.util.HashMap; import java.util.Map; -import org.baeldung.boot.repository.UserRepository; +import org.baeldung.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; diff --git a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java index 2d118b0eae..0ab4ecb128 100644 --- a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java @@ -1,9 +1,9 @@ package org.baeldung.main; +import org.baeldung.boot.controller.servlet.HelloWorldServlet; +import org.baeldung.boot.controller.servlet.SpringHelloWorldServlet; import org.baeldung.common.error.SpringHelloServletRegistrationBean; import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; -import org.baeldung.controller.servlet.HelloWorldServlet; -import org.baeldung.controller.servlet.SpringHelloWorldServlet; import org.baeldung.service.LoginService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; @@ -11,6 +11,7 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -21,7 +22,7 @@ import java.util.concurrent.Executors; @RestController @EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class) -@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" }) +@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources","org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config"}) public class SpringBootApplication { private static ApplicationContext applicationContext; diff --git a/spring-boot/src/main/java/org/baeldung/boot/model/User.java b/spring-boot/src/main/java/org/baeldung/model/User.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/boot/model/User.java rename to spring-boot/src/main/java/org/baeldung/model/User.java index f60ac86fe4..61936584c4 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/model/User.java +++ b/spring-boot/src/main/java/org/baeldung/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.model; +package org.baeldung.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot/src/main/java/org/baeldung/boot/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java similarity index 77% rename from spring-boot/src/main/java/org/baeldung/boot/repository/UserRepository.java rename to spring-boot/src/main/java/org/baeldung/repository/UserRepository.java index 3a419a65bd..360dbf883c 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.boot.repository; +package org.baeldung.repository; -import org.baeldung.boot.model.User; +import org.baeldung.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java index c0cc669420..70c68368b5 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java @@ -1,6 +1,6 @@ package org.baeldung.session.exception; -import org.baeldung.boot.model.Foo; +import org.baeldung.demo.model.Foo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java index 679d691b26..ce7bbfe57b 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java @@ -1,6 +1,6 @@ package org.baeldung.session.exception.repository; -import org.baeldung.boot.model.Foo; +import org.baeldung.demo.model.Foo; public interface FooRepository { diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java index 36d87e6dad..11df542d05 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -1,6 +1,6 @@ package org.baeldung.session.exception.repository; -import org.baeldung.boot.model.Foo; +import org.baeldung.demo.model.Foo; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 18d1223d43..458b4e0d46 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -49,10 +49,3 @@ contactInfoType=email endpoints.beans.id=springbeans endpoints.beans.sensitive=false - -#Keycloak Configuration -keycloak.auth-server-url=http://localhost:8180/auth -keycloak.realm=SpringBootKeycloak -keycloak.resource=login-app -keycloak.public-client=true -keycloak.principal-attribute=preferred_username diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index 358ba942d9..823625f811 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -1,6 +1,7 @@ package org.baeldung; -import org.baeldung.domain.Modes; +import org.baeldung.boot.Application; +import org.baeldung.boot.domain.Modes; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java index 185a36e571..2cb2f4dc10 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java @@ -1,8 +1,9 @@ package org.baeldung; -import org.baeldung.config.H2JpaConfig; -import org.baeldung.domain.GenericEntity; -import org.baeldung.repository.GenericEntityRepository; +import org.baeldung.boot.Application; +import org.baeldung.boot.config.H2JpaConfig; +import org.baeldung.boot.domain.GenericEntity; +import org.baeldung.boot.repository.GenericEntityRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java index 7c90622cdc..d9c30c67da 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java @@ -1,7 +1,8 @@ package org.baeldung; -import org.baeldung.domain.GenericEntity; -import org.baeldung.repository.GenericEntityRepository; +import org.baeldung.boot.Application; +import org.baeldung.boot.domain.GenericEntity; +import org.baeldung.boot.repository.GenericEntityRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java index 0e8a698f41..17e7d2d9e0 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java @@ -1,5 +1,6 @@ package org.baeldung; +import org.baeldung.boot.Application; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java index 9dd473f321..1d4ee262b0 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java @@ -1,8 +1,9 @@ package org.baeldung; +import org.baeldung.boot.Application; +import org.baeldung.boot.domain.GenericEntity; +import org.baeldung.boot.repository.GenericEntityRepository; import org.baeldung.config.H2TestProfileJPAConfig; -import org.baeldung.domain.GenericEntity; -import org.baeldung.repository.GenericEntityRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java index 4fcea35b4a..fba816c681 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java @@ -1,5 +1,6 @@ package org.baeldung.boot; +import org.baeldung.demo.DemoApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java similarity index 92% rename from spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java rename to spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java index 0f6c13ae1f..6f1cc66979 100644 --- a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package org.baeldung.boot.client; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; @@ -14,6 +14,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import org.baeldung.boot.client.Details; +import org.baeldung.boot.client.DetailsServiceClient; + @RunWith(SpringRunner.class) @RestClientTest(DetailsServiceClient.class) public class DetailsServiceClientIntegrationTest { diff --git a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonDeserializerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializerIntegrationTest.java similarity index 89% rename from spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonDeserializerIntegrationTest.java rename to spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializerIntegrationTest.java index 4f5af3d0e7..f8b47a23fc 100644 --- a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonDeserializerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializerIntegrationTest.java @@ -1,7 +1,9 @@ -package org.baeldung.jsoncomponent; +package org.baeldung.boot.jsoncomponent; import com.fasterxml.jackson.databind.ObjectMapper; import javafx.scene.paint.Color; + +import org.baeldung.boot.jsoncomponent.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonSerializerIntegrationTest.java similarity index 90% rename from spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java rename to spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonSerializerIntegrationTest.java index ac47c5e5d9..060374e8fa 100644 --- a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonSerializerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jsoncomponent; +package org.baeldung.boot.jsoncomponent; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -11,6 +11,8 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertEquals; +import org.baeldung.boot.jsoncomponent.User; + @JsonTest @RunWith(SpringRunner.class) public class UserJsonSerializerIntegrationTest { diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java index a844b26b2d..5d02d34f53 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java @@ -3,7 +3,8 @@ package org.baeldung.boot.repository; import static org.junit.Assert.assertThat; import org.baeldung.boot.DemoApplicationIntegrationTest; -import org.baeldung.boot.model.Foo; +import org.baeldung.demo.model.Foo; +import org.baeldung.demo.repository.FooRepository; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.is; diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java index be992bcc36..4658861162 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -5,7 +5,7 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.baeldung.boot.ApplicationIntegrationTest; -import org.baeldung.boot.model.Foo; +import org.baeldung.demo.model.Foo; import org.baeldung.session.exception.repository.FooRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 55b7fa7216..8de7068949 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -1,7 +1,7 @@ package org.baeldung.boot.repository; import org.baeldung.boot.ApplicationIntegrationTest; -import org.baeldung.boot.model.Foo; +import org.baeldung.demo.model.Foo; import org.baeldung.session.exception.repository.FooRepository; import org.hibernate.HibernateException; import org.junit.Test; diff --git a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java b/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java index eff383b440..499a755ae7 100644 --- a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java +++ b/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java @@ -41,7 +41,7 @@ public class H2TestProfileJPAConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.model", "org.baeldung.boot.boottest" }); + em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain", "org.baeldung.boot.boottest","org.baeldung.model" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterTest.java b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterTest.java new file mode 100644 index 0000000000..fb773fc44c --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterTest.java @@ -0,0 +1,54 @@ +package org.baeldung.converter; + +import com.baeldung.toggle.Employee; + +import org.baeldung.boot.Application; +import org.baeldung.boot.domain.Modes; +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.core.convert.ConversionService; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import java.math.BigDecimal; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = Application.class) +@WebAppConfiguration +public class CustomConverterTest { + + @Autowired + ConversionService conversionService; + + @Test + public void whenConvertStringToIntegerUsingDefaultConverter_thenSuccess() { + assertThat(conversionService.convert("25", Integer.class)).isEqualTo(25); + } + + @Test + public void whenConvertStringToEmployee_thenSuccess() { + Employee employee = conversionService.convert("1,50000.00", Employee.class); + Employee actualEmployee = new Employee(1, 50000.00); + assertThat(conversionService.convert("1,50000.00", Employee.class)) + .isEqualToComparingFieldByField(actualEmployee); + } + + @Test + public void whenConvertStringToEnum_thenSuccess() { + assertThat(conversionService.convert("ALPHA", Modes.class)).isEqualTo(Modes.ALPHA); + } + + @Test + public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() { + assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)) + .isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN)); + assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)) + .isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23))); + assertThat(conversionService.convert("2.32", BigDecimal.class)) + .isEqualTo(BigDecimal.valueOf(2.32)); + } +} \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerTest.java b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerTest.java new file mode 100644 index 0000000000..06c3f740c2 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerTest.java @@ -0,0 +1,35 @@ +package org.baeldung.converter.controller; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.hamcrest.CoreMatchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class) +@AutoConfigureMockMvc +public class StringToEmployeeConverterControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void getStringToEmployeeTest() throws Exception { + mockMvc.perform(get("/string-to-employee?employee=1,2000")) + .andDo(print()) + .andExpect(jsonPath("$.id", is(1))) + .andExpect(jsonPath("$.salary", is(2000.0))) + .andExpect(status().isOk()); + } +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java similarity index 93% rename from spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java rename to spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java index 2146fc09bc..f06c144908 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java @@ -1,5 +1,8 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; +import org.baeldung.demo.boottest.Employee; +import org.baeldung.demo.boottest.EmployeeRestController; +import org.baeldung.demo.boottest.EmployeeService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java similarity index 94% rename from spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java rename to spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java index ebde0e243a..221beda900 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java @@ -1,5 +1,7 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; +import org.baeldung.demo.boottest.Employee; +import org.baeldung.demo.boottest.EmployeeRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java similarity index 94% rename from spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java rename to spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java index 9e5613ab10..e6f2203476 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java @@ -1,6 +1,8 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; -import org.baeldung.boot.DemoApplication; +import org.baeldung.demo.DemoApplication; +import org.baeldung.demo.boottest.Employee; +import org.baeldung.demo.boottest.EmployeeRepository; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java similarity index 94% rename from spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java rename to spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java index 9837b02df6..58ef3d4081 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java @@ -1,5 +1,9 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; +import org.baeldung.demo.boottest.Employee; +import org.baeldung.demo.boottest.EmployeeRepository; +import org.baeldung.demo.boottest.EmployeeService; +import org.baeldung.demo.boottest.EmployeeServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java similarity index 91% rename from spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java rename to spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java index 36d07164b2..7e04f47696 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.boottest; +package org.baeldung.demo.boottest; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java b/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java new file mode 100644 index 0000000000..595ad6ce0d --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java @@ -0,0 +1,53 @@ +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(); + EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("CLIENT_A") + .addScript("classpath:dsrouting-db.sql") + .build(); + return embeddedDb; + } + + private DataSource clientBDatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("CLIENT_B") + .addScript("classpath:dsrouting-db.sql") + .build(); + return embeddedDb; + } +} diff --git a/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTests.java b/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTests.java new file mode 100644 index 0000000000..88a142fcde --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTests.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 DataSourceRoutingTests { + + @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-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java index ffd5bf55d6..a51e3a6884 100644 --- a/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java @@ -1,5 +1,7 @@ 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/dsrouting-db.sql b/spring-boot/src/test/resources/dsrouting-db.sql new file mode 100644 index 0000000000..c9ca52907a --- /dev/null +++ b/spring-boot/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-cloud/pom.xml b/spring-cloud/pom.xml index 44e72535f8..fd023a5ea5 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,7 +15,9 @@ spring-cloud-ribbon-client spring-cloud-rest spring-cloud-zookeeper - spring-cloud-gateway + spring-cloud-gateway + spring-cloud-stream + spring-cloud-connectors-heroku pom @@ -37,6 +39,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-connectors-heroku/pom.xml b/spring-cloud/spring-cloud-connectors-heroku/pom.xml new file mode 100644 index 0000000000..ba3f0ef28f --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + + + spring-boot-starter-parent + org.springframework.boot + 1.4.4.RELEASE + + + + com.baeldung.spring.cloud + spring-cloud-connectors-heroku + 1.0.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-cloud-connectors + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-actuator + + + + org.postgresql + postgresql + 9.4-1201-jdbc4 + + + + com.h2database + h2 + runtime + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud-dependencies.version} + pom + import + + + + + + Brixton.SR7 + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.0 + + 1.8 + 1.8 + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/ConnectorsHerokuApplication.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/ConnectorsHerokuApplication.java new file mode 100644 index 0000000000..63246e89cc --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/ConnectorsHerokuApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.connectors.heroku; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ConnectorsHerokuApplication { + + public static void main(String[] args) { + SpringApplication.run(ConnectorsHerokuApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/Product.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/Product.java new file mode 100644 index 0000000000..40e8809fc5 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/Product.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.cloud.connectors.heroku.product; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Product { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long productId; + private String sku; + + public Long getProductId() { + return productId; + } + + public void setProductId(Long productId) { + this.productId = productId; + } + + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java new file mode 100644 index 0000000000..51cf4412bf --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.cloud.connectors.heroku.product; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/products") +public class ProductController { + + private final ProductService productService; + + @Autowired + public ProductController(ProductService productService) { + this.productService = productService; + } + + @GetMapping("/{productId}") + public Product findProduct(@PathVariable Long productId) { + return productService.findProductById(productId); + } + + @PostMapping + public Product createProduct(@RequestBody Product product) { + return productService.createProduct(product); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductRepository.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductRepository.java new file mode 100644 index 0000000000..508e1d048b --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.spring.cloud.connectors.heroku.product; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ProductRepository extends JpaRepository{ +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java new file mode 100644 index 0000000000..f25b4ecf7b --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.cloud.connectors.heroku.product; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +public class ProductService { + private final ProductRepository productRepository; + + @Autowired + public ProductService(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public Product findProductById(Long productId) { + return productRepository.findOne(productId); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Product createProduct(Product product) { + Product newProduct = new Product(); + newProduct.setSku(product.getSku()); + return productRepository.save(newProduct); + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/resources/application.properties b/spring-cloud/spring-cloud-connectors-heroku/src/main/resources/application.properties new file mode 100644 index 0000000000..d2f1c89dc5 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.datasource.driverClassName=org.postgresql.Driver +spring.datasource.maxActive=10 +spring.datasource.maxIdle=5 +spring.datasource.minIdle=2 +spring.datasource.initialSize=5 +spring.datasource.removeAbandoned=true + +spring.jpa.hibernate.ddl-auto=update \ No newline at end of file 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/java/com/baeldung/dependencyinjectiontypes/ArticleFormatter.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/ArticleFormatter.java new file mode 100644 index 0000000000..069e9df084 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/ArticleFormatter.java @@ -0,0 +1,16 @@ +package com.baeldung.dependencyinjectiontypes; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class ArticleFormatter { + + @SuppressWarnings("resource") + public static void main(String[] args) { + ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml"); + ArticleWithSetterInjection article = (ArticleWithSetterInjection) context.getBean("articleWithSetterInjectionBean"); + String formattedArticle = article.format("This is a text !"); + + System.out.print(formattedArticle); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/ArticleWithConstructorInjection.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/ArticleWithConstructorInjection.java new file mode 100644 index 0000000000..776e9f4040 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/ArticleWithConstructorInjection.java @@ -0,0 +1,17 @@ +package com.baeldung.dependencyinjectiontypes; + +import org.springframework.beans.factory.annotation.Autowired; + +public class ArticleWithConstructorInjection { + + private TextFormatter formatter; + + @Autowired + public ArticleWithConstructorInjection(TextFormatter formatter) { + this.formatter = formatter; + } + + public String format(String text) { + return formatter.format(text); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/ArticleWithSetterInjection.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/ArticleWithSetterInjection.java new file mode 100644 index 0000000000..931c6ea276 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/ArticleWithSetterInjection.java @@ -0,0 +1,21 @@ +package com.baeldung.dependencyinjectiontypes; + +import org.springframework.beans.factory.annotation.Autowired; + +public class ArticleWithSetterInjection { + + private TextFormatter formatter; + + public ArticleWithSetterInjection(TextFormatter formatter) { + this.formatter = formatter; + } + + @Autowired + public void setTextFormatter(TextFormatter formatter) { + this.formatter = formatter; + } + + public String format(String text) { + return formatter.format(text); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/TextFormatter.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/TextFormatter.java new file mode 100644 index 0000000000..204436c9bd --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/TextFormatter.java @@ -0,0 +1,8 @@ +package com.baeldung.dependencyinjectiontypes; + +public class TextFormatter { + + public String format(String text) { + return text.toUpperCase(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/IService.java b/spring-core/src/main/java/com/baeldung/di/spring/IService.java new file mode 100644 index 0000000000..478eea0657 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/IService.java @@ -0,0 +1,5 @@ +package com.baeldung.di.spring; + +public interface IService { + public String serve(); +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/IndexApp.java b/spring-core/src/main/java/com/baeldung/di/spring/IndexApp.java new file mode 100644 index 0000000000..a45970d6b2 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/IndexApp.java @@ -0,0 +1,19 @@ +package com.baeldung.di.spring; + +public class IndexApp { + + private IService service; + + public String getServiceValue() { + return service.serve(); + } + + public IService getService() { + return service; + } + + public void setService(IService service) { + this.service = service; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/IndexService.java b/spring-core/src/main/java/com/baeldung/di/spring/IndexService.java new file mode 100644 index 0000000000..ad241f5200 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/IndexService.java @@ -0,0 +1,10 @@ +package com.baeldung.di.spring; + +public class IndexService implements IService { + + @Override + public String serve() { + return "Hello World"; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/InstanceServiceFactory.java b/spring-core/src/main/java/com/baeldung/di/spring/InstanceServiceFactory.java new file mode 100644 index 0000000000..f083504e8f --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/InstanceServiceFactory.java @@ -0,0 +1,14 @@ +package com.baeldung.di.spring; + +public class InstanceServiceFactory { + public IService getService(int number) { + switch (number) { + case 1: + return new MessageService("Foo"); + case 0: + return new IndexService(); + default: + throw new IllegalArgumentException("Unknown parameter " + number); + } + } +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/MessageApp.java b/spring-core/src/main/java/com/baeldung/di/spring/MessageApp.java new file mode 100644 index 0000000000..1bf6c20b28 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/MessageApp.java @@ -0,0 +1,14 @@ +package com.baeldung.di.spring; + +public class MessageApp { + + private IService iService; + + public MessageApp(IService iService) { + this.iService = iService; + } + + public String getServiceValue() { + return iService.serve(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/MessageService.java b/spring-core/src/main/java/com/baeldung/di/spring/MessageService.java new file mode 100644 index 0000000000..9b6efaab2a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/MessageService.java @@ -0,0 +1,16 @@ +package com.baeldung.di.spring; + +public class MessageService implements IService { + + private String message; + + public MessageService(String message) { + this.message = message; + } + + @Override + public String serve() { + return message; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/StaticServiceFactory.java b/spring-core/src/main/java/com/baeldung/di/spring/StaticServiceFactory.java new file mode 100644 index 0000000000..bd70898faf --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/StaticServiceFactory.java @@ -0,0 +1,14 @@ +package com.baeldung.di.spring; + +public class StaticServiceFactory { + public static IService getService(int number) { + switch (number) { + case 1: + return new MessageService("Foo"); + case 0: + return new IndexService(); + default: + throw new IllegalArgumentException("Unknown parameter " + number); + } + } +} diff --git a/spring-core/src/main/resources/com.baeldung.di.spring.properties b/spring-core/src/main/resources/com.baeldung.di.spring.properties new file mode 100644 index 0000000000..8b8b5b85c2 --- /dev/null +++ b/spring-core/src/main/resources/com.baeldung.di.spring.properties @@ -0,0 +1 @@ +message.value=Hello World \ No newline at end of file diff --git a/spring-core/src/main/resources/com.baeldung.di.spring.xml b/spring-core/src/main/resources/com.baeldung.di.spring.xml new file mode 100644 index 0000000000..e0c5d22abb --- /dev/null +++ b/spring-core/src/main/resources/com.baeldung.di.spring.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/main/resources/dependencyinjectiontypes-context.xml b/spring-core/src/main/resources/dependencyinjectiontypes-context.xml new file mode 100644 index 0000000000..bd6b3c408d --- /dev/null +++ b/spring-core/src/main/resources/dependencyinjectiontypes-context.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java b/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java new file mode 100644 index 0000000000..57c1927e58 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java @@ -0,0 +1,35 @@ +package com.baeldung.dependencyinjectiontypes; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class DependencyInjectionTest { + + @Test + public void givenAutowiredAnnotation_WhenSetOnSetter_ThenDependencyValid() { + + ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml"); + ArticleWithSetterInjection article = (ArticleWithSetterInjection) context.getBean("articleWithSetterInjectionBean"); + + String originalText = "This is a text !"; + String formattedArticle = article.format(originalText); + + assertTrue(originalText.toUpperCase().equals(formattedArticle)); + } + + @Test + public void givenAutowiredAnnotation_WhenSetOnConstructor_ThenDependencyValid() { + + ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml"); + ArticleWithConstructorInjection article = (ArticleWithConstructorInjection) context.getBean("articleWithConstructorInjectionBean"); + + String originalText = "This is a text !"; + String formattedArticle = article.format(originalText); + + assertTrue(originalText.toUpperCase().equals(formattedArticle)); + } + +} 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 new file mode 100644 index 0000000000..1660b99726 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java @@ -0,0 +1,31 @@ +package com.baeldung.di.spring; + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class BeanInjectionTest { + + private ApplicationContext applicationContext; + + @Before + public void setUp() throws Exception { + applicationContext = new ClassPathXmlApplicationContext("com.baeldung.di.spring.xml"); + } + + @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-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java b/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java new file mode 100644 index 0000000000..a128d8848c --- /dev/null +++ b/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java @@ -0,0 +1,81 @@ +package org.baeldung.spring; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate3.HibernateTransactionManager; +import org.springframework.orm.hibernate3.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "org.baeldung.persistence.dao", "org.baeldung.persistence.service" }) +public class PersistenceConfigHibernate3 { + + @Autowired + private Environment env; + + public PersistenceConfigHibernate3() { + super(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + Resource config = new ClassPathResource("exceptionDemo.cfg.xml"); + sessionFactory.setDataSource(dataSource()); + sessionFactory.setConfigLocation(config); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource dataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + @Autowired + public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) { + final HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(sessionFactory); + + return txManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + +} diff --git a/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java b/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java new file mode 100644 index 0000000000..d53c4445a8 --- /dev/null +++ b/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java @@ -0,0 +1,43 @@ +package org.baeldung.persistence.service; + +import java.util.List; + +import org.baeldung.persistence.model.Event; +import org.baeldung.spring.PersistenceConfigHibernate3; +import org.hamcrest.core.IsInstanceOf; +import org.hibernate.HibernateException; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfigHibernate3.class }, loader = AnnotationConfigContextLoader.class) +public class HibernateExceptionScen1MainIntegrationTest { + + @Autowired + EventService service; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Event("from LocalSessionFactoryBean")); + } + + @Test + @Ignore + public final void whenNoTransBoundToSession_thenException() { + expectedEx.expectCause(IsInstanceOf.instanceOf(HibernateException.class)); + expectedEx.expectMessage("No Hibernate Session bound to thread, " + + "and configuration does not allow creation " + + "of non-transactional one here"); + service.create(new Event("from LocalSessionFactoryBean")); + } +} diff --git a/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java b/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java new file mode 100644 index 0000000000..84cafe0536 --- /dev/null +++ b/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java @@ -0,0 +1,45 @@ +package org.baeldung.persistence.service; + +import java.util.List; + +import org.baeldung.persistence.model.Event; +import org.baeldung.spring.PersistenceConfig; +import org.hamcrest.core.IsInstanceOf; +import org.hibernate.HibernateException; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class HibernateExceptionScen2MainIntegrationTest { + + @Autowired + EventService service; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Event("from AnnotationSessionFactoryBean")); + } + + @Test + @Ignore + public final void whenNoTransBoundToSession_thenException() { + expectedEx.expectCause(IsInstanceOf.instanceOf(HibernateException.class)); + expectedEx.expectMessage("No Hibernate Session bound to thread, " + + "and configuration does not allow creation " + + "of non-transactional one here"); + service.create(new Event("from AnnotationSessionFactoryBean")); + } + +} diff --git a/spring-jms/README.md b/spring-jms/README.md index 9093937f44..b942cc72a0 100644 --- a/spring-jms/README.md +++ b/spring-jms/README.md @@ -1,2 +1,2 @@ -###Relevant Articles: +### Relevant Articles: - [An Introduction To Spring JMS](http://www.baeldung.com/spring-jms) 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/data.sql b/spring-jpa/src/main/resources/data.sql new file mode 100644 index 0000000000..f36e034ce1 --- /dev/null +++ b/spring-jpa/src/main/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-jpa/src/main/resources/schema.sql b/spring-jpa/src/main/resources/schema.sql new file mode 100644 index 0000000000..15d7788cd7 --- /dev/null +++ b/spring-jpa/src/main/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-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-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 new file mode 100644 index 0000000000..901d9a51ee --- /dev/null +++ b/spring-rest-shell/README.md @@ -0,0 +1,5 @@ +## Spring REST Shell Project + +### Relevant Articles + +- [Spring REST Shell](http://www.baeldung.com/spring-rest-shell) \ No newline at end of file diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml new file mode 100644 index 0000000000..fe255b397f --- /dev/null +++ b/spring-rest-shell/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + com.baeldung + spring-rest-shell + 0.0.1-SNAPSHOT + jar + + spring-rest-shell + A simple project to demonstrate Spring REST Shell features. + + + org.springframework.boot + spring-boot-starter-parent + 1.5.8.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-data-rest + + + + + com.h2database + h2 + runtime + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-rest-shell/src/main/java/com/baeldung/Application.java b/spring-rest-shell/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..37dbe7dab8 --- /dev/null +++ b/spring-rest-shell/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java b/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java new file mode 100644 index 0000000000..6a55517f9f --- /dev/null +++ b/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java @@ -0,0 +1,40 @@ +package com.baeldung.acticle; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public final class Article { + + @Id + @GeneratedValue + private Long id; + private String title; + private String content; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + +} diff --git a/spring-rest-shell/src/main/java/com/baeldung/acticle/ArticleRepository.java b/spring-rest-shell/src/main/java/com/baeldung/acticle/ArticleRepository.java new file mode 100644 index 0000000000..83daf819f0 --- /dev/null +++ b/spring-rest-shell/src/main/java/com/baeldung/acticle/ArticleRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.acticle; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import java.util.Optional; + +@RepositoryRestResource( + path = "articles", + collectionResourceRel = "articles", + itemResourceRel = "article" +) +public interface ArticleRepository extends CrudRepository { + + Optional
findByTitle(@Param("title") String title); + +} diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index f662b736ad..f3fdd78ff4 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -230,7 +230,7 @@ **/JdbcTest.java **/*LiveTest.java - true + 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/SpringAclTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclTest.java new file mode 100644 index 0000000000..fd9069d9bc --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclTest.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 SpringAclTest 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/spring-vertx/pom.xml b/spring-vertx/pom.xml index 2ab506f667..2b26d939a5 100644 --- a/spring-vertx/pom.xml +++ b/spring-vertx/pom.xml @@ -80,7 +80,7 @@ **/JdbcTest.java **/*LiveTest.java - true + 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 78% rename from junit5/README.md rename to testing-modules/junit-5/README.md index a3bb8fc1be..20ecb1eeab 100644 --- a/junit5/README.md +++ b/testing-modules/junit-5/README.md @@ -6,4 +6,5 @@ - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [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 86% rename from junit5/pom.xml rename to testing-modules/junit-5/pom.xml index b820d7b7bc..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 @@ -29,6 +30,7 @@ 3.6.0 2.19.1 4.12 + 5.0.1.RELEASE @@ -111,7 +113,18 @@ ${junit4.version} test + + org.springframework + spring-test + ${spring.version} + test + + + org.springframework + spring-context + ${spring.version} + - \ No newline at end of file + diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java new file mode 100644 index 0000000000..f43269f646 --- /dev/null +++ b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java @@ -0,0 +1,9 @@ +package com.baeldung.junit5; + +public class Greetings { + + public static String sayHello() { + return "Hello"; + } + +} 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/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java new file mode 100644 index 0000000000..efde4e7404 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.baeldung.junit5.Greetings; + +@RunWith(JUnitPlatform.class) +public class GreetingsTest { + + @Test + void whenCallingSayHello_thenReturnHello() { + 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/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java new file mode 100644 index 0000000000..3b89508c88 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java @@ -0,0 +1,21 @@ +package com.baeldung.junit5.spring; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.junit5.Greetings; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { SpringTestConfiguration.class }) +public class GreetingsSpringTest { + + @Test + void whenCallingSayHello_thenReturnHello() { + assertTrue("Hello".equals(Greetings.sayHello())); + } + +} \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java new file mode 100644 index 0000000000..7651b2bd41 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java @@ -0,0 +1,8 @@ +package com.baeldung.junit5.spring; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringTestConfiguration { + +} 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/spring-hibernate5/src/test/resources/.gitignore b/testing-modules/mockito/.gitignore similarity index 100% rename from spring-hibernate5/src/test/resources/.gitignore rename to testing-modules/mockito/.gitignore diff --git a/mockito/README.md b/testing-modules/mockito/README.md similarity index 100% rename from mockito/README.md rename to testing-modules/mockito/README.md diff --git a/mockito/pom.xml b/testing-modules/mockito/pom.xml similarity index 98% 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/spring-data-redis/src/main/resources/logback.xml b/testing-modules/mockito/src/main/resources/logback.xml similarity index 100% rename from spring-data-redis/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/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 100% rename from mockito/src/test/java/org/baeldung/mockito/MyList.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MyList.java 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 95% 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 97% 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/spring-hibernate3/src/main/resources/logback.xml b/testing-modules/rest-assured/src/test/resources/logback.xml similarity index 100% rename from spring-hibernate3/src/main/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 100% rename from rest-testing/README.md rename to testing-modules/rest-testing/README.md diff --git a/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml similarity index 91% rename from rest-testing/pom.xml rename to testing-modules/rest-testing/pom.xml index b99dfac571..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 + ../ @@ -88,6 +89,19 @@ ${jbehave.version} test + + + com.intuit.karate + karate-apache + ${karate.version} + + + + com.intuit.karate + karate-junit4 + ${karate.version} + test + @@ -150,6 +164,7 @@ 2.9.0 1.2.5 2.4.1 + 0.6.1 4.4.5 4.5.2 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/Feature/cucumber.feature b/testing-modules/rest-testing/src/main/resources/karate/cucumber.feature similarity index 100% rename from rest-testing/src/main/resources/Feature/cucumber.feature rename to testing-modules/rest-testing/src/main/resources/karate/cucumber.feature diff --git a/spring-hibernate5/src/main/resources/logback.xml b/testing-modules/rest-testing/src/main/resources/logback.xml similarity index 100% rename from spring-hibernate5/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/testing-modules/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 new file mode 100644 index 0000000000..f942721504 --- /dev/null +++ b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.rest.karate; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.intuit.karate.junit4.Karate; +import cucumber.api.CucumberOptions; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.runner.RunWith; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; + +@RunWith(Karate.class) +@CucumberOptions(features = "classpath:karate") +public class KarateUnitTest { + + private static final WireMockServer wireMockServer = new WireMockServer(); + + @BeforeClass + public static void setUp() throws Exception { + wireMockServer.start(); + + configureFor("localhost", 8080); + stubFor(get(urlEqualTo("/user/get")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{ \"id\": \"1234\", name: \"John Smith\" }"))); + stubFor(post(urlEqualTo("/user/create")) + .withHeader("content-type", equalTo("application/json")) + .withRequestBody(containing("id")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{ \"id\": \"1234\", name: \"John Smith\" }"))); + + } + + @AfterClass + public static void tearDown() throws Exception { + wireMockServer.stop(); + } + +} 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/testing-modules/rest-testing/src/test/resources/karate/user.feature b/testing-modules/rest-testing/src/test/resources/karate/user.feature new file mode 100644 index 0000000000..d9f0f12a9c --- /dev/null +++ b/testing-modules/rest-testing/src/test/resources/karate/user.feature @@ -0,0 +1,42 @@ +Feature: Testing a REST API with Karate + +Scenario: Testing valid GET endpoint + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + +Scenario: Testing an invalid GET endpoint - 404 + Given url 'http://localhost:8080/user/wrong' + When method GET + Then status 404 + +Scenario: Testing the exact response of a GET endpoint + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + And match $ == {id:"1234",name:"John Smith"} + +Scenario: Testing the exact response field value of a GET endpoint + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + And match $.id == "1234" + +Scenario: Testing that GET response contains specific field + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + And match $ contains {id:"1234"} + +Scenario: Test GET response using markers + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + And match $ == {id:"#notnull",name:"John Smith"} + +Scenario: Testing a POST endpoint with request body + Given url 'http://localhost:8080/user/create' + And request { id: '1234' , name: 'John Smith'} + When method POST + Then status 200 + And match $ contains {id:"#notnull"} 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 5b695ca900..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 + ../ @@ -27,7 +28,6 @@ **/*LiveTest.java - false 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 100% rename from testing/README.md rename to testing-modules/testing/README.md 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 95% 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/vavr/pom.xml b/vavr/pom.xml index 878430611b..f9fed7d4fc 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -97,7 +97,7 @@ **/JdbcTest.java **/*LiveTest.java - true + 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