From 6a9e13cc03901909a3c35fb26711685d3b97bd7d Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Fri, 4 Aug 2017 19:52:00 +0100 Subject: [PATCH 01/67] BAEL-892: Example of Sealed Classes (#2373) --- .../main/kotlin/com/baeldung/kotlin/Sealed.kt | 19 +++++ .../kotlin/com/baeldung/kotlin/SealedTest.kt | 84 +++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt create mode 100644 kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt new file mode 100644 index 0000000000..96e54716b3 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt @@ -0,0 +1,19 @@ +package com.baeldung.kotlin + +sealed class Result { + abstract fun map(func: (S) -> R) : Result + abstract fun mapFailure(func: (F) -> R) : Result + abstract fun get() : S? +} + +data class Success(val success: S) : Result() { + override fun map(func: (S) -> R) : Result = Success(func(success)) + override fun mapFailure(func: (F) -> R): Result = Success(success) + override fun get(): S? = success +} + +data class Failure(val failure: F) : Result() { + override fun map(func: (S) -> R) : Result = Failure(failure) + override fun mapFailure(func: (F) -> R): Result = Failure(func(failure)) + override fun get(): S? = null +} diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt new file mode 100644 index 0000000000..8c7509f653 --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt @@ -0,0 +1,84 @@ +package com.baeldung.kotlin + +import org.junit.Assert +import org.junit.Test + +class SealedTest { + fun divide(a: Int, b: Int) : Result = when (b) { + 0 -> Failure("Division by zero") + else -> Success(a.toFloat() / b) + } + + @Test + fun testSuccess() { + val result = divide(10, 5) + Assert.assertEquals(Success(2.0f), result) + } + + @Test + fun testError() { + val result = divide(10, 0) + Assert.assertEquals(Failure("Division by zero"), result) + } + + @Test + fun testMatchOnSuccess() { + val result = divide(10, 5) + when (result) { + is Success -> { + // Expected + } + is Failure -> Assert.fail("Expected Success") + } + } + + @Test + fun testMatchOnError() { + val result = divide(10, 0) + when (result) { + is Failure -> { + // Expected + } + } + } + + @Test + fun testGetSuccess() { + val result = divide(10, 5) + Assert.assertEquals(2.0f, result.get()) + } + + @Test + fun testGetError() { + val result = divide(10, 0) + Assert.assertNull(result.get()) + } + + @Test + fun testMapOnSuccess() { + val result = divide(10, 5) + .map { "Result: $it" } + Assert.assertEquals(Success("Result: 2.0"), result) + } + + @Test + fun testMapOnError() { + val result = divide(10, 0) + .map { "Result: $it" } + Assert.assertEquals(Failure("Division by zero"), result) + } + + @Test + fun testMapFailureOnSuccess() { + val result = divide(10, 5) + .mapFailure { "Failure: $it" } + Assert.assertEquals(Success(2.0f), result) + } + + @Test + fun testMapFailureOnError() { + val result = divide(10, 0) + .mapFailure { "Failure: $it" } + Assert.assertEquals(Failure("Failure: Division by zero"), result) + } +} From 891b4eb2484d69f34b620509ca7dbbbad803f7fb Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 5 Aug 2017 14:11:45 +0200 Subject: [PATCH 02/67] Remove jooq module (#2375) * Remove jooq module * Refactor --- jooq/README.md | 3 - jooq/pom.xml | 25 ------ .../test/java/com/baeldung/jool/JOOLTest.java | 90 +++++++++---------- pom.xml | 1 - 4 files changed, 45 insertions(+), 74 deletions(-) delete mode 100644 jooq/README.md delete mode 100644 jooq/pom.xml rename jooq/src/test/java/com/baeldung/JOOLUnitTest.java => libraries/src/test/java/com/baeldung/jool/JOOLTest.java (64%) diff --git a/jooq/README.md b/jooq/README.md deleted file mode 100644 index 2f09cab46b..0000000000 --- a/jooq/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Introduction to jOOL](http://www.baeldung.com/jool) diff --git a/jooq/pom.xml b/jooq/pom.xml deleted file mode 100644 index 667640d085..0000000000 --- a/jooq/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - - 4.0.0 - - jooq - - - - org.jooq - jool - ${jool.version} - - - - - 0.9.12 - - - \ No newline at end of file diff --git a/jooq/src/test/java/com/baeldung/JOOLUnitTest.java b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java similarity index 64% rename from jooq/src/test/java/com/baeldung/JOOLUnitTest.java rename to libraries/src/test/java/com/baeldung/jool/JOOLTest.java index 17873db50a..ba20e153fd 100644 --- a/jooq/src/test/java/com/baeldung/JOOLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.jool; import org.jooq.lambda.Seq; import org.jooq.lambda.Unchecked; @@ -13,6 +13,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -20,7 +21,7 @@ import static junit.framework.Assert.assertTrue; import static junit.framework.TestCase.assertEquals; import static org.jooq.lambda.tuple.Tuple.tuple; -public class JOOLUnitTest { +public class JOOLTest { @Test public void givenSeq_whenCheckContains_shouldReturnTrue() { List concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList(); @@ -54,58 +55,58 @@ public class JOOLUnitTest { @Test public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() { assertEquals( - Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2)) + Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2)) ); assertEquals( - Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) + Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) ); assertEquals( - Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) + Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) ); assertEquals( - Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), - Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) + Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), + Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) ); } @Test public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() { assertEquals( - Seq.of(1, 2, 3).cycle().limit(9).toList(), - Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) + Seq.of(1, 2, 3).cycle().limit(9).toList(), + Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) ); assertEquals( - Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) + Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), + tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) ); assertEquals( - Seq.of(1, 2, 3, 4).intersperse(0).toList(), - Arrays.asList(1, 0, 2, 0, 3, 0, 4) + Seq.of(1, 2, 3, 4).intersperse(0).toList(), + Arrays.asList(1, 0, 2, 0, 3, 0, 4) ); assertEquals( - Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), - 5 + Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), + 5 ); assertEquals( - Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) + Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), + tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) ); assertEquals( - Seq.of(1, 2, 3, 4).reverse().toList(), - Arrays.asList(4, 3, 2, 1) + Seq.of(1, 2, 3, 4).reverse().toList(), + Arrays.asList(4, 3, 2, 1) ); } @@ -117,20 +118,20 @@ public class JOOLUnitTest { expectedAfterGroupBy.put(0, Arrays.asList(2, 4)); assertEquals( - Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), - expectedAfterGroupBy + Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), + expectedAfterGroupBy ); assertEquals( - Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), - "!abc" + Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), + "!abc" ); assertEquals( - Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), - "abc!" + Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), + "abc!" ); } @@ -138,13 +139,13 @@ public class JOOLUnitTest { public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() { assertEquals( - Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), - Arrays.asList(3, 4, 5) + Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), + Arrays.asList(3, 4, 5) ); assertEquals( - Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), - Arrays.asList(3, 4, 5) + Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), + Arrays.asList(3, 4, 5) ); } @@ -152,19 +153,19 @@ public class JOOLUnitTest { public void givenSeq_whenZip_shouldHaveZippedSeq() { assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), - Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) + Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), + Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) ); assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), - Arrays.asList("1:a", "2:b", "3:c") + Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), + Arrays.asList("1:a", "2:b", "3:c") ); assertEquals( - Seq.of("a", "b", "c").zipWithIndex().toList(), - Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) + Seq.of("a", "b", "c").zipWithIndex().toList(), + Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) ); } @@ -187,8 +188,8 @@ public class JOOLUnitTest { //then assertEquals( - collect, - Arrays.asList(1, 1, 1) + collect, + Arrays.asList(1, 1, 1) ); } @@ -197,13 +198,13 @@ public class JOOLUnitTest { public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() { //when List collect = Stream.of("a", "b", "c") - .map(Unchecked.function(elem -> methodThatThrowsChecked(elem))) - .collect(Collectors.toList()); + .map(Unchecked.function(this::methodThatThrowsChecked)) + .collect(Collectors.toList()); //then assertEquals( - collect, - Arrays.asList(1, 1, 1) + collect, + Arrays.asList(1, 1, 1) ); } @@ -236,5 +237,4 @@ public class JOOLUnitTest { Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer")) ); } - } diff --git a/pom.xml b/pom.xml index 3feba96d5a..82dccf832d 100644 --- a/pom.xml +++ b/pom.xml @@ -83,7 +83,6 @@ jjwt - jooq jpa-storedprocedure jsf json-path From 7114e3965bb4755d8d561a6775bce0418b3401f2 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sat, 5 Aug 2017 14:48:10 +0200 Subject: [PATCH 03/67] fix spring config (#2374) * fix spring config * fix spring config --- spring-mvc-email/pom.xml | 11 ++++---- .../java/com/baeldung/spring/Application.java | 3 ++- spring-security-mvc-ldap/pom.xml | 2 +- .../org/baeldung/SampleLDAPApplication.java | 22 +++++++++------ spring-security-rest-custom/pom.xml | 27 +++++-------------- 5 files changed, 30 insertions(+), 35 deletions(-) diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml index c40abdb4bf..9228054878 100644 --- a/spring-mvc-email/pom.xml +++ b/spring-mvc-email/pom.xml @@ -21,16 +21,17 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-tomcat + provided + org.springframework.boot spring-boot-starter-mail - + - - org.apache.tomcat.embed - tomcat-embed-jasper - javax.servlet jstl diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java index f146ee1d04..bc5d6b3151 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java @@ -2,10 +2,11 @@ package com.baeldung.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); } diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index f2b6b766eb..e6452ea70b 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -57,7 +57,7 @@ - 1.5.7 + 1.5.5 diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java index 4bcb255046..5936aa30ef 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java @@ -1,8 +1,9 @@ package org.baeldung; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -11,17 +12,22 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter * class to run up a Jetty Server (on http://localhost:8080) * */ -@EnableAutoConfiguration -@ComponentScan("org.baeldung") -public class SampleLDAPApplication extends WebMvcConfigurerAdapter { +@SpringBootApplication +public class SampleLDAPApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SampleLDAPApplication.class, args); } - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/login").setViewName("login"); + @Bean + public WebMvcConfigurerAdapter adapter() { + return new WebMvcConfigurerAdapter() { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login") + .setViewName("login"); + } + }; } } \ No newline at end of file diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index c329bd1cb8..77a58a56d8 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -33,12 +33,6 @@ org.springframework spring-core - - - commons-logging - commons-logging - - org.springframework @@ -79,6 +73,12 @@ spring-oxm + + commons-logging + commons-logging + ${commons-logging.version} + + @@ -105,24 +105,11 @@ org.apache.httpcomponents httpcore - ${httpcore.version} - - - commons-logging - commons-logging - - org.apache.httpcomponents httpclient - - - commons-logging - commons-logging - - @@ -213,7 +200,7 @@ 19.0 3.5 - + 1.2 4.4.5 4.5.2 From f913859c6f9434cbd89748055cb8505fa6ca4846 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 5 Aug 2017 16:13:22 +0300 Subject: [PATCH 04/67] package fixes --- .../java/com/baeldung/hashcode/application/Application.java | 5 +++-- .../src/main/java/com/baeldung/hashcode/entities/User.java | 2 +- .../com/baeldung/hashcode/application/ApplicationTest.java | 2 +- .../test/java/com/baeldung/hashcode/entities/UserTest.java | 4 ++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java index 08c670c82f..8e6125045e 100644 --- a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java +++ b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java @@ -1,9 +1,10 @@ -package com.baeldung.application; +package com.baeldung.hashcode.application; -import com.baeldung.entities.User; import java.util.HashMap; import java.util.Map; +import com.baeldung.hashcode.entities.User; + public class Application { public static void main(String[] args) { diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java index a976233562..c1c5a82d31 100644 --- a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -1,4 +1,4 @@ -package com.baeldung.entities; +package com.baeldung.hashcode.entities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java index dcd853f451..70abd69fad 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.application; +package com.baeldung.hashcode.application; import org.junit.After; import org.junit.Before; diff --git a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java index 01f6085d7e..e356b4beef 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java @@ -1,4 +1,4 @@ -package com.baeldung.entities; +package com.baeldung.hashcode.entities; import org.junit.After; import org.junit.Assert; @@ -23,7 +23,7 @@ public class UserTest { } @Test - public void equals_EqualUserInstance_TrueAssertion(){ + public void equals_EqualUserInstance_TrueAssertion() { Assert.assertTrue(user.equals(comparisonUser)); } From 4d8f92e58753a71683e8d14d68784f86907601a9 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 5 Aug 2017 16:14:20 +0300 Subject: [PATCH 05/67] formatting cleanup --- .../cyclicbarrier/CyclicBarrierDemo.java | 12 ++--- .../diningphilosophers/Philosopher.java | 3 +- .../executorservice/ExecutorServiceDemo.java | 26 +++++------ .../concurrent/future/FutureDemo.java | 46 +++++++++---------- .../threadfactory/BaeldungThreadFactory.java | 26 +++++------ .../concurrent/threadfactory/Task.java | 10 ++-- .../filesystem/jndi/LookupFSJNDI.java | 13 +++--- .../com/baeldung/hashcode/entities/User.java | 11 +++-- .../baeldung/jmx/JMXTutorialMainlauncher.java | 1 - .../java/com/baeldung/socket/EchoClient.java | 3 +- .../com/baeldung/stream/InfiniteStreams.java | 1 - .../com/baeldung/string/StringHelper.java | 9 +--- .../baeldung/stringtokenizer/MyTokenizer.java | 6 +-- .../CustomTemporalAdjuster.java | 12 ++--- .../com/baeldung/transferqueue/Consumer.java | 1 - .../accumulator/LongAccumulatorUnitTest.java | 12 ++--- .../hashcode/application/ApplicationTest.java | 2 +- .../LambdaExceptionWrappersUnitTest.java | 1 - .../list/listoflist/ListOfListsUnitTest.java | 24 ++++------ .../CoreThreadPoolIntegrationTest.java | 1 - 20 files changed, 96 insertions(+), 124 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java index 977dae4fdb..758bdecd0c 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java @@ -15,14 +15,12 @@ public class CyclicBarrierDemo { private int NUM_PARTIAL_RESULTS; private int NUM_WORKERS; - private void runSimulation(int numWorkers, int numberOfPartialResults) { NUM_PARTIAL_RESULTS = numberOfPartialResults; NUM_WORKERS = numWorkers; cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread()); - System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " - + NUM_PARTIAL_RESULTS + " partial results each"); + System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " + NUM_PARTIAL_RESULTS + " partial results each"); for (int i = 0; i < NUM_WORKERS; i++) { Thread worker = new Thread(new NumberCruncherThread()); worker.setName("Thread " + i); @@ -38,8 +36,7 @@ public class CyclicBarrierDemo { List partialResult = new ArrayList<>(); for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) { Integer num = random.nextInt(10); - System.out.println(thisThreadName - + ": Crunching some numbers! Final result - " + num); + System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num); partialResult.add(num); } partialResults.add(partialResult); @@ -57,13 +54,12 @@ public class CyclicBarrierDemo { @Override public void run() { String thisThreadName = Thread.currentThread().getName(); - System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS - + " workers, having " + NUM_PARTIAL_RESULTS + " results each."); + System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each."); int sum = 0; for (List threadResult : partialResults) { System.out.print("Adding "); for (Integer partialResult : threadResult) { - System.out.print(partialResult+" "); + System.out.print(partialResult + " "); sum += partialResult; } System.out.println(); diff --git a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java index c5672706ad..4de420900a 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java +++ b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java @@ -15,7 +15,8 @@ public class Philosopher implements Runnable { Thread.sleep(((int) (Math.random() * 100))); } - @Override public void run() { + @Override + public void run() { try { while (true) { doAction(System.nanoTime() + ": Thinking"); // thinking diff --git a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java index ae2b279d9a..83a9fb6692 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java @@ -6,22 +6,22 @@ import java.util.concurrent.TimeUnit; public class ExecutorServiceDemo { - ExecutorService executor = Executors.newFixedThreadPool(10); + ExecutorService executor = Executors.newFixedThreadPool(10); - public void execute() { + public void execute() { - executor.submit(() -> { - new Task(); - }); + executor.submit(() -> { + new Task(); + }); - executor.shutdown(); - executor.shutdownNow(); - try { - executor.awaitTermination(20l, TimeUnit.NANOSECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } + executor.shutdown(); + executor.shutdownNow(); + try { + executor.awaitTermination(20l, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } - } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java index 7cb611be0f..4794d5cb61 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java @@ -9,36 +9,36 @@ import java.util.concurrent.TimeoutException; public class FutureDemo { - public String invoke() { + public String invoke() { - String str = null; + String str = null; - ExecutorService executorService = Executors.newFixedThreadPool(10); + ExecutorService executorService = Executors.newFixedThreadPool(10); - Future future = executorService.submit(() -> { - // Task - Thread.sleep(10000l); - return "Hellow world"; - }); + Future future = executorService.submit(() -> { + // Task + Thread.sleep(10000l); + return "Hellow world"; + }); - future.cancel(false); + future.cancel(false); - try { - future.get(20, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException e1) { - e1.printStackTrace(); - } + try { + future.get(20, TimeUnit.SECONDS); + } catch (InterruptedException | ExecutionException | TimeoutException e1) { + e1.printStackTrace(); + } - if (future.isDone() && !future.isCancelled()) { - try { - str = future.get(); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - } - } + if (future.isDone() && !future.isCancelled()) { + try { + str = future.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } - return str; + return str; - } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java index 8744027e40..f708804cae 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java @@ -4,20 +4,20 @@ import java.util.concurrent.ThreadFactory; public class BaeldungThreadFactory implements ThreadFactory { - private int threadId; - private String name; + private int threadId; + private String name; - public BaeldungThreadFactory(String name) { - threadId = 1; - this.name = name; - } + public BaeldungThreadFactory(String name) { + threadId = 1; + this.name = name; + } - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r, name + "-Thread_" + threadId); - System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); - threadId++; - return t; - } + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r, name + "-Thread_" + threadId); + System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); + threadId++; + return t; + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java index 04ba62d457..a69623c667 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java @@ -2,9 +2,9 @@ package com.baeldung.concurrent.threadfactory; public class Task implements Runnable { - @Override - public void run() { - // task details - } - + @Override + public void run() { + // task details + } + } diff --git a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java index 4afce56e39..7e6bb5d3b2 100644 --- a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java +++ b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java @@ -14,26 +14,25 @@ public class LookupFSJNDI { super(); init(); } - + private void init() throws NamingException { Hashtable env = new Hashtable(); - - env.put (Context.INITIAL_CONTEXT_FACTORY, - "com.sun.jndi.fscontext.RefFSContextFactory"); + + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); // URI to namespace (actual directory) env.put(Context.PROVIDER_URL, "file:./src/test/resources"); - + ctx = new InitialContext(env); } public InitialContext getCtx() { return ctx; } - + public File getFile(String fileName) { File file; try { - file = (File)getCtx().lookup(fileName); + file = (File) getCtx().lookup(fileName); } catch (NamingException e) { file = null; } diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java index c1c5a82d31..c46c3de65a 100644 --- a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -18,13 +18,16 @@ public class User { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null) return false; - if (this.getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; User user = (User) o; return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); } - + @Override public int hashCode() { int hash = 7; diff --git a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java index 220b9a8ec6..21044f82c4 100644 --- a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java +++ b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -10,7 +10,6 @@ public class JMXTutorialMainlauncher { private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); - public static void main(String[] args) { // TODO Auto-generated method stub diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java index cf5c253276..fa3901d5da 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -8,9 +8,8 @@ import java.net.*; public class EchoClient { - private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class); - + private Socket clientSocket; private PrintWriter out; private BufferedReader in; diff --git a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java index ae00fc7cb4..d79a7c3ecb 100644 --- a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java +++ b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java @@ -1,6 +1,5 @@ package com.baeldung.stream; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java/src/main/java/com/baeldung/string/StringHelper.java b/core-java/src/main/java/com/baeldung/string/StringHelper.java index dac0d1272e..a9cc71d36a 100644 --- a/core-java/src/main/java/com/baeldung/string/StringHelper.java +++ b/core-java/src/main/java/com/baeldung/string/StringHelper.java @@ -12,15 +12,10 @@ class StringHelper { } static String removeLastCharOptional(String s) { - return Optional.ofNullable(s) - .filter(str -> str.length() != 0) - .map(str -> str.substring(0, str.length() - 1)) - .orElse(s); + return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s); } static String removeLastCharRegexOptional(String s) { - return Optional.ofNullable(s) - .map(str -> str.replaceAll(".$", "")) - .orElse(s); + return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s); } } diff --git a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java index 130218acc2..21164a976c 100644 --- a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java +++ b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java @@ -25,11 +25,7 @@ public class MyTokenizer { } public List getTokensWithCollection(String str) { - return Collections - .list(new StringTokenizer(str, ",")) - .stream() - .map(token -> (String) token) - .collect(Collectors.toList()); + return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList()); } public List getTokensFromFile(String path, String delim) { diff --git a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java index bfb6681f7c..5631616ea8 100644 --- a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java +++ b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java @@ -11,12 +11,12 @@ public class CustomTemporalAdjuster implements TemporalAdjuster { @Override public Temporal adjustInto(Temporal temporal) { switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) { - case FRIDAY: - return temporal.plus(3, ChronoUnit.DAYS); - case SATURDAY: - return temporal.plus(2, ChronoUnit.DAYS); - default: - return temporal.plus(1, ChronoUnit.DAYS); + case FRIDAY: + return temporal.plus(3, ChronoUnit.DAYS); + case SATURDAY: + return temporal.plus(2, ChronoUnit.DAYS); + default: + return temporal.plus(1, ChronoUnit.DAYS); } } } diff --git a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java index 69d7ff2390..a5f70d9df5 100644 --- a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java +++ b/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java @@ -9,7 +9,6 @@ import java.util.concurrent.atomic.AtomicInteger; public class Consumer implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); - private final TransferQueue transferQueue; private final String name; private final int numberOfMessagesToConsume; diff --git a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java index 2f1abef64e..8cddf31245 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java @@ -15,28 +15,24 @@ public class LongAccumulatorUnitTest { @Test public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException { - //given + // given ExecutorService executorService = Executors.newFixedThreadPool(8); LongBinaryOperator sum = Long::sum; LongAccumulator accumulator = new LongAccumulator(sum, 0L); int numberOfThreads = 4; int numberOfIncrements = 100; - //when - Runnable accumulateAction = () -> IntStream - .rangeClosed(0, numberOfIncrements) - .forEach(accumulator::accumulate); + // when + Runnable accumulateAction = () -> IntStream.rangeClosed(0, numberOfIncrements).forEach(accumulator::accumulate); for (int i = 0; i < numberOfThreads; i++) { executorService.execute(accumulateAction); } - - //then + // then executorService.awaitTermination(500, TimeUnit.MILLISECONDS); executorService.shutdown(); assertEquals(accumulator.get(), 20200); - } } diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java index 70abd69fad..bf7a24347d 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -24,7 +24,7 @@ public class ApplicationTest { @Test public void main_NoInputState_TextPrintedToConsole() throws Exception { - Application.main(new String[]{}); + Application.main(new String[] {}); assertEquals("User found in the collection", outContent.toString()); } } \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java index 0fd6f7dfe8..fe10266043 100644 --- a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java @@ -15,7 +15,6 @@ public class LambdaExceptionWrappersUnitTest { private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class); - private List integers; @Before diff --git a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java index 7a23afa12f..5327e5f4f0 100644 --- a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java @@ -29,12 +29,9 @@ public class ListOfListsUnitTest { @Test public void givenListOfLists_thenCheckNames() { - assertEquals("Pen 1", ((Pen) listOfLists.get(0) - .get(0)).getName()); - assertEquals("Pencil 1", ((Pencil) listOfLists.get(1) - .get(0)).getName()); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(2) - .get(0)).getName()); + assertEquals("Pen 1", ((Pen) listOfLists.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) listOfLists.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(2).get(0)).getName()); } @SuppressWarnings("unchecked") @@ -43,11 +40,9 @@ public class ListOfListsUnitTest { ((ArrayList) listOfLists.get(1)).remove(0); listOfLists.remove(1); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(1) - .get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(1).get(0)).getName()); listOfLists.remove(0); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(0) - .get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(0).get(0)).getName()); } @Test @@ -67,11 +62,8 @@ public class ListOfListsUnitTest { list.add(pencils); list.add(rubbers); - assertEquals("Pen 1", ((Pen) list.get(0) - .get(0)).getName()); - assertEquals("Pencil 1", ((Pencil) list.get(1) - .get(0)).getName()); - assertEquals("Rubber 1", ((Rubber) list.get(2) - .get(0)).getName()); + assertEquals("Pen 1", ((Pen) list.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) list.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) list.get(2).get(0)).getName()); } } diff --git a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java index 9d8d3c884b..5fb85bb2c4 100644 --- a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java @@ -13,7 +13,6 @@ public class CoreThreadPoolIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class); - @Test(timeout = 1000) public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { From 67448de055fde89b7be1b7cd77a5a38df5ba7a8e Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 5 Aug 2017 16:32:00 +0300 Subject: [PATCH 06/67] enabling jee7 in the main build --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 82dccf832d..8401a2f159 100644 --- a/pom.xml +++ b/pom.xml @@ -80,7 +80,7 @@ javax-servlets javaxval jaxb - + jee7 jjwt jpa-storedprocedure From ae827f312222cc4e5ba97cd13fe2eecfe421e859 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 5 Aug 2017 22:07:50 +0200 Subject: [PATCH 07/67] Refactor hashcode() samples (#2377) --- core-java/hashcode/pom.xml | 39 ------------------- .../com/baeldung/application/Application.java | 23 ----------- .../main/java/com/baeldung/entities/User.java | 38 ------------------ .../baeldung/application/ApplicationTest.java | 30 -------------- .../java/com/baeldung/entities/UserTest.java | 34 ---------------- .../hashcode/application/Application.java | 24 ------------ .../hashcode/application/ApplicationTest.java | 30 +++++++------- 7 files changed, 15 insertions(+), 203 deletions(-) delete mode 100644 core-java/hashcode/pom.xml delete mode 100644 core-java/hashcode/src/main/java/com/baeldung/application/Application.java delete mode 100644 core-java/hashcode/src/main/java/com/baeldung/entities/User.java delete mode 100644 core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java delete mode 100644 core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java delete mode 100644 core-java/src/main/java/com/baeldung/hashcode/application/Application.java diff --git a/core-java/hashcode/pom.xml b/core-java/hashcode/pom.xml deleted file mode 100644 index 393aa69153..0000000000 --- a/core-java/hashcode/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - com.baeldung.hashcode - hashcode - 1.0 - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - - junit - junit - 4.12 - test - - - org.slf4j - slf4j-api - 1.7.25 - - - org.slf4j - slf4j-simple - 1.7.25 - - - \ No newline at end of file diff --git a/core-java/hashcode/src/main/java/com/baeldung/application/Application.java b/core-java/hashcode/src/main/java/com/baeldung/application/Application.java deleted file mode 100644 index 08c670c82f..0000000000 --- a/core-java/hashcode/src/main/java/com/baeldung/application/Application.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.application; - -import com.baeldung.entities.User; -import java.util.HashMap; -import java.util.Map; - -public class Application { - - public static void main(String[] args) { - Map users = new HashMap<>(); - User user1 = new User(1L, "John", "john@domain.com"); - User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); - User user3 = new User(3L, "Mary", "mary@domain.com"); - - users.put(user1, user1); - users.put(user2, user2); - users.put(user3, user3); - - if (users.containsKey(user1)) { - System.out.print("User found in the collection"); - } - } -} diff --git a/core-java/hashcode/src/main/java/com/baeldung/entities/User.java b/core-java/hashcode/src/main/java/com/baeldung/entities/User.java deleted file mode 100644 index a976233562..0000000000 --- a/core-java/hashcode/src/main/java/com/baeldung/entities/User.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.entities; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class User { - - private final Logger logger = LoggerFactory.getLogger(User.class); - private long id; - private String name; - private String email; - - public User(long id, String name, String email) { - this.id = id; - this.name = name; - this.email = email; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null) return false; - if (this.getClass() != o.getClass()) return false; - User user = (User) o; - return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); - } - - @Override - public int hashCode() { - int hash = 7; - hash = 31 * hash + (int) id; - hash = 31 * hash + (name == null ? 0 : name.hashCode()); - hash = 31 * hash + (email == null ? 0 : email.hashCode()); - logger.info("hashCode() method called - Computed hash: " + hash); - return hash; - } - // getters and setters here -} diff --git a/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java b/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java deleted file mode 100644 index dcd853f451..0000000000 --- a/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.application; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import static org.junit.Assert.assertEquals; - -public class ApplicationTest { - - private ByteArrayOutputStream outContent; - - @Before - public void setUpPrintStreamInstance() throws Exception { - this.outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - } - - @After - public void tearDownByteArrayOutputStream() throws Exception { - outContent = null; - } - - @Test - public void main_NoInputState_TextPrintedToConsole() throws Exception { - Application.main(new String[]{}); - assertEquals("User found in the collection", outContent.toString()); - } -} \ No newline at end of file diff --git a/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java b/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java deleted file mode 100644 index 01f6085d7e..0000000000 --- a/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.entities; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class UserTest { - - private User user; - private User comparisonUser; - - @Before - public void setUpUserInstances() { - this.user = new User(1L, "test", "test@domain.com"); - this.comparisonUser = this.user; - } - - @After - public void tearDownUserInstances() { - user = null; - comparisonUser = null; - } - - @Test - public void equals_EqualUserInstance_TrueAssertion(){ - Assert.assertTrue(user.equals(comparisonUser)); - } - - @Test - public void hashCode_UserHash_TrueAssertion() { - Assert.assertEquals(1792276941, user.hashCode()); - } -} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java deleted file mode 100644 index 8e6125045e..0000000000 --- a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.hashcode.application; - -import java.util.HashMap; -import java.util.Map; - -import com.baeldung.hashcode.entities.User; - -public class Application { - - public static void main(String[] args) { - Map users = new HashMap<>(); - User user1 = new User(1L, "John", "john@domain.com"); - User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); - User user3 = new User(3L, "Mary", "mary@domain.com"); - - users.put(user1, user1); - users.put(user2, user2); - users.put(user3, user3); - - if (users.containsKey(user1)) { - System.out.print("User found in the collection"); - } - } -} diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java index bf7a24347d..04e32e5fa0 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -1,30 +1,30 @@ package com.baeldung.hashcode.application; +import com.baeldung.hashcode.entities.User; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.util.HashMap; +import java.util.Map; + import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class ApplicationTest { - private ByteArrayOutputStream outContent; - - @Before - public void setUpPrintStreamInstance() throws Exception { - this.outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - } - - @After - public void tearDownByteArrayOutputStream() throws Exception { - outContent = null; - } - @Test public void main_NoInputState_TextPrintedToConsole() throws Exception { - Application.main(new String[] {}); - assertEquals("User found in the collection", outContent.toString()); + Map users = new HashMap<>(); + User user1 = new User(1L, "John", "john@domain.com"); + User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); + User user3 = new User(3L, "Mary", "mary@domain.com"); + + users.put(user1, user1); + users.put(user2, user2); + users.put(user3, user3); + + assertTrue(users.containsKey(user1)); } } \ No newline at end of file From 40b3cc7d2b1549c67f19610cac156772dbd7f69a Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sun, 6 Aug 2017 02:01:55 +0530 Subject: [PATCH 08/67] Bootique module (#2376) * moving jmh into libraries module * refactoring jmh * Update pom.xml * manual algorightm * with BM result * fix for space issue * Fixed indentation * change as per suggestion * vavr either * adding unit test and othe rutilities * adding concurrent module * concurrent package description * concurrent package description * Update EitherUnitTest.java * introducing lambda expression * jooby project * jooby project * reducing employee bean content * bootique module * bootique * bootique --- bootique/config.yml | 11 ++++ bootique/dependency-reduced-pom.xml | 50 ++++++++++++++ bootique/pom.xml | 66 +++++++++++++++++++ .../main/java/com/baeldung/bootique/App.java | 42 ++++++++++++ .../bootique/module/ModuleBinder.java | 15 +++++ .../bootique/module/ModuleProvider.java | 14 ++++ .../bootique/router/IndexController.java | 14 ++++ .../bootique/router/SaveController.java | 20 ++++++ .../bootique/service/HelloService.java | 7 ++ .../service/impl/HelloServiceImpl.java | 12 ++++ .../services/io.bootique.BQModuleProvider | 1 + .../java/com/baeldung/bootique/AppTest.java | 29 ++++++++ 12 files changed, 281 insertions(+) create mode 100644 bootique/config.yml create mode 100644 bootique/dependency-reduced-pom.xml create mode 100644 bootique/pom.xml create mode 100644 bootique/src/main/java/com/baeldung/bootique/App.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/router/IndexController.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/router/SaveController.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/service/HelloService.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java create mode 100644 bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider create mode 100644 bootique/src/test/java/com/baeldung/bootique/AppTest.java diff --git a/bootique/config.yml b/bootique/config.yml new file mode 100644 index 0000000000..269b4ab867 --- /dev/null +++ b/bootique/config.yml @@ -0,0 +1,11 @@ +log: + level: warn + appenders: + - type: file + logFormat: '%c{20}: %m%n' + file: /home/logger.log + +jetty: + context: /hello + connector: + port: 10001 diff --git a/bootique/dependency-reduced-pom.xml b/bootique/dependency-reduced-pom.xml new file mode 100644 index 0000000000..ed18f4e42a --- /dev/null +++ b/bootique/dependency-reduced-pom.xml @@ -0,0 +1,50 @@ + + + + bootique-parent + io.bootique.parent + 0.12 + + 4.0.0 + com.baeldung.bootique + bootique + bootique + 1.0-SNAPSHOT + http://maven.apache.org + + + + maven-shade-plugin + + + + + + io.bootique + bootique-test + 0.23 + test + + + junit + junit + 3.8.1 + test + + + + + + io.bootique.bom + bootique-bom + 0.23 + pom + import + + + + + com.baeldung.bootique.App + + + diff --git a/bootique/pom.xml b/bootique/pom.xml new file mode 100644 index 0000000000..28b716e104 --- /dev/null +++ b/bootique/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + com.baeldung.bootique + bootique + jar + 1.0-SNAPSHOT + bootique + http://maven.apache.org + + + com.baeldung.bootique.App + + + + io.bootique.parent + bootique-parent + 0.12 + + + + + + io.bootique.bom + bootique-bom + 0.23 + pom + import + + + + + + + io.bootique.jersey + bootique-jersey + compile + + + io.bootique.logback + bootique-logback + compile + + + io.bootique + bootique-test + test + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + + \ No newline at end of file diff --git a/bootique/src/main/java/com/baeldung/bootique/App.java b/bootique/src/main/java/com/baeldung/bootique/App.java new file mode 100644 index 0000000000..2fd03bd6c3 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/App.java @@ -0,0 +1,42 @@ +package com.baeldung.bootique; + +import java.util.function.Supplier; + +import com.baeldung.bootique.module.ModuleBinder; +import com.baeldung.bootique.router.IndexController; +import com.baeldung.bootique.router.SaveController; +import com.google.inject.Module; + +import io.bootique.Bootique; +import io.bootique.jersey.JerseyModule; +import io.bootique.log.BootLogger; + +public class App { + + public static void main(String[] args) { + Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class) + .addResource(SaveController.class); + Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() { + @Override + public void trace(Supplier arg0) { + // ... + } + + @Override + public void stdout(String arg0) { + // ... + } + + @Override + public void stderr(String arg0, Throwable arg1) { + // ... + } + + @Override + public void stderr(String arg0) { + // ... + } + }).autoLoadModules().exec(); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java new file mode 100644 index 0000000000..8c6fbb9642 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java @@ -0,0 +1,15 @@ +package com.baeldung.bootique.module; + +import com.baeldung.bootique.service.HelloService; +import com.baeldung.bootique.service.impl.HelloServiceImpl; +import com.google.inject.Binder; +import com.google.inject.Module; + +public class ModuleBinder implements Module { + + @Override + public void configure(Binder binder) { + binder.bind(HelloService.class).to(HelloServiceImpl.class); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java new file mode 100644 index 0000000000..8de866fcfb --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java @@ -0,0 +1,14 @@ +package com.baeldung.bootique.module; + +import com.google.inject.Module; + +import io.bootique.BQModuleProvider; + +public class ModuleProvider implements BQModuleProvider { + + @Override + public Module module() { + return new ModuleBinder(); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java new file mode 100644 index 0000000000..4bb80277a1 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java @@ -0,0 +1,14 @@ +package com.baeldung.bootique.router; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/") +public class IndexController { + + @GET + public String index() { + return "Hello, baeldung!"; + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java new file mode 100644 index 0000000000..0610b9d913 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java @@ -0,0 +1,20 @@ +package com.baeldung.bootique.router; + +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +import com.baeldung.bootique.service.HelloService; +import com.google.inject.Inject; + +@Path("/save") +public class SaveController { + + @Inject + HelloService helloService; + + @POST + public String save() { + return "Data Saved!"; + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java b/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java new file mode 100644 index 0000000000..74c0401cc3 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java @@ -0,0 +1,7 @@ +package com.baeldung.bootique.service; + +public interface HelloService { + + boolean save(); + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java b/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java new file mode 100644 index 0000000000..d2c0b5b838 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java @@ -0,0 +1,12 @@ +package com.baeldung.bootique.service.impl; + +import com.baeldung.bootique.service.HelloService; + +public class HelloServiceImpl implements HelloService { + + @Override + public boolean save() { + return true; + } + +} diff --git a/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider b/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider new file mode 100644 index 0000000000..714cf3a2df --- /dev/null +++ b/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider @@ -0,0 +1 @@ +com.baeldung.bootique.module.ModuleProvider \ No newline at end of file diff --git a/bootique/src/test/java/com/baeldung/bootique/AppTest.java b/bootique/src/test/java/com/baeldung/bootique/AppTest.java new file mode 100644 index 0000000000..0793e2f13c --- /dev/null +++ b/bootique/src/test/java/com/baeldung/bootique/AppTest.java @@ -0,0 +1,29 @@ +package com.baeldung.bootique; + +import static org.junit.Assert.assertEquals; + +import org.junit.Rule; +import org.junit.Test; + +import com.baeldung.bootique.service.HelloService; + +import io.bootique.BQRuntime; +import io.bootique.test.junit.BQDaemonTestFactory; +import io.bootique.test.junit.BQTestFactory; + +public class AppTest { + + @Rule + public BQTestFactory bqTestFactory = new BQTestFactory(); + + @Rule + public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); + + @Test + public void givenService_expectBoolen() { + BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); + HelloService service = runtime.getInstance(HelloService.class); + assertEquals(true, service.save()); + } + +} From b6e59c2ae7113bc31ae82d07571e2f9a87a70d86 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 6 Aug 2017 13:23:19 +0200 Subject: [PATCH 09/67] Refactor bootique (#2380) --- .../main/java/com/baeldung/bootique/App.java | 49 +++++++++---------- .../bootique/module/ModuleBinder.java | 8 +-- .../bootique/module/ModuleProvider.java | 9 ++-- .../bootique/router/IndexController.java | 10 ++-- .../bootique/router/SaveController.java | 22 ++++----- .../java/com/baeldung/bootique/AppTest.java | 30 ++++++------ .../hashcode/application/ApplicationTest.java | 6 +-- pom.xml | 1 + 8 files changed, 64 insertions(+), 71 deletions(-) diff --git a/bootique/src/main/java/com/baeldung/bootique/App.java b/bootique/src/main/java/com/baeldung/bootique/App.java index 2fd03bd6c3..cc1b90ce7d 100644 --- a/bootique/src/main/java/com/baeldung/bootique/App.java +++ b/bootique/src/main/java/com/baeldung/bootique/App.java @@ -1,42 +1,41 @@ package com.baeldung.bootique; -import java.util.function.Supplier; - import com.baeldung.bootique.module.ModuleBinder; import com.baeldung.bootique.router.IndexController; import com.baeldung.bootique.router.SaveController; import com.google.inject.Module; - import io.bootique.Bootique; import io.bootique.jersey.JerseyModule; import io.bootique.log.BootLogger; +import java.util.function.Supplier; + public class App { - public static void main(String[] args) { - Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class) - .addResource(SaveController.class); - Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() { - @Override - public void trace(Supplier arg0) { - // ... - } + public static void main(String[] args) { + Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class) + .addResource(SaveController.class); + Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() { + @Override + public void trace(Supplier arg0) { + // ... + } - @Override - public void stdout(String arg0) { - // ... - } + @Override + public void stdout(String arg0) { + // ... + } - @Override - public void stderr(String arg0, Throwable arg1) { - // ... - } + @Override + public void stderr(String arg0, Throwable arg1) { + // ... + } - @Override - public void stderr(String arg0) { - // ... - } - }).autoLoadModules().exec(); - } + @Override + public void stderr(String arg0) { + // ... + } + }).autoLoadModules().exec(); + } } diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java index 8c6fbb9642..8811d48652 100644 --- a/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java @@ -7,9 +7,9 @@ import com.google.inject.Module; public class ModuleBinder implements Module { - @Override - public void configure(Binder binder) { - binder.bind(HelloService.class).to(HelloServiceImpl.class); - } + @Override + public void configure(Binder binder) { + binder.bind(HelloService.class).to(HelloServiceImpl.class); + } } diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java index 8de866fcfb..cf78177e6d 100644 --- a/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java @@ -1,14 +1,13 @@ package com.baeldung.bootique.module; import com.google.inject.Module; - import io.bootique.BQModuleProvider; public class ModuleProvider implements BQModuleProvider { - @Override - public Module module() { - return new ModuleBinder(); - } + @Override + public Module module() { + return new ModuleBinder(); + } } diff --git a/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java index 4bb80277a1..6e3b31df41 100644 --- a/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java +++ b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java @@ -5,10 +5,10 @@ import javax.ws.rs.Path; @Path("/") public class IndexController { - - @GET - public String index() { - return "Hello, baeldung!"; - } + + @GET + public String index() { + return "Hello, baeldung!"; + } } diff --git a/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java index 0610b9d913..f38f59708c 100644 --- a/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java +++ b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java @@ -1,20 +1,20 @@ package com.baeldung.bootique.router; -import javax.ws.rs.POST; -import javax.ws.rs.Path; - import com.baeldung.bootique.service.HelloService; import com.google.inject.Inject; +import javax.ws.rs.POST; +import javax.ws.rs.Path; + @Path("/save") public class SaveController { - @Inject - HelloService helloService; - - @POST - public String save() { - return "Data Saved!"; - } - + @Inject + HelloService helloService; + + @POST + public String save() { + return "Data Saved!"; + } + } diff --git a/bootique/src/test/java/com/baeldung/bootique/AppTest.java b/bootique/src/test/java/com/baeldung/bootique/AppTest.java index 0793e2f13c..8856780ed4 100644 --- a/bootique/src/test/java/com/baeldung/bootique/AppTest.java +++ b/bootique/src/test/java/com/baeldung/bootique/AppTest.java @@ -1,29 +1,27 @@ package com.baeldung.bootique; -import static org.junit.Assert.assertEquals; - -import org.junit.Rule; -import org.junit.Test; - import com.baeldung.bootique.service.HelloService; - import io.bootique.BQRuntime; import io.bootique.test.junit.BQDaemonTestFactory; import io.bootique.test.junit.BQTestFactory; +import org.junit.Rule; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; public class AppTest { - @Rule - public BQTestFactory bqTestFactory = new BQTestFactory(); + @Rule + public BQTestFactory bqTestFactory = new BQTestFactory(); - @Rule - public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); + @Rule + public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); - @Test - public void givenService_expectBoolen() { - BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); - HelloService service = runtime.getInstance(HelloService.class); - assertEquals(true, service.save()); - } + @Test + public void givenService_expectBoolen() { + BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); + HelloService service = runtime.getInstance(HelloService.class); + assertEquals(true, service.save()); + } } diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java index 04e32e5fa0..60950fae7a 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -1,15 +1,11 @@ package com.baeldung.hashcode.application; import com.baeldung.hashcode.entities.User; -import org.junit.After; -import org.junit.Before; import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; + import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ApplicationTest { diff --git a/pom.xml b/pom.xml index 8401a2f159..f33d63bc48 100644 --- a/pom.xml +++ b/pom.xml @@ -38,6 +38,7 @@ apache-thrift autovalue axon + bootique cdi From 5383b2b01b857635b421d29216431fbedda1b5bb Mon Sep 17 00:00:00 2001 From: chrisoberle Date: Sun, 6 Aug 2017 16:31:55 -0400 Subject: [PATCH 10/67] add valueswithdefaults example (#2369) * add values with defaults example * add additional examples * remove unused imports --- .../ValuesWithDefaultsApp.java | 75 +++++++++++++++++++ .../resources/valueswithdefaults.properties | 0 2 files changed, 75 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java create mode 100644 spring-core/src/main/resources/valueswithdefaults.properties diff --git a/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java b/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java new file mode 100644 index 0000000000..d2cda19ae6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java @@ -0,0 +1,75 @@ +package com.baeldung.valuewithdefaults; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.util.Assert; + +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; + +/** + * Demonstrates setting defaults for @Value annotation. Note that there are no properties + * defined in the specified property source. We also assume that the user here + * does not have a system property named some.key. + * + */ +@Configuration +@PropertySource(name = "myProperties", value = "valueswithdefaults.properties") +public class ValuesWithDefaultsApp { + + @Value("${some.key:my default value}") + private String stringWithDefaultValue; + + @Value("${some.key:}") + private String stringWithBlankDefaultValue; + + @Value("${some.key:true}") + private boolean booleanWithDefaultValue; + + @Value("${some.key:42}") + private int intWithDefaultValue; + + @Value("${some.key:one,two,three}") + private String[] stringArrayWithDefaults; + + @Value("${some.key:1,2,3}") + private int[] intArrayWithDefaults; + + @Value("#{systemProperties['some.key'] ?: 'my default system property value'}") + private String spelWithDefaultValue; + + + public static void main(String[] args) { + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesWithDefaultsApp.class); + } + + @PostConstruct + public void afterInitialize() { + // strings + Assert.isTrue(stringWithDefaultValue.equals("my default value")); + Assert.isTrue(stringWithBlankDefaultValue.equals("")); + + // other primitives + Assert.isTrue(booleanWithDefaultValue); + Assert.isTrue(intWithDefaultValue == 42); + + // arrays + List stringListValues = Lists.newArrayList("one", "two", "three"); + Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues)); + + List intListValues = Lists.newArrayList(1, 2, 3); + Assert.isTrue(Ints.asList(intArrayWithDefaults).containsAll(intListValues)); + + // SpEL + Assert.isTrue(spelWithDefaultValue.equals("my default system property value")); + + } +} diff --git a/spring-core/src/main/resources/valueswithdefaults.properties b/spring-core/src/main/resources/valueswithdefaults.properties new file mode 100644 index 0000000000..e69de29bb2 From ddee04fca6640fdcb6fd8fb74c1437405ff75849 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 6 Aug 2017 21:53:30 -0500 Subject: [PATCH 11/67] BAEL-644: RSS with Rome (#2385) * BAEL-886: Updated README * BAEL-917 Testing with Google Truth Updated README * BAEL-936: adding akka-streams module to parent * BAEL-936: Update README * BAEL-918: Update README * BAEL-980: Update README * BAEL-967: Update README * BAEL-509: Using @GetMapping instead of @RequestMapping with method=GET * BAEL-1005: Update README * BAEL-509: Security and WebSockets (README) * BAEL-861: Intro to Awaitility (README) * BAEL-1010: Guide to the HyperLogLog Algorithm (README) * BAEL-907: Guide to Apache Commons CircularFifoQueue (README) * BAEL-644: Quick Guide to RSS with Rome --- libraries/pom.xml | 6 ++ .../com/baeldung/rome/RSSRomeExample.java | 76 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java diff --git a/libraries/pom.xml b/libraries/pom.xml index efdf20423a..87971fb26e 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -181,6 +181,11 @@ jetty-servlet ${jetty.version} + + rome + rome + ${rome.version} + io.specto hoverfly-java @@ -497,5 +502,6 @@ 1.6.0 1.7.1 2.1.2 + 1.0 diff --git a/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java b/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java new file mode 100644 index 0000000000..66a9e0ebce --- /dev/null +++ b/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java @@ -0,0 +1,76 @@ +package com.baeldung.rome; + +import com.sun.syndication.feed.synd.*; +import com.sun.syndication.io.FeedException; +import com.sun.syndication.io.SyndFeedInput; +import com.sun.syndication.io.SyndFeedOutput; +import com.sun.syndication.io.XmlReader; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class RSSRomeExample { + + public static void main(String[] args) throws IOException, FeedException { + SyndFeed feed = createFeed(); + addEntryToFeed(feed); + publishFeed(feed); + readFeed(); + } + + private static SyndFeed createFeed() { + SyndFeed feed = new SyndFeedImpl(); + feed.setFeedType("rss_1.0"); + feed.setTitle("Test title"); + feed.setLink("http://www.somelink.com"); + feed.setDescription("Basic description"); + + return feed; + } + + private static void addEntryToFeed(SyndFeed feed) { + SyndEntry entry = new SyndEntryImpl(); + entry.setTitle("Entry title"); + entry.setLink("http://www.somelink.com/entry1"); + + addDescriptionToEntry(entry); + addCategoryToEntry(entry); + + feed.setEntries(Arrays.asList(entry)); + } + + private static void addDescriptionToEntry(SyndEntry entry) { + SyndContent description = new SyndContentImpl(); + description.setType("text/html"); + description.setValue("First entry"); + + entry.setDescription(description); + } + + private static void addCategoryToEntry(SyndEntry entry) { + List categories = new ArrayList<>(); + SyndCategory category = new SyndCategoryImpl(); + category.setName("Sophisticated category"); + categories.add(category); + + entry.setCategories(categories); + } + + private static void publishFeed(SyndFeed feed) throws IOException, FeedException { + Writer writer = new FileWriter("xyz.txt"); + SyndFeedOutput syndFeedOutput = new SyndFeedOutput(); + syndFeedOutput.output(feed, writer); + writer.close(); + } + + private static SyndFeed readFeed() throws IOException, FeedException { + URL feedSource = new URL("http://rssblog.whatisrss.com/feed/"); + SyndFeedInput input = new SyndFeedInput(); + return input.build(new XmlReader(feedSource)); + } +} \ No newline at end of file From a1388b643b6327cd5b6d32be40eb9d11f2b42d20 Mon Sep 17 00:00:00 2001 From: Mansi Date: Mon, 7 Aug 2017 12:16:40 +0530 Subject: [PATCH 12/67] BAEL-378 A Guide to Activiti with Java (#2245) * Example Code For Evaluation Article This is an example code for the evaluation article on "Different Types of Bean Injection in Spring" * Added unit tests * Minor changes to application context * Removed code committed for evaluation article * BAEL-944 Demonstrating the problems with new Url pattern matching in Spring 5 * BAEL-944 Demonstrating the problems with new Url pattern matching in Spring 5 * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Code Formatting and solving build issue * BAEL-944 Resolving build issue due to change in Spring version * BAEL-944 Resolving build issue * BAEL-944 Formatting code * BAEL-944 Moving tests to correct package * BAEL-944 Moving tests to correct package * BAEL-944 Replacing @RequestMapping by @GetMapping * BAEL-944 Remove unnecessary attribute name, "value" in annotations * BAEL-79 Intro to Activiti with Spring * BAEL-79 Intro to Activiti with Spring * BAEL-79 Adding activiti module to the parent modules * BAEL-79 Using latest version * BAEL-79 Update Spring boot version that works with Activiti * BAEL-79 Replace RequestMapping with GetMapping * BAEL-79 Use Java 8 Syntax * BAEL-79 Formatting * BAEL-79 changed module name * BAEL-378 A Guide to Activiti with Java * BAEL-79 Fixed unit tests * BAEL-79 Simplified the process * BAEL-79 Fix test cases --- .../ActivitiController.java | 7 +- .../servicetasks/SendEmailServiceTask.java | 12 ++ .../resources/processes/my-process.bpmn20.xml | 65 ++------ .../ActivitiControllerIntegrationTest.java | 14 +- .../ProcessEngineCreationTests.java | 64 ++++++++ .../ProcessExecutionTests.java | 97 ++++++++++++ .../src/test/resources/activiti.cfg.xml | 16 ++ .../src/test/resources/my.activiti.cfg.xml | 26 +++ .../activiti/test/vacationRequest.bpmn20.xml | 149 ++++++++++++++++++ 9 files changed, 388 insertions(+), 62 deletions(-) create mode 100644 spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java create mode 100644 spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java create mode 100644 spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java create mode 100644 spring-activiti/src/test/resources/activiti.cfg.xml create mode 100644 spring-activiti/src/test/resources/my.activiti.cfg.xml create mode 100644 spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java index fd184556c4..96b551c03c 100644 --- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java @@ -42,16 +42,11 @@ public class ActivitiController { } @GetMapping("/complete-task-A/{processInstanceId}") - public TaskRepresentation completeTaskA(@PathVariable String processInstanceId) { + public void completeTaskA(@PathVariable String processInstanceId) { Task task = taskService.createTaskQuery() .processInstanceId(processInstanceId) .singleResult(); taskService.complete(task.getId()); logger.info("Task completed"); - task = taskService.createTaskQuery() - .processInstanceId(processInstanceId) - .singleResult(); - - return new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()); } } diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java b/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java new file mode 100644 index 0000000000..c11b48f37a --- /dev/null +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java @@ -0,0 +1,12 @@ +package com.example.activitiwithspring.servicetasks; + +import org.activiti.engine.delegate.DelegateExecution; +import org.activiti.engine.delegate.JavaDelegate; + +public class SendEmailServiceTask implements JavaDelegate { + + public void execute(DelegateExecution execution) { + //logic to sent email confirmation + } + +} diff --git a/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml b/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml index 3ced8d6b7c..6f151af458 100644 --- a/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml +++ b/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml @@ -1,66 +1,35 @@ - - + + - - - + + + - - - - - + - + - + - + - - + + - - - - - - + + + - - - - - - - + + + diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java index baca58f6ff..65fd33bfc6 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java @@ -106,14 +106,12 @@ public class ActivitiControllerIntegrationTest { .get(0); logger.info("process instance = " + pi.getId()); - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId())) - .andReturn() - .getResponse() - .getContentAsString(); - - ObjectMapper mapper = new ObjectMapper(); - TaskRepresentation task = mapper.readValue(responseBody, TaskRepresentation.class); - assertEquals("B", task.getName()); + this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId())) + .andReturn() + .getResponse() + .getContentAsString(); + List list = runtimeService.createProcessInstanceQuery().list(); + assertEquals(0, list.size()); } } diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java new file mode 100644 index 0000000000..7f07191cde --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java @@ -0,0 +1,64 @@ +package com.example.activitiwithspring; + +import org.activiti.engine.ProcessEngine; +import org.activiti.engine.ProcessEngineConfiguration; +import org.activiti.engine.ProcessEngines; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import org.junit.Test; + +public class ProcessEngineCreationTests { + + @Test + public void givenXMLConfig_whenGetDefault_thenGotProcessEngine() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + assertNotNull(processEngine); + assertEquals("root", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenXMLConfig_whenCreateDefaultConfiguration_thenGotProcessEngine() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault(); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("root", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenDifferentNameXMLConfig_whenGetProcessEngineConfig_thenGotResult() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("my.activiti.cfg.xml"); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenDifferentBeanNameInXMLConfig_whenGetProcessEngineConfig_thenGotResult() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration + .createProcessEngineConfigurationFromResource("my.activiti.cfg.xml", "myProcessEngineConfiguration"); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenNoXMLConfig_whenCreateInMemProcessEngineConfig_thenCreated() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration(); + ProcessEngine processEngine = processEngineConfiguration + .setJdbcUrl("jdbc:h2:mem:my-own-in-mem-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenNoXMLConfig_whenCreateProcessEngineConfig_thenCreated() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration(); + ProcessEngine processEngine = processEngineConfiguration + .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE) + .setJdbcUrl("jdbc:h2:mem:my-own-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } +} diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java new file mode 100644 index 0000000000..cae28d5281 --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java @@ -0,0 +1,97 @@ +package com.example.activitiwithspring; + + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.activiti.engine.ActivitiException; +import org.activiti.engine.ProcessEngine; +import org.activiti.engine.ProcessEngines; +import org.activiti.engine.RepositoryService; +import org.activiti.engine.RuntimeService; +import org.activiti.engine.TaskService; +import org.activiti.engine.runtime.ProcessInstance; +import org.activiti.engine.task.Task; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class ProcessExecutionTests { + + @Test + public void givenBPMN_whenDeployProcess_thenDeployed() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + Long count = repositoryService.createProcessDefinitionQuery().count(); + assertTrue(count >= 1); + } + + @Test + public void givenProcessDefinition_whenStartProcessInstance_thenProcessRunning() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + Map variables = new HashMap(); + variables.put("employeeName", "Kermit"); + variables.put("numberOfDays", new Integer(4)); + variables.put("vacationMotivation", "I'm really tired!"); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("vacationRequest", variables); + + Long count = runtimeService.createProcessInstanceQuery().count(); + assertTrue(count >= 1); + } + + @Test + public void givenProcessInstance_whenCompleteTask_thenProcessExecutionContinues() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + Map variables = new HashMap(); + variables.put("employeeName", "Kermit"); + variables.put("numberOfDays", new Integer(4)); + variables.put("vacationMotivation", "I'm really tired!"); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("vacationRequest", variables); + + TaskService taskService = processEngine.getTaskService(); + List tasks = taskService.createTaskQuery().taskCandidateGroup("management").list(); + + Task task = tasks.get(0); + + Map taskVariables = new HashMap(); + taskVariables.put("vacationApproved", "false"); + taskVariables.put("comments", "We have a tight deadline!"); + taskService.complete(task.getId(), taskVariables); + + Task currentTask = taskService.createTaskQuery().taskName("Modify vacation request").singleResult(); + assertNotNull(currentTask); + } + + @Test(expected = ActivitiException.class) + public void givenProcessDefinition_whenSuspend_thenNoProcessInstanceCreated() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + repositoryService.suspendProcessDefinitionByKey("vacationRequest"); + runtimeService.startProcessInstanceByKey("vacationRequest"); + } +} diff --git a/spring-activiti/src/test/resources/activiti.cfg.xml b/spring-activiti/src/test/resources/activiti.cfg.xml new file mode 100644 index 0000000000..1ee117d936 --- /dev/null +++ b/spring-activiti/src/test/resources/activiti.cfg.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/spring-activiti/src/test/resources/my.activiti.cfg.xml b/spring-activiti/src/test/resources/my.activiti.cfg.xml new file mode 100644 index 0000000000..07e4206dad --- /dev/null +++ b/spring-activiti/src/test/resources/my.activiti.cfg.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml b/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml new file mode 100644 index 0000000000..354c633385 --- /dev/null +++ b/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml @@ -0,0 +1,149 @@ + + + + + + + + + + + + + ${employeeName} would like to take ${numberOfDays} day(s) of vacation (Motivation: ${reason}). + + + + + + + + + + management + + + + + + + + + + Your manager has disapproved your vacation request for ${numberOfDays} days. + Reason: ${comments} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From d11d9ad8b190a2657a6d725c95273f01f1bbb159 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Mon, 7 Aug 2017 14:31:28 +0200 Subject: [PATCH 13/67] fix spring config (#2386) * fix spring config * fix spring config * fix spring config --- patterns/intercepting-filter/pom.xml | 1 - .../org/baeldung/config/UiApplication.java | 14 ++----------- .../org/baeldung/config/UiSecurityConfig.java | 20 +++++++++++++++++++ .../org/baeldung/config/UiApplication.java | 15 ++------------ .../org/baeldung/config/UiSecurityConfig.java | 20 +++++++++++++++++++ .../org/baeldung/config/UiApplication.java | 3 ++- 6 files changed, 46 insertions(+), 27 deletions(-) create mode 100644 spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java create mode 100644 spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml index 550409b643..5b7eb48a86 100644 --- a/patterns/intercepting-filter/pom.xml +++ b/patterns/intercepting-filter/pom.xml @@ -22,7 +22,6 @@ org.slf4j slf4j-api ${slf4j.version} - provided diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java index 5ef699d264..c0ad5eb690 100644 --- a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java @@ -3,24 +3,14 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.context.request.RequestContextListener; @EnableOAuth2Sso @SpringBootApplication -public class UiApplication extends WebSecurityConfigurerAdapter { +public class UiApplication extends SpringBootServletInitializer { - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } @Bean public RequestContextListener requestContextListener() { diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java new file mode 100644 index 0000000000..5dbe9ada34 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +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 UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java index 5ef699d264..6e29879cb3 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -3,24 +3,13 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.context.request.RequestContextListener; @EnableOAuth2Sso @SpringBootApplication -public class UiApplication extends WebSecurityConfigurerAdapter { - - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } +public class UiApplication extends SpringBootServletInitializer { @Bean public RequestContextListener requestContextListener() { diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java new file mode 100644 index 0000000000..5dbe9ada34 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +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 UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java index 625e5439ee..b8eda25960 100644 --- a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -2,11 +2,12 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableZuulProxy @SpringBootApplication -public class UiApplication { +public class UiApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(UiApplication.class, args); From 2263b24c9fb80b41636219319feff15b506cf4cc Mon Sep 17 00:00:00 2001 From: Roman Seleznov Date: Mon, 7 Aug 2017 21:19:41 +0100 Subject: [PATCH 14/67] BAEL-764 Renaming Modules as per the review (#2371) * Create pom.xml Initial import * First submit * Second submit * Different Types of Bean Injection in Spring * Different Types of Bean Injection in Spring * Added spring-core-di into the main build * Revert "Create pom.xml" This reverts commit 1bdc5443125df19575605f41ab28c9e8b6c69a32. * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot Make executable jars for property-exp-default project and use mvn exec:java to run property-exp-default project * BAEL-764 Automatic Property Expansion with Spring Boot Rename modules as per code reivew --- spring-boot-property-exp/pom.xml | 4 ++-- .../pom.xml | 0 .../propertyexpansion/SpringBootPropertyExpansionApp.java | 0 .../propertyexpansion/components/PropertyLoggerBean.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/banner.txt | 0 .../build.gradle | 0 .../gradle.properties | 0 .../pom.xml | 0 .../settings.gradle | 0 .../propertyexpansion/SpringBootPropertyExpansionApp.java | 0 .../propertyexpansion/components/PropertyLoggerBean.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/banner.txt | 0 14 files changed, 2 insertions(+), 2 deletions(-) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/pom.xml (100%) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java (100%) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java (100%) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/src/main/resources/application.properties (100%) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/src/main/resources/banner.txt (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/build.gradle (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/gradle.properties (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/pom.xml (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/settings.gradle (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/src/main/resources/application.properties (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/src/main/resources/banner.txt (100%) diff --git a/spring-boot-property-exp/pom.xml b/spring-boot-property-exp/pom.xml index f554bb5b99..0c54d57db1 100644 --- a/spring-boot-property-exp/pom.xml +++ b/spring-boot-property-exp/pom.xml @@ -24,8 +24,8 @@ - property-exp-default - property-exp-custom + property-exp-default-config + property-exp-custom-config diff --git a/spring-boot-property-exp/property-exp-custom/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml similarity index 100% rename from spring-boot-property-exp/property-exp-custom/pom.xml rename to spring-boot-property-exp/property-exp-custom-config/pom.xml diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties rename to spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt rename to spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt diff --git a/spring-boot-property-exp/property-exp-default/build.gradle b/spring-boot-property-exp/property-exp-default-config/build.gradle similarity index 100% rename from spring-boot-property-exp/property-exp-default/build.gradle rename to spring-boot-property-exp/property-exp-default-config/build.gradle diff --git a/spring-boot-property-exp/property-exp-default/gradle.properties b/spring-boot-property-exp/property-exp-default-config/gradle.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default/gradle.properties rename to spring-boot-property-exp/property-exp-default-config/gradle.properties diff --git a/spring-boot-property-exp/property-exp-default/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml similarity index 100% rename from spring-boot-property-exp/property-exp-default/pom.xml rename to spring-boot-property-exp/property-exp-default-config/pom.xml diff --git a/spring-boot-property-exp/property-exp-default/settings.gradle b/spring-boot-property-exp/property-exp-default-config/settings.gradle similarity index 100% rename from spring-boot-property-exp/property-exp-default/settings.gradle rename to spring-boot-property-exp/property-exp-default-config/settings.gradle diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/resources/application.properties rename to spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt rename to spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt From 1824320f95fda5a87347803fb9c1297feff4a2a6 Mon Sep 17 00:00:00 2001 From: cleversonzanon Date: Mon, 7 Aug 2017 18:14:57 -0300 Subject: [PATCH 15/67] [BAEL-1066] Implementing Singleton pattern in Java (#2361) * Different Types of Bean Injection in Spring code * Dataclasses in Kotlin * Revert "Different Types of Bean Injection in Spring code" This reverts commit 4b747726b93a9f6bf76d6518792fc77e0d5c2fc9. * Destructuring Declarations in Kotlin * Corrections on Destructuring Declarations in Kotlin * Implementing Singleton pattern in Java * [BAEL-1066] Implementing Singleton pattern in Java * Singleton Implementation changes. --- .../singleton/ClassSingleton.java | 28 ++++++++++++++++ .../singleton/EnumSingleton.java | 26 +++++++++++++++ .../designpatterns/singleton/Sandbox.java | 32 +++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java new file mode 100644 index 0000000000..0fc86e30a7 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java @@ -0,0 +1,28 @@ +package com.baeldung.designpatterns.singleton; + +public class ClassSingleton { + + private static ClassSingleton INSTANCE; + private String info = "Initial class info"; + + private ClassSingleton(){ + } + + public static ClassSingleton getInstance(){ + if(INSTANCE == null){ + INSTANCE = new ClassSingleton(); + } + + return INSTANCE; + } + + // getters and setters + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java new file mode 100644 index 0000000000..f75484477b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.singleton; + +public enum EnumSingleton { + + INSTANCE("Initial enum info"); //Name of the single instance + + private String info; + + private EnumSingleton(String info) { + this.info = info; + } + + public EnumSingleton getInstance(){ + return INSTANCE; + } + + //getters and setters + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java new file mode 100644 index 0000000000..f8ca2ffa78 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java @@ -0,0 +1,32 @@ +package com.baeldung.designpatterns.singleton; + +public class Sandbox { + + public static void main(String[] args) { + + //Class singleton + + ClassSingleton classSingleton1 = ClassSingleton.getInstance(); + //OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible + + System.out.println(classSingleton1.getInfo()); //Initial class info + + ClassSingleton classSingleton2 = ClassSingleton.getInstance(); + classSingleton2.setInfo("New class info"); + + System.out.println(classSingleton1.getInfo()); //New class info + System.out.println(classSingleton2.getInfo()); //New class info + + //Enum singleton + + EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance(); + + System.out.println(enumSingleton1.getInfo()); //Initial enum info + + EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance(); + enumSingleton2.setInfo("New enum info"); + + System.out.println(enumSingleton1.getInfo()); //New enum info + System.out.println(enumSingleton2.getInfo()); //New enum info + } +} From 53433a06d899571a22d08405208b441e439b9e01 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Mon, 7 Aug 2017 17:45:03 -0500 Subject: [PATCH 16/67] README updates (#2389) * BAEL-886: Updated README * BAEL-917 Testing with Google Truth Updated README * BAEL-936: adding akka-streams module to parent * BAEL-936: Update README * BAEL-918: Update README * BAEL-980: Update README * BAEL-967: Update README * BAEL-509: Using @GetMapping instead of @RequestMapping with method=GET * BAEL-1005: Update README * BAEL-509: Security and WebSockets (README) * BAEL-861: Intro to Awaitility (README) * BAEL-1010: Guide to the HyperLogLog Algorithm (README) * BAEL-907: Guide to Apache Commons CircularFifoQueue (README) * BAEL-1086: README update * BAEL-644: README update --- libraries/README.md | 1 + spring-core/README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/libraries/README.md b/libraries/README.md index 86baa39045..0e58628118 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -28,6 +28,7 @@ - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) - [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) - [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) +- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/spring-core/README.md b/spring-core/README.md index 380b3138fe..b0d0b8408c 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -6,3 +6,4 @@ - [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok) - [A Quick Guide to Spring @Value](http://www.baeldung.com/spring-value-annotation) - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) +- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) From 415b80d03f554f6535a4b74172ddf8daffc39ed8 Mon Sep 17 00:00:00 2001 From: ramansahasi Date: Tue, 8 Aug 2017 23:26:53 +0530 Subject: [PATCH 17/67] BAEL-1072 - Difference between Proxy, Decorator, Adapter, and Bridge Patterns (#2390) * Structural Design Patterns Difference between several types of structural design patterns * Structural Design Pattern Difference between several types of structural design patterns * Structural Design Patterns Difference between several types of structural design patterns * Structural Design Patterns Difference between several types of structural design patterns --- core-java/pom.xml | 6 ++- .../adapter/AdapterPatternDriver.java | 13 +++++ .../adapter/LuxuryCarsSpeed.java | 15 ++++++ .../adapter/LuxuryCarsSpeedAdapter.java | 7 +++ .../adapter/LuxuryCarsSpeedAdapterImpl.java | 26 ++++++++++ .../baeldung/designpatterns/bridge/Blue.java | 12 +++++ .../bridge/BridgePatternDriver.java | 14 +++++ .../baeldung/designpatterns/bridge/Color.java | 5 ++ .../baeldung/designpatterns/bridge/Red.java | 12 +++++ .../baeldung/designpatterns/bridge/Shape.java | 11 ++++ .../designpatterns/bridge/Square.java | 16 ++++++ .../designpatterns/bridge/Triangle.java | 16 ++++++ .../decorator/BubbleLights.java | 16 ++++++ .../decorator/ChristmasTree.java | 5 ++ .../decorator/ChristmasTreeImpl.java | 10 ++++ .../decorator/DecoratorPatternDriver.java | 20 +++++++ .../designpatterns/decorator/Garland.java | 16 ++++++ .../decorator/TreeDecorator.java | 15 ++++++ .../designpatterns/proxy/ExpensiveObject.java | 5 ++ .../proxy/ExpensiveObjectImpl.java | 20 +++++++ .../proxy/ExpensiveObjectProxy.java | 13 +++++ .../proxy/ProxyPatternDriver.java | 9 ++++ .../designpatterns/util/LogerUtil.java | 35 +++++++++++++ .../resources/log4jstructuraldp.properties | 9 ++++ .../AdapterPatternIntegrationTest.java | 20 +++++++ .../BridgePatternIntegrationTest.java | 52 +++++++++++++++++++ .../DecoratorPatternIntegrationTest.java | 28 ++++++++++ .../ProxyPatternIntegrationTest.java | 44 ++++++++++++++++ .../designpatterns/TestAppenderDP.java | 29 +++++++++++ 29 files changed, 498 insertions(+), 1 deletion(-) create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java create mode 100644 core-java/src/main/resources/log4jstructuraldp.properties create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java diff --git a/core-java/pom.xml b/core-java/pom.xml index 73b1c22ed8..422965a0ed 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -80,7 +80,11 @@ - + + log4j + log4j + 1.2.17 + org.slf4j slf4j-api diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java new file mode 100644 index 0000000000..0d69d0e7ec --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.adapter; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class AdapterPatternDriver { + + public static void main(String args[]) { + LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); + LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph."); + LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph."); + LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph."); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java new file mode 100644 index 0000000000..278329b994 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.adapter; + +public class LuxuryCarsSpeed { + public double bugattiVeyronInMPH() { + return 268; + } + + public double mcLarenInMPH() { + return 241; + } + + public double astonMartinInMPH() { + return 220; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java new file mode 100644 index 0000000000..84f7be2729 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java @@ -0,0 +1,7 @@ +package com.baeldung.designpatterns.adapter; + +public interface LuxuryCarsSpeedAdapter { + public double bugattiVeyronInKMPH(); + public double mcLarenInKMPH(); + public double astonMartinInKMPH(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java new file mode 100644 index 0000000000..2767b78e38 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.adapter; + +public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter { + + @Override + public double bugattiVeyronInKMPH() { + double mph = super.bugattiVeyronInMPH(); + return convertMPHtoKMPH(mph); + } + + @Override + public double mcLarenInKMPH() { + double mph = super.mcLarenInMPH(); + return convertMPHtoKMPH(mph); + } + + @Override + public double astonMartinInKMPH() { + double mph = super.astonMartinInMPH(); + return convertMPHtoKMPH(mph); + } + + private double convertMPHtoKMPH(double mph) { + return mph * 1.60934; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java new file mode 100644 index 0000000000..97a4a9508c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java @@ -0,0 +1,12 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Blue implements Color { + + @Override + public void fillColor() { + LOG.info("Color : Blue"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java new file mode 100644 index 0000000000..921deadcac --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java @@ -0,0 +1,14 @@ +package com.baeldung.designpatterns.bridge; + +public class BridgePatternDriver { + + public static void main(String[] args) { + //a square with red color + Shape square = new Square(new Red()); + square.drawShape(); + + //a triangle with blue color + Shape triangle = new Triangle(new Blue()); + triangle.drawShape(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java new file mode 100644 index 0000000000..91d2b01609 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.bridge; + +public interface Color { + public void fillColor(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java new file mode 100644 index 0000000000..8c22a94f00 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java @@ -0,0 +1,12 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Red implements Color { + + @Override + public void fillColor() { + LOG.info("Color : Red"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java new file mode 100644 index 0000000000..c4daf7a821 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java @@ -0,0 +1,11 @@ +package com.baeldung.designpatterns.bridge; + +public abstract class Shape { + protected Color color; + + public Shape(Color color) { + this.color = color; + } + + abstract public void drawShape(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java new file mode 100644 index 0000000000..6b377197eb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Square extends Shape { + + public Square(Color color) { + super(color); + } + + @Override + public void drawShape() { + LOG.info("Square drawn. "); + color.fillColor(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java new file mode 100644 index 0000000000..900e78cf2b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Triangle extends Shape { + + public Triangle(Color color) { + super(color); + } + + @Override + public void drawShape() { + LOG.info("Triangle drawn. "); + color.fillColor(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java new file mode 100644 index 0000000000..881add8b21 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.decorator; + +public class BubbleLights extends TreeDecorator { + + public BubbleLights(ChristmasTree tree) { + super(tree); + } + + public String decorate() { + return super.decorate() + decorateWithBubbleLights(); + } + + private String decorateWithBubbleLights() { + return " with Bubble Lights"; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java new file mode 100644 index 0000000000..80a0865567 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.decorator; + +public interface ChristmasTree { + public String decorate(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java new file mode 100644 index 0000000000..9241fd59db --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.decorator; + +public class ChristmasTreeImpl implements ChristmasTree { + + @Override + public String decorate() { + return "Christmas tree"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java new file mode 100644 index 0000000000..f70991da6b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns.decorator; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class DecoratorPatternDriver { + + public static void main(String[] args) { + //christmas tree with just one Garland + ChristmasTree tree1 = new Garland(new ChristmasTreeImpl()); + LOG.info(tree1.decorate()); + + //christmas tree with two Garlands and one Bubble lights + ChristmasTree tree2 = new BubbleLights(new Garland( + new Garland(new ChristmasTreeImpl())) + ); + LOG.info(tree2.decorate()); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java new file mode 100644 index 0000000000..d2efd6e451 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.decorator; + +public class Garland extends TreeDecorator { + + public Garland(ChristmasTree tree) { + super(tree); + } + + public String decorate() { + return super.decorate() + decorateWithGarland(); + } + + private String decorateWithGarland() { + return " with Garland"; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java new file mode 100644 index 0000000000..5427d2ac7e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.decorator; + +public abstract class TreeDecorator implements ChristmasTree { + private ChristmasTree tree; + + public TreeDecorator(ChristmasTree tree) { + this.tree = tree; + } + + @Override + public String decorate() { + return tree.decorate(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java new file mode 100644 index 0000000000..96a6bfb878 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.proxy; + +public interface ExpensiveObject { + public void process(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java new file mode 100644 index 0000000000..7014d3811c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns.proxy; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG;; + +public class ExpensiveObjectImpl implements ExpensiveObject { + + public ExpensiveObjectImpl() { + heavyInitialConfiguration(); + } + + @Override + public void process() { + LOG.info("processing complete."); + } + + private void heavyInitialConfiguration() { + LOG.info("Loading initial configuration..."); + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java new file mode 100644 index 0000000000..f36e688c90 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.proxy; + +public class ExpensiveObjectProxy implements ExpensiveObject{ + private static ExpensiveObject object; + + @Override + public void process() { + if(object == null) { + object = new ExpensiveObjectImpl(); + } + object.process(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java new file mode 100644 index 0000000000..088b069e28 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java @@ -0,0 +1,9 @@ +package com.baeldung.designpatterns.proxy; + +public class ProxyPatternDriver { + public static void main(String[] args) { + ExpensiveObject object = new ExpensiveObjectProxy(); + object.process(); + object.process(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java b/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java new file mode 100644 index 0000000000..f7b6e4f3e9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java @@ -0,0 +1,35 @@ +package com.baeldung.designpatterns.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Properties; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; + +public class LogerUtil { + + public final static Logger LOG = Logger.getLogger("GLOBAL"); + + static { + configuration(); + } + + private static void configuration() { + Properties props = new Properties(); + try { + props.load( + new BufferedReader( + new InputStreamReader( + LogerUtil.class.getResourceAsStream("/log4jstructuraldp.properties") + ) + ) + ); + } catch (IOException e) { + System.out.println("log4jstructuraldp.properties file not configured properly"); + System.exit(0); + } + PropertyConfigurator.configure(props); + } +} diff --git a/core-java/src/main/resources/log4jstructuraldp.properties b/core-java/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/core-java/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java new file mode 100644 index 0000000000..fb483a8a68 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns; + + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapter; +import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapterImpl; + +public class AdapterPatternIntegrationTest { + @Test + public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() { + LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); + assertEquals(luxuryCars.bugattiVeyronInKMPH(), 431.30312, 0.00001); + assertEquals(luxuryCars.mcLarenInKMPH(), 387.85094, 0.00001); + assertEquals(luxuryCars.astonMartinInKMPH(), 354.0548, 0.00001); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java new file mode 100644 index 0000000000..56a7a704f2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.designpatterns; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.designpatterns.bridge.Blue; +import com.baeldung.designpatterns.bridge.Red; +import com.baeldung.designpatterns.bridge.Shape; +import com.baeldung.designpatterns.bridge.Square; +import com.baeldung.designpatterns.bridge.Triangle; + +public class BridgePatternIntegrationTest { + public static TestAppenderDP appender; + + @Before + public void setUp() { + appender = new TestAppenderDP(); + LOG.addAppender(appender); + } + + @Test + public void whenBridgePatternInvoked_thenConfigSuccess() { + //a square with red color + Shape square = new Square(new Red()); + square.drawShape(); + + //a triangle with blue color + Shape triangle = new Triangle(new Blue()); + triangle.drawShape(); + + final List log = appender.getLog(); + + assertThat((String) log.get(0).getMessage(), is("Square drawn. ")); + assertThat((String) log.get(1).getMessage(), is("Color : Red")); + assertThat((String) log.get(2).getMessage(), is("Triangle drawn. ")); + assertThat((String) log.get(3).getMessage(), is("Color : Blue")); + } + + @After + public void tearDown() { + LOG.removeAppender(appender); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java new file mode 100644 index 0000000000..b3b3f988f1 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.designpatterns; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.designpatterns.decorator.BubbleLights; +import com.baeldung.designpatterns.decorator.ChristmasTree; +import com.baeldung.designpatterns.decorator.ChristmasTreeImpl; +import com.baeldung.designpatterns.decorator.Garland; + +public class DecoratorPatternIntegrationTest { + private ChristmasTree tree; + + @Test + public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() { + //christmas tree with just one Garland + tree = new Garland(new ChristmasTreeImpl()); + assertEquals(tree.decorate(), "Christmas tree with Garland"); + + //christmas tree with two Garlands and one Bubble lights + tree = new BubbleLights(new Garland( + new Garland(new ChristmasTreeImpl())) + ); + assertEquals(tree.decorate(), "Christmas tree with Garland with Garland with Bubble Lights"); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java new file mode 100644 index 0000000000..7fa95b31d7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.designpatterns; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.designpatterns.proxy.ExpensiveObject; +import com.baeldung.designpatterns.proxy.ExpensiveObjectProxy; + +public class ProxyPatternIntegrationTest { + public static TestAppenderDP appender; + + @Before + public void setUp() { + appender = new TestAppenderDP(); + LOG.addAppender(appender); + } + + @Test + public void givenExpensiveObjectProxy_WhenObjectInitialized_thenInitializedOnlyOnce() { + ExpensiveObject object = new ExpensiveObjectProxy(); + object.process(); + object.process(); + + final List log = appender.getLog(); + + assertThat((String) log.get(0).getMessage(), is("Loading initial configuration...")); + assertThat((String) log.get(1).getMessage(), is("processing complete.")); + assertThat((String) log.get(2).getMessage(), is("processing complete.")); + } + + @After + public void tearDown() { + LOG.removeAppender(appender); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java b/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java new file mode 100644 index 0000000000..613c26fa13 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java @@ -0,0 +1,29 @@ +package com.baeldung.designpatterns; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class TestAppenderDP extends AppenderSkeleton { + private final List log = new ArrayList(); + + @Override + public boolean requiresLayout() { + return false; + } + + @Override + protected void append(final LoggingEvent loggingEvent) { + log.add(loggingEvent); + } + + @Override + public void close() { + } + + public List getLog() { + return new ArrayList(log); + } +} \ No newline at end of file From 2036138ed17fc71fea05f52e9e8e7130825fbf7c Mon Sep 17 00:00:00 2001 From: Eric Goebelbecker Date: Wed, 9 Aug 2017 02:19:15 -0400 Subject: [PATCH 18/67] BAEL-1044 - Introduction to NoException (#2394) * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException --- noexception/README.md | 2 + noexception/pom.xml | 23 +++++++ .../noexception/CustomExceptionHandler.java | 24 +++++++ .../noexception/NoExceptionUnitTest.java | 63 +++++++++++++++++++ pom.xml | 1 + 5 files changed, 113 insertions(+) create mode 100644 noexception/README.md create mode 100644 noexception/pom.xml create mode 100644 noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java create mode 100644 noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java diff --git a/noexception/README.md b/noexception/README.md new file mode 100644 index 0000000000..d840191369 --- /dev/null +++ b/noexception/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) diff --git a/noexception/pom.xml b/noexception/pom.xml new file mode 100644 index 0000000000..64c0591fda --- /dev/null +++ b/noexception/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + + com.baeldung + noexception + 1.0 + noexception + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.machinezoo.noexception + noexception + 1.1.0 + + + diff --git a/noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java new file mode 100644 index 0000000000..59e13efaa0 --- /dev/null +++ b/noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java @@ -0,0 +1,24 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.ExceptionHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CustomExceptionHandler extends ExceptionHandler { + + private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class); + + @Override + public boolean handle(Throwable throwable) { + + if (throwable.getClass() + .isAssignableFrom(RuntimeException.class) + || throwable.getClass() + .isAssignableFrom(Error.class)) { + return false; + } else { + logger.error("Caught Exception ", throwable); + return true; + } + } +} diff --git a/noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java b/noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java new file mode 100644 index 0000000000..690ea43520 --- /dev/null +++ b/noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.Exceptions; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NoExceptionUnitTest { + + private static Logger logger = LoggerFactory.getLogger(NoExceptionUnitTest.class); + + @Test + public void whenStdExceptionHandling_thenCatchAndLog() { + try { + System.out.println("Result is " + Integer.parseInt("foobar")); + } catch (Throwable exception) { + logger.error("Caught exception:", exception); + } + } + + @Test + public void whenDefaultNoException_thenCatchAndLog() { + + Exceptions.log().run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenLogger_whenDefaultNoException_thenCatchAndLogWithClassName() { + System.out.println("Result is " + Exceptions.log(logger).get(() -> +Integer.parseInt("foobar")).orElse(-1)); + } + + @Test + public void givenLoggerAndMessage_whenDefaultNoException_thenCatchAndLogWithClassNameAndMessage() { + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> +Integer.parseInt("foobar")).orElse(-1)); + } + + @Test + public void givenDefaultValue_whenDefaultNoException_thenCatchAndLogPrintDefault() { + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> +Integer.parseInt("foobar")).orElse(-1)); + } + + @Test(expected = Error.class) + public void givenCustomHandler_whenError_thenRethrowError() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwError()); + } + + @Test + public void givenCustomHandler_whenException_thenCatchAndLog() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwException()); + } + + private static void throwError() { + throw new Error("This is very bad."); + } + + private static void throwException() { + String testString = "foo"; + testString.charAt(5); + } + +} diff --git a/pom.xml b/pom.xml index f33d63bc48..8b3df8de0d 100644 --- a/pom.xml +++ b/pom.xml @@ -106,6 +106,7 @@ mockito2 mocks mustache + noexception orika From 69f3e1175ace4edf9e2cfb5526060f431bfeead1 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Wed, 9 Aug 2017 15:30:02 +0200 Subject: [PATCH 19/67] minor fix (#2398) * fix spring config * fix spring config * fix spring config * minor fix --- apache-velocity/src/main/webapp/WEB-INF/velocity.properties | 2 +- spring-jpa/pom.xml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/apache-velocity/src/main/webapp/WEB-INF/velocity.properties b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties index 00e0b7e410..97b19f4cb7 100644 --- a/apache-velocity/src/main/webapp/WEB-INF/velocity.properties +++ b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties @@ -1,4 +1,4 @@ resource.loader=webapp webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader -webapp.resource.loader.path = . +webapp.resource.loader.path = webapp.resource.loader.cache = true \ No newline at end of file diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 1a1e6b3152..6a67d44b48 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -102,6 +102,7 @@ javax.servlet servlet-api + provided ${javax.servlet.servlet-api.version} From b5478f7e9a7d8a0b29040f58572b346e8527c85f Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 9 Aug 2017 15:32:08 +0200 Subject: [PATCH 20/67] Build opt 9 08 2017 (#2397) * pCollections * Reformat * Refactor metrics * Refactor hoverfly --- .../java/com/baeldung/hll/HLLUnitTest.java | 18 ++++++------ ...t.java => HoverflyApiIntegrationTest.java} | 2 +- .../pcollections/PCollectionsUnitTest.java | 29 ++++++++++++------- .../metrics/servo/AtlasObserverLiveTest.java | 3 -- ...t.java => MetricAnnotationManualTest.java} | 5 +--- ...est.java => MetricObserverManualTest.java} | 12 ++++---- ...rTest.java => MetricPollerManualTest.java} | 15 ++++++---- .../metrics/servo/MetricTestBase.java | 10 ++++--- .../metrics/servo/MetricTypeTest.java | 28 +++++++++++++----- 9 files changed, 72 insertions(+), 50 deletions(-) rename libraries/src/test/java/com/baeldung/hoverfly/{HoverflyApiTest.java => HoverflyApiIntegrationTest.java} (99%) rename metrics/src/test/java/com/baeldung/metrics/servo/{MetricAnnotationTest.java => MetricAnnotationManualTest.java} (95%) rename metrics/src/test/java/com/baeldung/metrics/servo/{MetricObserverTest.java => MetricObserverManualTest.java} (86%) rename metrics/src/test/java/com/baeldung/metrics/servo/{MetricPollerTest.java => MetricPollerManualTest.java} (74%) diff --git a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java b/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java index 8d09c99f0f..e208add3c8 100644 --- a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java @@ -23,9 +23,9 @@ public class HLLUnitTest { //when LongStream.range(0, numberOfElements).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - hll.addRaw(hashedValue); - } + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + hll.addRaw(hashedValue); + } ); //then @@ -44,15 +44,15 @@ public class HLLUnitTest { //when LongStream.range(0, numberOfElements).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - firstHll.addRaw(hashedValue); - } + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + firstHll.addRaw(hashedValue); + } ); LongStream.range(numberOfElements, numberOfElements * 2).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - secondHLL.addRaw(hashedValue); - } + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + secondHLL.addRaw(hashedValue); + } ); //then diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java similarity index 99% rename from libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java rename to libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java index bdaf4d7bd9..167aef5ec6 100644 --- a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java +++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java @@ -31,7 +31,7 @@ import org.springframework.web.client.RestTemplate; import io.specto.hoverfly.junit.core.SimulationSource; import io.specto.hoverfly.junit.rule.HoverflyRule; -public class HoverflyApiTest { +public class HoverflyApiIntegrationTest { private static final SimulationSource source = dsl( service("http://www.baeldung.com") diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java index 23f9abf2f3..acc7718ea8 100644 --- a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java @@ -1,7 +1,12 @@ package com.baeldung.pcollections; import org.junit.Test; -import org.pcollections.*; +import org.pcollections.HashPMap; +import org.pcollections.HashTreePMap; +import org.pcollections.HashTreePSet; +import org.pcollections.MapPSet; +import org.pcollections.PVector; +import org.pcollections.TreePVector; import java.util.Arrays; import java.util.HashMap; @@ -27,7 +32,7 @@ public class PCollectionsUnitTest { @Test public void givenExistingHashMap_whenFrom_thenCreateHashPMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("mkey1", "mval1"); map.put("mkey2", "mval2"); @@ -41,7 +46,7 @@ public class PCollectionsUnitTest { HashPMap pmap = HashTreePMap.empty(); HashPMap pmap0 = pmap.plus("key1", "value1"); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("key2", "val2"); map.put("key3", "val3"); @@ -57,22 +62,24 @@ public class PCollectionsUnitTest { @Test public void whenTreePVectorMethods_thenPerformOperations() { - TreePVector pVector = TreePVector.empty(); + TreePVector pVector = TreePVector.empty(); + + TreePVector pV1 = pVector.plus("e1"); + TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4")); - TreePVector pV1 = pVector.plus("e1"); - TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4")); assertEquals(1, pV1.size()); assertEquals(4, pV2.size()); - TreePVector pV3 = pV2.minus("e1"); - TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4")); + TreePVector pV3 = pV2.minus("e1"); + TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4")); + assertEquals(pV3.size(), 3); assertEquals(pV4.size(), 0); - TreePVector pSub = pV2.subList(0, 2); + TreePVector pSub = pV2.subList(0, 2); assertTrue(pSub.contains("e1") && pSub.contains("e2")); - TreePVector pVW = (TreePVector) pV2.with(0, "e10"); + PVector pVW = pV2.with(0, "e10"); assertEquals(pVW.get(0), "e10"); } @@ -80,7 +87,7 @@ public class PCollectionsUnitTest { public void whenMapPSetMethods_thenPerformOperations() { MapPSet pSet = HashTreePSet.empty() - .plusAll(Arrays.asList("e1","e2","e3","e4")); + .plusAll(Arrays.asList("e1", "e2", "e3", "e4")); assertEquals(pSet.size(), 4); MapPSet pSet1 = pSet.minus("e4"); diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java index cc2d3aa393..134c3c91cf 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java @@ -27,9 +27,6 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; -/** - * @author aiet - */ public class AtlasObserverLiveTest { private final String atlasUri = "http://localhost:7101/api/v1"; diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationManualTest.java similarity index 95% rename from metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationTest.java rename to metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationManualTest.java index 3d6a73912f..2f908531f6 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationManualTest.java @@ -22,10 +22,7 @@ import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -/** - * @author aiet - */ -public class MetricAnnotationTest extends MetricTestBase { +public class MetricAnnotationManualTest extends MetricTestBase { @Monitor(name = "integerCounter", type = DataSourceType.COUNTER, description = "Total number of update operations.") private final AtomicInteger updateCount = new AtomicInteger(0); diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverManualTest.java similarity index 86% rename from metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverTest.java rename to metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverManualTest.java index 14d3c2646f..3bb421b3ef 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverManualTest.java @@ -13,14 +13,16 @@ import java.util.List; import static com.netflix.servo.annotations.DataSourceType.GAUGE; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -/** - * @author aiet - */ -public class MetricObserverTest extends MetricTestBase { +public class MetricObserverManualTest extends MetricTestBase { @Test public void givenMetrics_whenRegister_thenMonitored() throws InterruptedException { diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerManualTest.java similarity index 74% rename from metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerTest.java rename to metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerManualTest.java index 4a9a77efde..318170fb1f 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerManualTest.java @@ -1,20 +1,23 @@ package com.baeldung.metrics.servo; import com.netflix.servo.Metric; -import com.netflix.servo.publish.*; +import com.netflix.servo.publish.BasicMetricFilter; +import com.netflix.servo.publish.JvmMetricPoller; +import com.netflix.servo.publish.MemoryMetricObserver; +import com.netflix.servo.publish.PollRunnable; +import com.netflix.servo.publish.PollScheduler; import org.junit.Test; import java.util.List; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toList; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; -/** - * @author aiet - */ -public class MetricPollerTest { +public class MetricPollerManualTest { @Test public void givenJvmPoller_whenMonitor_thenDataCollected() throws Exception { diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java index 86a9d201e8..42f3c72e97 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java @@ -1,14 +1,16 @@ package com.baeldung.metrics.servo; -import com.netflix.servo.publish.*; +import com.netflix.servo.publish.BasicMetricFilter; +import com.netflix.servo.publish.MemoryMetricObserver; +import com.netflix.servo.publish.MetricFilter; +import com.netflix.servo.publish.MonitorRegistryMetricPoller; +import com.netflix.servo.publish.PollRunnable; +import com.netflix.servo.publish.PollScheduler; import org.junit.After; import org.junit.Before; import static java.util.concurrent.TimeUnit.SECONDS; -/** - * @author aiet - */ abstract class MetricTestBase { MemoryMetricObserver observer; diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java index 68ba23244d..99009f8d84 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java @@ -1,6 +1,21 @@ package com.baeldung.metrics.servo; -import com.netflix.servo.monitor.*; +import com.netflix.servo.monitor.BasicCounter; +import com.netflix.servo.monitor.BasicGauge; +import com.netflix.servo.monitor.BasicInformational; +import com.netflix.servo.monitor.BasicTimer; +import com.netflix.servo.monitor.BucketConfig; +import com.netflix.servo.monitor.BucketTimer; +import com.netflix.servo.monitor.Counter; +import com.netflix.servo.monitor.Gauge; +import com.netflix.servo.monitor.MaxGauge; +import com.netflix.servo.monitor.Monitor; +import com.netflix.servo.monitor.MonitorConfig; +import com.netflix.servo.monitor.Monitors; +import com.netflix.servo.monitor.PeakRateCounter; +import com.netflix.servo.monitor.StatsTimer; +import com.netflix.servo.monitor.StepCounter; +import com.netflix.servo.monitor.Stopwatch; import com.netflix.servo.stats.StatsConfig; import org.junit.Ignore; import org.junit.Test; @@ -9,13 +24,12 @@ import java.util.Map; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toMap; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasEntry; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -/** - * Unit test for simple App. - */ public class MetricTypeTest { @Test @@ -113,7 +127,7 @@ public class MetricTypeTest { BucketTimer timer = new BucketTimer(MonitorConfig .builder("test") .build(), new BucketConfig.Builder() - .withBuckets(new long[] { 2L, 5L }) + .withBuckets(new long[]{2L, 5L}) .withTimeUnit(SECONDS) .build(), SECONDS); timer.record(3); @@ -150,7 +164,7 @@ public class MetricTypeTest { .builder("test") .build(), new StatsConfig.Builder() .withComputeFrequencyMillis(2000) - .withPercentiles(new double[] { 99.0, 95.0, 90.0 }) + .withPercentiles(new double[]{99.0, 95.0, 90.0}) .withPublishMax(true) .withPublishMin(true) .withPublishCount(true) From 1a001a5a6834a57f332c0a34e023757a367fee27 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 9 Aug 2017 15:58:00 +0200 Subject: [PATCH 21/67] Activiti test as integration (#2399) --- ...ProcessEngineCreationIntegrationTest.java} | 19 +++++----- ...a => ProcessExecutionIntegrationTest.java} | 35 ++++++++++--------- 2 files changed, 28 insertions(+), 26 deletions(-) rename spring-activiti/src/test/java/com/example/activitiwithspring/{ProcessEngineCreationTests.java => ProcessEngineCreationIntegrationTest.java} (85%) rename spring-activiti/src/test/java/com/example/activitiwithspring/{ProcessExecutionTests.java => ProcessExecutionIntegrationTest.java} (85%) diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationIntegrationTest.java similarity index 85% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationIntegrationTest.java index 7f07191cde..00afd14590 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationIntegrationTest.java @@ -3,11 +3,12 @@ package com.example.activitiwithspring; import org.activiti.engine.ProcessEngine; import org.activiti.engine.ProcessEngineConfiguration; import org.activiti.engine.ProcessEngines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import org.junit.Test; -public class ProcessEngineCreationTests { +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class ProcessEngineCreationIntegrationTest { @Test public void givenXMLConfig_whenGetDefault_thenGotProcessEngine() { @@ -35,7 +36,7 @@ public class ProcessEngineCreationTests { @Test public void givenDifferentBeanNameInXMLConfig_whenGetProcessEngineConfig_thenGotResult() { ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration - .createProcessEngineConfigurationFromResource("my.activiti.cfg.xml", "myProcessEngineConfiguration"); + .createProcessEngineConfigurationFromResource("my.activiti.cfg.xml", "myProcessEngineConfiguration"); ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); assertNotNull(processEngine); assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); @@ -45,8 +46,8 @@ public class ProcessEngineCreationTests { public void givenNoXMLConfig_whenCreateInMemProcessEngineConfig_thenCreated() { ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration(); ProcessEngine processEngine = processEngineConfiguration - .setJdbcUrl("jdbc:h2:mem:my-own-in-mem-db;DB_CLOSE_DELAY=1000") - .buildProcessEngine(); + .setJdbcUrl("jdbc:h2:mem:my-own-in-mem-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); assertNotNull(processEngine); assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); } @@ -55,9 +56,9 @@ public class ProcessEngineCreationTests { public void givenNoXMLConfig_whenCreateProcessEngineConfig_thenCreated() { ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration(); ProcessEngine processEngine = processEngineConfiguration - .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE) - .setJdbcUrl("jdbc:h2:mem:my-own-db;DB_CLOSE_DELAY=1000") - .buildProcessEngine(); + .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE) + .setJdbcUrl("jdbc:h2:mem:my-own-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); assertNotNull(processEngine); assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); } diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionIntegrationTest.java similarity index 85% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionIntegrationTest.java index cae28d5281..9c35ea413b 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionIntegrationTest.java @@ -1,10 +1,6 @@ package com.example.activitiwithspring; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.activiti.engine.ActivitiException; import org.activiti.engine.ProcessEngine; import org.activiti.engine.ProcessEngines; @@ -13,19 +9,24 @@ import org.activiti.engine.RuntimeService; import org.activiti.engine.TaskService; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import org.junit.Test; -public class ProcessExecutionTests { +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class ProcessExecutionIntegrationTest { @Test public void givenBPMN_whenDeployProcess_thenDeployed() { ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); RepositoryService repositoryService = processEngine.getRepositoryService(); repositoryService.createDeployment() - .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") - .deploy(); + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); Long count = repositoryService.createProcessDefinitionQuery().count(); assertTrue(count >= 1); } @@ -35,8 +36,8 @@ public class ProcessExecutionTests { ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); RepositoryService repositoryService = processEngine.getRepositoryService(); repositoryService.createDeployment() - .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") - .deploy(); + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); Map variables = new HashMap(); variables.put("employeeName", "Kermit"); @@ -45,7 +46,7 @@ public class ProcessExecutionTests { RuntimeService runtimeService = processEngine.getRuntimeService(); ProcessInstance processInstance = runtimeService - .startProcessInstanceByKey("vacationRequest", variables); + .startProcessInstanceByKey("vacationRequest", variables); Long count = runtimeService.createProcessInstanceQuery().count(); assertTrue(count >= 1); @@ -56,8 +57,8 @@ public class ProcessExecutionTests { ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); RepositoryService repositoryService = processEngine.getRepositoryService(); repositoryService.createDeployment() - .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") - .deploy(); + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); Map variables = new HashMap(); variables.put("employeeName", "Kermit"); @@ -66,7 +67,7 @@ public class ProcessExecutionTests { RuntimeService runtimeService = processEngine.getRuntimeService(); ProcessInstance processInstance = runtimeService - .startProcessInstanceByKey("vacationRequest", variables); + .startProcessInstanceByKey("vacationRequest", variables); TaskService taskService = processEngine.getTaskService(); List tasks = taskService.createTaskQuery().taskCandidateGroup("management").list(); @@ -87,8 +88,8 @@ public class ProcessExecutionTests { ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); RepositoryService repositoryService = processEngine.getRepositoryService(); repositoryService.createDeployment() - .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") - .deploy(); + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); RuntimeService runtimeService = processEngine.getRuntimeService(); repositoryService.suspendProcessDefinitionByKey("vacationRequest"); From ca70e9f9fbf1d4186f4028538c61e181333fded6 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Thu, 10 Aug 2017 02:49:03 +0530 Subject: [PATCH 22/67] Changes for BAEL-332 (#2396) --- .../controller/redirect/RedirectController.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java b/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java index 472c0c8bf5..59868593a3 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java @@ -1,11 +1,15 @@ package org.baeldung.web.controller.redirect; +import javax.servlet.http.HttpServletRequest; + +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.View; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; @@ -49,4 +53,16 @@ public class RedirectController { model.addAttribute("redirectionAttribute", flashAttribute); return new ModelAndView("redirection", model); } + + @RequestMapping(value = "/redirectPostToPost", method = RequestMethod.POST) + public ModelAndView redirectPostToPost(HttpServletRequest request) { + request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT); + return new ModelAndView("redirect:/redirectedPostToPost"); + } + + @RequestMapping(value = "/redirectedPostToPost", method = RequestMethod.POST) + public ModelAndView redirectedPostToPost() { + return new ModelAndView("redirection"); + } + } \ No newline at end of file From 71ef6b2a431d8395b41ffa1387ff650a4f0b35ae Mon Sep 17 00:00:00 2001 From: Mohamed Sanaulla Date: Thu, 10 Aug 2017 04:02:17 +0300 Subject: [PATCH 23/67] code for Java 9 Objects API (#2408) --- .../language/Java9ObjectsAPIUnitTest.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java new file mode 100644 index 0000000000..a174e519ab --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.java9.language; + +import org.junit.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +import static org.hamcrest.Matchers.*; +import static org.hamcrest.MatcherAssert.assertThat; + +public class Java9ObjectsAPIUnitTest { + + @Test + public void givenNullObject_whenRequireNonNullElse_thenElse(){ + assertThat(Objects.requireNonNullElse(null, Collections.EMPTY_LIST), + is(Collections.EMPTY_LIST)); + } + + @Test + public void givenObject_whenRequireNonNullElse_thenObject(){ + assertThat(Objects.requireNonNullElse(List.of("item1", "item2"), + Collections.EMPTY_LIST), is(List.of("item1", "item2"))); + } + + @Test + public void givenObject_whenRequireNonNullElseGet_thenObject(){ + assertThat(Objects.requireNonNullElseGet(null, List::of), + is(List.of())); + } + + @Test + public void givenNumber_whenInvokeCheckIndex_thenNumber(){ + int length = 5; + + assertThat(Objects.checkIndex(4, length), is(4)); + + try{ + Objects.checkIndex(5, length); + }catch(Exception ex){ + assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); + } + } + + @Test + public void givenSubRange_whenCheckFromToIndex_thenNumber(){ + int length = 6; + + assertThat(Objects.checkFromToIndex(2,length,length), is(2)); + + try{ + Objects.checkFromToIndex(2,7,length); + }catch(Exception ex){ + assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); + } + } + + @Test + public void giveSubRange_whenCheckFromIndexSize_thenNumber(){ + int length = 6; + + assertThat(Objects.checkFromToIndex(2,5,length), is(2)); + + try{ + Objects.checkFromToIndex(2,6,length); + }catch(Exception ex){ + assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); + } + } + + +} From 146b633bacef437ea51c1d9ed0bc3526b53505b3 Mon Sep 17 00:00:00 2001 From: Makoto Go Date: Thu, 10 Aug 2017 08:27:27 -0500 Subject: [PATCH 24/67] New artifacts for BAEL-1081. (#2392) * New artifacts for BAEL-1081. * Consolidate code to new package. --- junit5/pom.xml | 8 +- .../param/InvalidPersonParameterResolver.java | 50 ++++++ .../test/java/com/baeldung/param/Person.java | 43 ++++++ .../com/baeldung/param/PersonValidator.java | 142 ++++++++++++++++++ .../baeldung/param/PersonValidatorTest.java | 102 +++++++++++++ .../param/ValidPersonParameterResolver.java | 50 ++++++ 6 files changed, 391 insertions(+), 4 deletions(-) create mode 100644 junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java create mode 100644 junit5/src/test/java/com/baeldung/param/Person.java create mode 100644 junit5/src/test/java/com/baeldung/param/PersonValidator.java create mode 100644 junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java create mode 100644 junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java diff --git a/junit5/pom.xml b/junit5/pom.xml index 2316b034e9..1fa4818447 100644 --- a/junit5/pom.xml +++ b/junit5/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.baeldung + junit5 1.0-SNAPSHOT @@ -19,9 +19,9 @@ UTF-8 1.8 - 5.0.0-M5 - 1.0.0-M5 - 4.12.0-M5 + 5.0.0-RC2 + 1.0.0-RC2 + 4.12.0-RC2 2.8.2 1.4.196 diff --git a/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java new file mode 100644 index 0000000000..67bd47a44a --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java @@ -0,0 +1,50 @@ +package com.baeldung.param; + +import java.util.Random; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class InvalidPersonParameterResolver implements ParameterResolver { + + /** + * The "bad" (invalid) data for testing purposes has to go somewhere, right? + */ + public static Person[] INVALID_PERSONS = { + new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"), + new Person().setId(2L).setLastName(",Baker").setFirstName(""), + new Person().setId(3L).setLastName(null).setFirstName(null), + new Person().setId(4L).setLastName("Daniel&").setFirstName("{Joseph}"), + new Person().setId(5L).setLastName("").setFirstName("English, Jane"), + new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */, + // TODO: ADD MORE DATA HERE + }; + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + Object ret = null; + // + // Return a random, valid Person object if Person.class is the type of Parameter + /// to be resolved. Otherwise return null. + if (parameterContext.getParameter().getType() == Person.class) { + ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)]; + } + return ret; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + boolean ret = false; + // + // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! + if (parameterContext.getParameter().getType() == Person.class) { + ret = true; + } + return ret; + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/Person.java b/junit5/src/test/java/com/baeldung/param/Person.java new file mode 100644 index 0000000000..65333b5e56 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.param; + +/** + * Very simple Person entity. + * Use the Fluent-style interface to set properties. + * + * @author J Steven Perry + * + */ +public class Person { + + private Long id; + private String lastName; + private String firstName; + + public Long getId() { + return id; + } + + public Person setId(Long id) { + this.id = id; + return this; + } + + public String getLastName() { + return lastName; + } + + public Person setLastName(String lastName) { + this.lastName = lastName; + return this; + } + + public String getFirstName() { + return firstName; + } + + public Person setFirstName(String firstName) { + this.firstName = firstName; + return this; + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidator.java b/junit5/src/test/java/com/baeldung/param/PersonValidator.java new file mode 100644 index 0000000000..0219169aab --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/PersonValidator.java @@ -0,0 +1,142 @@ +package com.baeldung.param; + +import java.util.Arrays; + +/** + * Somewhat contrived validation class to illustrate unit test + * concepts. + * + * @author J Steven Perry + * + */ +public class PersonValidator { + + /** + * Contrived checked exception to illustrate one possible + * way to handle validation errors (via a checked exception). + * + * @author J Steven Perry + * + */ + public static class ValidationException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -134518049431883102L; + + // Probably should implement some more constructors, but don't want + /// to tarnish the lesson... + + /** + * The one and only way to create this checked exception. + * + * @param message + * The message accompanying the exception. Should be meaningful. + */ + public ValidationException(String message) { + super(message); + + } + + } + + private static final String[] ILLEGAL_NAME_CHARACTERS = { + ",", + "_", + "{", + "}", + "!" + }; + + /** + * Validate the first name of the specified Person object. + * + * @param person + * The Person object to validate. + * + * @return - returns true if the specified Person is valid + * + * @throws ValidationException + * - this Exception is thrown if any kind of validation error occurs. + */ + public static boolean validateFirstName(Person person) throws ValidationException { + boolean ret = true; + // The validation rules go here. + // Naive: use simple ifs + if (person == null) { + throw new ValidationException("Person is null (not allowed)!"); + } + if (person.getFirstName() == null) { + throw new ValidationException("Person FirstName is null (not allowed)!"); + } + if (person.getFirstName().isEmpty()) { + throw new ValidationException("Person FirstName is an empty String (not allowed)!"); + } + if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { + throw new ValidationException( + "Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: " + + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + + "!"); + } + return ret; + } + + /** + * Validate the last name of the specified Person object. Looks the same as first + * name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge. + * + * @param person + * The Person object to validate. + * + * @return - returns true if the specified Person is valid + * + * @throws ValidationException + * - this Exception is thrown if any kind of validation error occurs. + */ + public static boolean validateLastName(Person person) throws ValidationException { + boolean ret = true; + // The validation rules go here. + // Naive: use simple ifs + if (person == null) { + throw new ValidationException("Person is null (not allowed)!"); + } + if (person.getFirstName() == null) { + throw new ValidationException("Person FirstName is null (not allowed)!"); + } + if (person.getFirstName().isEmpty()) { + throw new ValidationException("Person FirstName is an empty String (not allowed)!"); + } + if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { + throw new ValidationException( + "Person LastName (" + person.getLastName() + ") may not contain any of the following characters: " + + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + + "!"); + } + return ret; + } + + /** + * Validates the specified name. If it contains any of the illegalCharacters, + * this method returns false (indicating the name is illegal). Otherwise it returns true. + * + * @param candidate + * The candidate String to validate + * + * @param illegalCharacters + * The characters the String is not allowed to have + * + * @return - boolean - true if the name is valid, false otherwise. + */ + private static boolean isStringValid(String candidate, String[] illegalCharacters) { + boolean ret = true; + for (String illegalChar : illegalCharacters) { + if (candidate.contains(illegalChar)) { + ret = false; + break; + } + } + return ret; + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java b/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java new file mode 100644 index 0000000000..09ab03b811 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java @@ -0,0 +1,102 @@ +package com.baeldung.param; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@DisplayName("Testing PersonValidator") +public class PersonValidatorTest { + + /** + * Nested class, uses ExtendWith + * {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver} + * to feed Test methods with "good" data. + */ + @Nested + @DisplayName("When using Valid data") + @ExtendWith(ValidPersonParameterResolver.class) + public class ValidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are valid") + public void validateFirstName(Person person) { + try { + assertTrue(PersonValidator.validateFirstName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All last names are valid") + public void validateLastName(Person person) { + try { + assertTrue(PersonValidator.validateLastName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + + } + + /** + * Nested class, uses ExtendWith + * {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver} + * to feed Test methods with "bad" data. + */ + @Nested + @DisplayName("When using Invalid data") + @ExtendWith(InvalidPersonParameterResolver.class) + public class InvalidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateFirstName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person)); + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateLastName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person)); + } + + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java b/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java new file mode 100644 index 0000000000..abb97586eb --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java @@ -0,0 +1,50 @@ +package com.baeldung.param; + +import java.util.Random; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class ValidPersonParameterResolver implements ParameterResolver { + + /** + * The "good" (valid) data for testing purposes has to go somewhere, right? + */ + public static Person[] VALID_PERSONS = { + new Person().setId(1L).setLastName("Adams").setFirstName("Jill"), + new Person().setId(2L).setLastName("Baker").setFirstName("James"), + new Person().setId(3L).setLastName("Carter").setFirstName("Samanta"), + new Person().setId(4L).setLastName("Daniels").setFirstName("Joseph"), + new Person().setId(5L).setLastName("English").setFirstName("Jane"), + new Person().setId(6L).setLastName("Fontana").setFirstName("Enrique"), + // TODO: ADD MORE DATA HERE + }; + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + Object ret = null; + // + // Return a random, valid Person object if Person.class is the type of Parameter + /// to be resolved. Otherwise return null. + if (parameterContext.getParameter().getType() == Person.class) { + ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)]; + } + return ret; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + boolean ret = false; + // + // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! + if (parameterContext.getParameter().getType() == Person.class) { + ret = true; + } + return ret; + } + +} From c3de3dbfa9d1ed6ab552f4e4a55cf29d05364aac Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Thu, 10 Aug 2017 16:58:22 +0300 Subject: [PATCH 25/67] BAEL 1035 - Introduction to Eclipse Collections (#2395) * Evaluation article: Different Types of Bean Injection in Spring * added tests & changed configuration to Java-based config * removed xml config files * rename unit tests * BAEL-972 - Apache Commons Text * remove code from evaluation article * remove code from evaluation article * BAEL-972 - Apache Commons Text - added another example * BAEL-972 - Apache Commons Text - just indentation * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java - fix problems * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * fix formatting * BAEL-1033 minor refactor * BAEL-1035 Introduction to Eclipse Collections * format * BAEL-1035 Introduction to Eclipse Collections --- libraries/pom.xml | 8 ++- .../ConvertContainerToAnother.java | 20 ++++++ .../baeldung/eclipsecollections/Student.java | 20 ++++++ .../AllSatisfyPatternTest.java | 34 +++++++++++ .../AnySatisfyPatternTest.java | 34 +++++++++++ .../CollectPatternTest.java | 22 +++++++ .../ConvertContainerToAnotherTest.java | 20 ++++++ .../eclipsecollections/DetectPatternTest.java | 34 +++++++++++ .../ForEachPatternTest.java | 32 ++++++++++ .../InjectIntoPatternTest.java | 23 +++++++ .../eclipsecollections/LazyIterationTest.java | 26 ++++++++ .../PartitionPatternTest.java | 61 +++++++++++++++++++ .../eclipsecollections/RejectPatternTest.java | 38 ++++++++++++ .../eclipsecollections/SelectPatternTest.java | 52 ++++++++++++++++ 14 files changed, 423 insertions(+), 1 deletion(-) create mode 100644 libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java create mode 100644 libraries/src/main/java/com/baeldung/eclipsecollections/Student.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 87971fb26e..8f28a23d75 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -462,6 +462,11 @@ pcollections ${pcollections.version} + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + 0.7.0 @@ -503,5 +508,6 @@ 1.7.1 2.1.2 1.0 + 8.2.0 - + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java new file mode 100644 index 0000000000..069baeab9f --- /dev/null +++ b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java @@ -0,0 +1,20 @@ +package com.baeldung.eclipsecollections; + +import java.util.List; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.set.mutable.UnifiedSet; + +public class ConvertContainerToAnother { + + @SuppressWarnings("rawtypes") + public static List convertToList() { + UnifiedSet cars = new UnifiedSet<>(); + + cars.add("Toyota"); + cars.add("Mercedes"); + cars.add("Volkswagen"); + + return cars.toList(); + } +} diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java new file mode 100644 index 0000000000..2c634a28d9 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java @@ -0,0 +1,20 @@ +package com.baeldung.eclipsecollections; + +public class Student { + + private String firstName; + private String lastName; + + public Student(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return this.firstName; + } + + public String getLastName() { + return this.lastName; + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java new file mode 100644 index 0000000000..1ea10317c7 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java @@ -0,0 +1,34 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class AllSatisfyPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + boolean result = list.allSatisfy(Predicates.greaterThan(0)); + + assertTrue(result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java new file mode 100644 index 0000000000..58f8ad40af --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java @@ -0,0 +1,34 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class AnySatisfyPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + boolean result = list.anySatisfy(Predicates.greaterThan(30)); + + assertTrue(result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java new file mode 100644 index 0000000000..51591cd08c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java @@ -0,0 +1,22 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class CollectPatternTest { + + @Test + public void whenCollect_thenCorrect() { + Student student1 = new Student("John", "Hopkins"); + Student student2 = new Student("George", "Adams"); + + MutableList students = FastList.newListWith(student1, student2); + + MutableList lastNames = students.collect(Student::getLastName); + + assertEquals(lastNames.get(0), "Hopkins"); + assertEquals(lastNames.get(1), "Adams"); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java new file mode 100644 index 0000000000..b538abfa6e --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java @@ -0,0 +1,20 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.junit.Test; + +public class ConvertContainerToAnotherTest { + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void whenConvertContainerToAnother_thenCorrect() { + MutableList cars = (MutableList) ConvertContainerToAnother.convertToList(); + + assertTrue(cars.anySatisfy(Predicates.equal("Toyota"))); + assertTrue(cars.anySatisfy(Predicates.equal("Mercedes"))); + assertTrue(cars.anySatisfy(Predicates.equal("Volkswagen"))); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java new file mode 100644 index 0000000000..fc643f2840 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java @@ -0,0 +1,34 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class DetectPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void whenDetect_thenCorrect() { + Integer result = list.detect(Predicates.greaterThan(30)); + + assertEquals((int) result, 41); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java new file mode 100644 index 0000000000..e8d93a2af6 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java @@ -0,0 +1,32 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.block.procedure.Procedure; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.map.mutable.UnifiedMap; +import org.eclipse.collections.impl.tuple.Tuples; +import static org.junit.Assert.assertEquals; + +import java.util.Map; + +import org.junit.Test; + +public class ForEachPatternTest { + + @SuppressWarnings("unchecked") + @Test + public void whenInstantiateAndChangeValues_thenCorrect() { + Pair pair1 = Tuples.pair(1, "One"); + Pair pair2 = Tuples.pair(2, "Two"); + Pair pair3 = Tuples.pair(3, "Three"); + + UnifiedMap map = UnifiedMap.newMapWith(pair1, pair2, pair3); + + for (int i = 0; i < map.size(); i++) { + map.put(i + 1, "New Value"); + } + + for (int i = 0; i < map.size(); i++) { + assertEquals("New Value", map.get(i + 1)); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java new file mode 100644 index 0000000000..bcd34021b1 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java @@ -0,0 +1,23 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.eclipse.collections.impl.factory.Lists; +import org.junit.Test; + +public class InjectIntoPatternTest { + + @Test + public void whenInjectInto_thenCorrect() { + List list = Lists.mutable.of(1, 2, 3, 4); + int result = 5; + for (int i = 0; i < list.size(); i++) { + Integer v = list.get(i); + result = result + v.intValue(); + } + + assertEquals(15, result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java new file mode 100644 index 0000000000..8fe1286d41 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.LazyIterable; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.factory.Lists; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class LazyIterationTest { + + @Test + public void whenLazyIteration_thenCorrect() { + Student student1 = new Student("John", "Hopkins"); + Student student2 = new Student("George", "Adams"); + Student student3 = new Student("Jennifer", "Rodriguez"); + + MutableList students = Lists.mutable.with(student1, student2, student3); + LazyIterable lazyStudents = students.asLazy(); + LazyIterable lastNames = lazyStudents.collect(Student::getLastName); + + assertTrue(lastNames.anySatisfy(Predicates.equal("Hopkins"))); + assertTrue(lastNames.anySatisfy(Predicates.equal("Adams"))); + assertTrue(lastNames.anySatisfy(Predicates.equal("Rodriguez"))); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java new file mode 100644 index 0000000000..3e52829824 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java @@ -0,0 +1,61 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.block.predicate.Predicate; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.partition.list.PartitionMutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class PartitionPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @SuppressWarnings({ "unused" }) + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + MutableList numbers = list; + PartitionMutableList partitionedFolks = numbers.partition(new Predicate() { + + /** + * + */ + private static final long serialVersionUID = -1551138743683678406L; + + public boolean accept(Integer each) { + return each > 30; + } + }); + MutableList greaterThanThirty = partitionedFolks.getSelected() + .sortThis(); + MutableList smallerThanThirty = partitionedFolks.getRejected() + .sortThis(); + + assertEquals(1, (int) smallerThanThirty.getFirst()); + assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(5))); + assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(8))); + assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(17))); + assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(23))); + + assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(31))); + assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(38))); + assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(41))); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java new file mode 100644 index 0000000000..044a8203d6 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java @@ -0,0 +1,38 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; + +public class RejectPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void whenReject_thenCorrect() { + MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)) + .sortThis(); + + assertEquals(1, (int) notGreaterThanThirty.getFirst()); + assertEquals(5, (int) notGreaterThanThirty.get(1)); + assertEquals(8, (int) notGreaterThanThirty.get(2)); + assertEquals(17, (int) notGreaterThanThirty.get(3)); + assertEquals(23, (int) notGreaterThanThirty.getLast()); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java new file mode 100644 index 0000000000..20c94f6028 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java @@ -0,0 +1,52 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; + +public class SelectPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void givenListwhenSelect_thenCorrect() { + MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)) + .sortThis(); + + assertEquals(31, (int) greaterThanThirty.getFirst()); + assertEquals(38, (int) greaterThanThirty.get(1)); + assertEquals(41, (int) greaterThanThirty.getLast()); + } + + @SuppressWarnings("rawtypes") + public MutableList selectUsingLambda() { + return list.select(each -> each > 30) + .sortThis(); + } + + @SuppressWarnings("unchecked") + @Test + public void givenListwhenSelectUsingLambda_thenCorrect() { + MutableList greaterThanThirty = selectUsingLambda(); + + assertEquals(31, (int) greaterThanThirty.getFirst()); + assertEquals(38, (int) greaterThanThirty.get(1)); + assertEquals(41, (int) greaterThanThirty.getLast()); + } +} From accb430f5e76d3223f3ee1fb00c92c008669c30f Mon Sep 17 00:00:00 2001 From: Mohamed Sanaulla Date: Thu, 10 Aug 2017 20:45:43 +0300 Subject: [PATCH 26/67] java 9 objects api sample (#2413) --- .../baeldung/java9/process/ServiceMain.java | 2 +- .../language/Java9ObjectsAPIUnitTest.java | 50 ++++++++++--------- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java index 299f74e877..5dc00dba25 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java @@ -6,7 +6,7 @@ public class ServiceMain { public static void main(String[] args) throws InterruptedException { ProcessHandle thisProcess = ProcessHandle.current(); - long pid = thisProcess.getPid(); + long pid = thisProcess.pid(); Optional opArgs = Optional.ofNullable(args); String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java index a174e519ab..93abe4e185 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java @@ -10,7 +10,7 @@ import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.assertThat; public class Java9ObjectsAPIUnitTest { - + @Test public void givenNullObject_whenRequireNonNullElse_thenElse(){ assertThat(Objects.requireNonNullElse(null, Collections.EMPTY_LIST), @@ -23,6 +23,11 @@ public class Java9ObjectsAPIUnitTest { Collections.EMPTY_LIST), is(List.of("item1", "item2"))); } + @Test(expected = NullPointerException.class) + public void givenNull_whenRequireNonNullElse_thenException(){ + Objects.requireNonNullElse(null, null); + } + @Test public void givenObject_whenRequireNonNullElseGet_thenObject(){ assertThat(Objects.requireNonNullElseGet(null, List::of), @@ -32,40 +37,39 @@ public class Java9ObjectsAPIUnitTest { @Test public void givenNumber_whenInvokeCheckIndex_thenNumber(){ int length = 5; - assertThat(Objects.checkIndex(4, length), is(4)); - - try{ - Objects.checkIndex(5, length); - }catch(Exception ex){ - assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); - } } + @Test(expected = IndexOutOfBoundsException.class) + public void givenOutOfRangeNumber_whenInvokeCheckIndex_thenException(){ + int length = 5; + Objects.checkIndex(5, length); + } + + @Test public void givenSubRange_whenCheckFromToIndex_thenNumber(){ int length = 6; - assertThat(Objects.checkFromToIndex(2,length,length), is(2)); - - try{ - Objects.checkFromToIndex(2,7,length); - }catch(Exception ex){ - assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); - } } - @Test - public void giveSubRange_whenCheckFromIndexSize_thenNumber(){ + @Test(expected = IndexOutOfBoundsException.class) + public void givenInvalidSubRange_whenCheckFromToIndex_thenException(){ int length = 6; + Objects.checkFromToIndex(2,7,length); + } - assertThat(Objects.checkFromToIndex(2,5,length), is(2)); - try{ - Objects.checkFromToIndex(2,6,length); - }catch(Exception ex){ - assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); - } + @Test + public void givenSubRange_whenCheckFromIndexSize_thenNumber(){ + int length = 6; + assertThat(Objects.checkFromIndexSize(2,3,length), is(2)); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void givenInvalidSubRange_whenCheckFromIndexSize_thenException(){ + int length = 6; + Objects.checkFromIndexSize(2, 6, length); } From 69d8c107515a4eaa8bf5c4828e435a74abc0249e Mon Sep 17 00:00:00 2001 From: Eric Goebelbecker Date: Thu, 10 Aug 2017 13:59:38 -0400 Subject: [PATCH 27/67] BAEL-1044 - Introduction to NoException (#2412) * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException * Update pom.xml Add missing --- libraries/README.md | 2 + libraries/pom.xml | 7 ++- .../noexception/CustomExceptionHandler.java | 24 +++++++ .../noexception/NoExceptionUnitTest.java | 62 +++++++++++++++++++ 4 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java create mode 100644 libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java diff --git a/libraries/README.md b/libraries/README.md index 0e58628118..88075af390 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -29,6 +29,8 @@ - [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) - [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) +- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) + The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 8f28a23d75..490302ca29 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -462,6 +462,11 @@ pcollections ${pcollections.version} + + com.machinezoo.noexception + noexception + 1.1.0 + org.eclipse.collections eclipse-collections @@ -510,4 +515,4 @@ 1.0 8.2.0 - \ No newline at end of file + diff --git a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java new file mode 100644 index 0000000000..59e13efaa0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java @@ -0,0 +1,24 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.ExceptionHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CustomExceptionHandler extends ExceptionHandler { + + private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class); + + @Override + public boolean handle(Throwable throwable) { + + if (throwable.getClass() + .isAssignableFrom(RuntimeException.class) + || throwable.getClass() + .isAssignableFrom(Error.class)) { + return false; + } else { + logger.error("Caught Exception ", throwable); + return true; + } + } +} diff --git a/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java b/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java new file mode 100644 index 0000000000..b7619202fe --- /dev/null +++ b/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.Exceptions; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NoExceptionUnitTest { + + private static Logger logger = LoggerFactory.getLogger(NoExceptionUnitTest.class); + + @Test + public void whenStdExceptionHandling_thenCatchAndLog() { + try { + System.out.println("Result is " + Integer.parseInt("foobar")); + } catch (Throwable exception) { + logger.error("Caught exception:", exception); + } + } + + @Test + public void whenDefaultNoException_thenCatchAndLog() { + Exceptions.log().run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenLogger_whenDefaultNoException_thenCatchAndLogWithClassName() { + Exceptions.log(logger).run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenLoggerAndMessage_whenDefaultNoException_thenCatchAndLogWithMessage() { + Exceptions.log(logger, "Something went wrong:").run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenDefaultValue_whenDefaultNoException_thenCatchAndLogPrintDefault() { + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> Integer.parseInt("foobar")).orElse(-1)); + } + + @Test(expected = Error.class) + public void givenCustomHandler_whenError_thenRethrowError() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwError()); + } + + @Test + public void givenCustomHandler_whenException_thenCatchAndLog() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwException()); + } + + private static void throwError() { + throw new Error("This is very bad."); + } + + private static void throwException() { + String testString = "foo"; + testString.charAt(5); + } + +} From 127dd7323d801a78bed8adf057e41e6a916c7616 Mon Sep 17 00:00:00 2001 From: Parth Karia Date: Fri, 11 Aug 2017 20:39:36 +0530 Subject: [PATCH 28/67] BAEL-243 Spring Batch using Partitioner (#2419) * BAEL-1004 changes in variable names * BAEL-243 Spring Batch using Partitioner --- .../CustomMultiResourcePartitioner.java | 77 ++++++++ .../SpringbatchPartitionConfig.java | 169 ++++++++++++++++++ .../SpringbatchPartitionerApp.java | 28 +++ .../resources/input/partitioner/record1.csv | 4 + .../resources/input/partitioner/record2.csv | 4 + .../resources/input/partitioner/record3.csv | 4 + .../resources/input/partitioner/record4.csv | 4 + .../resources/input/partitioner/record5.csv | 4 + .../src/main/resources/output/output1.xml | 21 +++ .../src/main/resources/output/output2.xml | 21 +++ .../src/main/resources/output/output3.xml | 21 +++ .../src/main/resources/output/output4.xml | 21 +++ .../src/main/resources/output/output5.xml | 21 +++ 13 files changed, 399 insertions(+) create mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java create mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java create mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java create mode 100644 spring-batch/src/main/resources/input/partitioner/record1.csv create mode 100644 spring-batch/src/main/resources/input/partitioner/record2.csv create mode 100644 spring-batch/src/main/resources/input/partitioner/record3.csv create mode 100644 spring-batch/src/main/resources/input/partitioner/record4.csv create mode 100644 spring-batch/src/main/resources/input/partitioner/record5.csv create mode 100644 spring-batch/src/main/resources/output/output1.xml create mode 100644 spring-batch/src/main/resources/output/output2.xml create mode 100644 spring-batch/src/main/resources/output/output3.xml create mode 100644 spring-batch/src/main/resources/output/output4.xml create mode 100644 spring-batch/src/main/resources/output/output5.xml diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java new file mode 100644 index 0000000000..4cae69efbd --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java @@ -0,0 +1,77 @@ +/* + * Copyright 2006-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.baeldung.spring_batch_intro.partitioner; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.batch.core.partition.support.Partitioner; +import org.springframework.batch.item.ExecutionContext; +import org.springframework.core.io.Resource; +import org.springframework.util.Assert; + +public class CustomMultiResourcePartitioner implements Partitioner { + + private static final String DEFAULT_KEY_NAME = "fileName"; + + private static final String PARTITION_KEY = "partition"; + + private Resource[] resources = new Resource[0]; + + private String keyName = DEFAULT_KEY_NAME; + + /** + * The resources to assign to each partition. In Spring configuration you + * can use a pattern to select multiple resources. + * @param resources the resources to use + */ + public void setResources(Resource[] resources) { + this.resources = resources; + } + + /** + * The name of the key for the file name in each {@link ExecutionContext}. + * Defaults to "fileName". + * @param keyName the value of the key + */ + public void setKeyName(String keyName) { + this.keyName = keyName; + } + + /** + * Assign the filename of each of the injected resources to an + * {@link ExecutionContext}. + * + * @see Partitioner#partition(int) + */ + @Override + public Map partition(int gridSize) { + Map map = new HashMap(gridSize); + int i = 0, k = 1; + for (Resource resource : resources) { + ExecutionContext context = new ExecutionContext(); + Assert.state(resource.exists(), "Resource does not exist: " + resource); + context.putString(keyName, resource.getFilename()); + context.putString("opFileName", "output" + k++ + ".xml"); + + map.put(PARTITION_KEY + i, context); + i++; + } + return map; + } + +} diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java new file mode 100644 index 0000000000..fe8339a8b4 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java @@ -0,0 +1,169 @@ +package org.baeldung.spring_batch_intro.partitioner; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.text.ParseException; + +import javax.sql.DataSource; + +import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; +import org.springframework.batch.item.UnexpectedInputException; +import org.springframework.batch.item.file.FlatFileItemReader; +import org.springframework.batch.item.file.mapping.DefaultLineMapper; +import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; +import org.springframework.batch.item.xml.StaxEventItemWriter; +import org.springframework.batch.support.transaction.ResourcelessTransactionManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.task.TaskExecutor; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.oxm.Marshaller; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.transaction.PlatformTransactionManager; + +@Configuration +@EnableBatchProcessing +public class SpringbatchPartitionConfig { + + @Autowired + ResourcePatternResolver resoursePatternResolver; + + @Autowired + private JobBuilderFactory jobs; + + @Autowired + private StepBuilderFactory steps; + + @Bean(name = "partitionerJob") + public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException { + return jobs.get("partitionerJob") + .start(partitionStep()) + .build(); + } + + @Bean + public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException { + return steps.get("partitionStep") + .partitioner("slaveStep", partitioner()) + .step(slaveStep()) + .taskExecutor(taskExecutor()) + .build(); + } + + @Bean + public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException { + return steps.get("slaveStep") + . chunk(1) + .reader(itemReader(null)) + .writer(itemWriter(marshaller(), null)) + .build(); + } + + @Bean + public CustomMultiResourcePartitioner partitioner() { + CustomMultiResourcePartitioner partitioner = new CustomMultiResourcePartitioner(); + Resource[] resources; + try { + resources = resoursePatternResolver.getResources("file:src/main/resources/input/partitioner/*.csv"); + } catch (IOException e) { + throw new RuntimeException("I/O problems when resolving the input file pattern.", e); + } + partitioner.setResources(resources); + return partitioner; + } + + @Bean + @StepScope + public FlatFileItemReader itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { + FlatFileItemReader reader = new FlatFileItemReader(); + DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); + String[] tokens = { "username", "userid", "transactiondate", "amount" }; + tokenizer.setNames(tokens); + reader.setResource(new ClassPathResource("input/partitioner/" + filename)); + DefaultLineMapper lineMapper = new DefaultLineMapper(); + lineMapper.setLineTokenizer(tokenizer); + lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); + reader.setLinesToSkip(1); + reader.setLineMapper(lineMapper); + return reader; + } + + @Bean(destroyMethod = "") + @StepScope + public StaxEventItemWriter itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) throws MalformedURLException { + StaxEventItemWriter itemWriter = new StaxEventItemWriter<>(); + itemWriter.setMarshaller(marshaller); + itemWriter.setRootTagName("transactionRecord"); + itemWriter.setResource(new FileSystemResource("src/main/resources/output/" + filename)); + return itemWriter; + } + + @Bean + public Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + return marshaller; + } + + @Bean + public TaskExecutor taskExecutor() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setMaxPoolSize(5); + taskExecutor.setCorePoolSize(5); + taskExecutor.setQueueCapacity(5); + taskExecutor.afterPropertiesSet(); + return taskExecutor; + } + + private JobRepository getJobRepository() throws Exception { + JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); + factory.setDataSource(dataSource()); + factory.setTransactionManager(getTransactionManager()); + // JobRepositoryFactoryBean's methods Throws Generic Exception, + // it would have been better to have a specific one + factory.afterPropertiesSet(); + return (JobRepository) factory.getObject(); + } + + private DataSource dataSource() { + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL) + .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") + .addScript("classpath:org/springframework/batch/core/schema-h2.sql") + .build(); + return db; + } + + private PlatformTransactionManager getTransactionManager() { + return new ResourcelessTransactionManager(); + } + + public JobLauncher getJobLauncher() throws Exception { + SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); + // SimpleJobLauncher's methods Throws Generic Exception, + // it would have been better to have a specific one + jobLauncher.setJobRepository(getJobRepository()); + jobLauncher.afterPropertiesSet(); + return jobLauncher; + } +} diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java new file mode 100644 index 0000000000..1d6d922969 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java @@ -0,0 +1,28 @@ +package org.baeldung.spring_batch_intro.partitioner; + +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class SpringbatchPartitionerApp { + public static void main(final String[] args) { + // Spring Java config + final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(SpringbatchPartitionConfig.class); + context.refresh(); + + final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + final Job job = (Job) context.getBean("partitionerJob"); + System.out.println("Starting the batch job"); + try { + final JobExecution execution = jobLauncher.run(job, new JobParameters()); + System.out.println("Job Status : " + execution.getStatus()); + System.out.println("Job succeeded"); + } catch (final Exception e) { + e.printStackTrace(); + System.out.println("Job failed"); + } + } +} \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record1.csv b/spring-batch/src/main/resources/input/partitioner/record1.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record1.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record2.csv b/spring-batch/src/main/resources/input/partitioner/record2.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record2.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record3.csv b/spring-batch/src/main/resources/input/partitioner/record3.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record3.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record4.csv b/spring-batch/src/main/resources/input/partitioner/record4.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record4.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record5.csv b/spring-batch/src/main/resources/input/partitioner/record5.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record5.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output1.xml b/spring-batch/src/main/resources/output/output1.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output1.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output2.xml b/spring-batch/src/main/resources/output/output2.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output2.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output3.xml b/spring-batch/src/main/resources/output/output3.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output3.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output4.xml b/spring-batch/src/main/resources/output/output4.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output4.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output5.xml b/spring-batch/src/main/resources/output/output5.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output5.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file From dc3589a7a0548e0d6d1a1158fabd0f6af9bd4b2e Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Fri, 11 Aug 2017 22:02:08 +0200 Subject: [PATCH 29/67] fix spring-boot module (#2422) * fix spring config * fix spring config * fix spring config * minor fix * fix spring-boot module --- spring-boot/pom.xml | 8 ++++---- .../baeldung/servlets/props/PropertySourcesLoader.java | 2 +- .../utils/{Application.java => UtilsApplication.java} | 4 ++-- spring-boot/src/main/webapp/WEB-INF/context.xml | 4 ++-- spring-boot/src/main/webapp/WEB-INF/dispatcher.xml | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) rename spring-boot/src/main/java/com/baeldung/utils/{Application.java => UtilsApplication.java} (83%) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 2a1de00039..3fafa6ade2 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -52,7 +52,7 @@ test - + io.dropwizard.metrics @@ -253,8 +253,8 @@ - org.baeldung.boot.DemoApplication - 4.3.4.RELEASE + 4.3.4.RELEASE 2.2.1 3.1.1 3.3.7-1 diff --git a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java b/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java index 56a6751326..aa70bac777 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java @@ -9,7 +9,7 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.ConfigurableEnvironment; @Configuration -@ComponentScan(basePackages = { "com.baeldung.*" }) +@ComponentScan(basePackages = { "com.baeldung.servlets.*" }) @PropertySource("classpath:custom.properties") public class PropertySourcesLoader { private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class); diff --git a/spring-boot/src/main/java/com/baeldung/utils/Application.java b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java similarity index 83% rename from spring-boot/src/main/java/com/baeldung/utils/Application.java rename to spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java index 9d5d75bce2..b63ada9eee 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/Application.java +++ b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java @@ -10,11 +10,11 @@ import com.baeldung.autoconfiguration.MySQLAutoconfiguration; @SpringBootApplication(exclude=MySQLAutoconfiguration.class) @ComponentScan(basePackages="com.baeldung.utils") -public class Application { +public class UtilsApplication { @RolesAllowed("*") public static void main(String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(UtilsApplication.class, args); } } diff --git a/spring-boot/src/main/webapp/WEB-INF/context.xml b/spring-boot/src/main/webapp/WEB-INF/context.xml index 263bed4430..32f11f78f6 100644 --- a/spring-boot/src/main/webapp/WEB-INF/context.xml +++ b/spring-boot/src/main/webapp/WEB-INF/context.xml @@ -6,7 +6,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> - + - + \ No newline at end of file diff --git a/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml b/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml index ade8e66777..54e62921be 100644 --- a/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml +++ b/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml @@ -7,7 +7,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> - + From a4132df3e541db2825134cbd81222b43c7c74525 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sat, 12 Aug 2017 07:49:55 +0200 Subject: [PATCH 30/67] fix pom (#2423) * fix spring config * fix spring config * fix spring config * minor fix * fix spring-boot module * fix pom --- spring-boot/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 3fafa6ade2..0cf7df86cd 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -253,8 +253,8 @@ - 4.3.4.RELEASE + org.baeldung.boot.DemoApplication + 4.3.4.RELEASE 2.2.1 3.1.1 3.3.7-1 From 310e89e4f04402700be4a5fa4686a9c7914ec6f6 Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Sat, 12 Aug 2017 07:59:15 +0200 Subject: [PATCH 31/67] BAEL-1035 Introduction to Eclipse Collections (#2421) * Evaluation article: Different Types of Bean Injection in Spring * added tests & changed configuration to Java-based config * removed xml config files * rename unit tests * BAEL-972 - Apache Commons Text * remove code from evaluation article * remove code from evaluation article * BAEL-972 - Apache Commons Text - added another example * BAEL-972 - Apache Commons Text - just indentation * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java - fix problems * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * fix formatting * BAEL-1033 minor refactor * BAEL-1035 Introduction to Eclipse Collections * format * BAEL-1035 Introduction to Eclipse Collections * BAEL-1035 Introduction to Eclipse Collections --- libraries/pom.xml | 2 +- .../baeldung/eclipsecollections/Student.java | 26 ++++++++++++ .../CollectPatternTest.java | 4 +- .../eclipsecollections/FlatCollectTest.java | 42 +++++++++++++++++++ .../PartitionPatternTest.java | 1 - .../baeldung/eclipsecollections/ZipTest.java | 22 ++++++++++ .../eclipsecollections/ZipWithIndexTest.java | 22 ++++++++++ 7 files changed, 115 insertions(+), 4 deletions(-) create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 490302ca29..a16a4de59d 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -515,4 +515,4 @@ 1.0 8.2.0 - + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java index 2c634a28d9..cf6c06cec0 100644 --- a/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java +++ b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java @@ -1,15 +1,25 @@ package com.baeldung.eclipsecollections; +import java.util.List; + public class Student { private String firstName; private String lastName; + private List addresses; public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } + public Student(String firstName, String lastName, List addresses) { + super(); + this.firstName = firstName; + this.lastName = lastName; + this.addresses = addresses; + } + public String getFirstName() { return this.firstName; } @@ -17,4 +27,20 @@ public class Student { public String getLastName() { return this.lastName; } + + public List getAddresses() { + return addresses; + } + + public void setAddresses(List addresses) { + this.addresses = addresses; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java index 51591cd08c..5fb63794a1 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java @@ -16,7 +16,7 @@ public class CollectPatternTest { MutableList lastNames = students.collect(Student::getLastName); - assertEquals(lastNames.get(0), "Hopkins"); - assertEquals(lastNames.get(1), "Adams"); + assertEquals("Hopkins", lastNames.get(0)); + assertEquals("Adams", lastNames.get(1)); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java new file mode 100644 index 0000000000..3d1453e557 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java @@ -0,0 +1,42 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; + +public class FlatCollectTest { + + MutableList addresses1; + MutableList addresses2; + MutableList addresses3; + MutableList addresses4; + + MutableList students; + + @Before + public void setup() { + String address1 = "73 Pacific St., Forest Hills, NY 11375"; + String address2 = "93 Bayport Ave., South Richmond Hill, NY 11419"; + String address3 = "548 Market St, San Francisco, CA 94104"; + String address4 = "8605 Santa Monica Blvd, West Hollywood, CA 90069"; + + this.addresses1 = FastList.newListWith(address1, address2); + this.addresses2 = FastList.newListWith(address3, address4); + Student student1 = new Student("John", "Hopkins", addresses1); + Student student2 = new Student("George", "Adams", addresses2); + this.addresses2 = FastList.newListWith(address3, address4); + this.students = FastList.newListWith(student1, student2); + } + + @Test + public void whenFlatCollect_thenCorrect() { + MutableList addresses = students.flatCollect(Student::getAddresses); + + assertEquals("73 Pacific St., Forest Hills, NY 11375", addresses.get(0)); + assertEquals("93 Bayport Ave., South Richmond Hill, NY 11419", addresses.get(1)); + assertEquals("548 Market St, San Francisco, CA 94104", addresses.get(2)); + assertEquals("8605 Santa Monica Blvd, West Hollywood, CA 90069", addresses.get(3)); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java index 3e52829824..4d9619817b 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java @@ -28,7 +28,6 @@ public class PartitionPatternTest { list.add(38); } - @SuppressWarnings({ "unused" }) @Test public void whenAnySatisfiesCondition_thenCorrect() { MutableList numbers = list; diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java new file mode 100644 index 0000000000..9dfab8f32d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java @@ -0,0 +1,22 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.tuple.Tuples; +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class ZipTest { + + @Test + public void whenZip_thenCorrect() { + MutableList numbers = Lists.mutable.with("1", "2", "3", "Ignored"); + MutableList cars = Lists.mutable.with("Porsche", "Volvo", "Toyota"); + MutableList> pairs = numbers.zip(cars); + + assertEquals(Tuples.pair("1", "Porsche"), pairs.get(0)); + assertEquals(Tuples.pair("2", "Volvo"), pairs.get(1)); + assertEquals(Tuples.pair("3", "Toyota"), pairs.get(2)); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java new file mode 100644 index 0000000000..3e8fe9b410 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java @@ -0,0 +1,22 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.eclipse.collections.impl.tuple.Tuples; +import org.junit.Test; + +public class ZipWithIndexTest { + + @Test + public void whenZip_thenCorrect() { + MutableList cars = FastList.newListWith("Porsche", "Volvo", "Toyota"); + MutableList> pairs = cars.zipWithIndex(); + + assertEquals(Tuples.pair("Porsche", 0), pairs.get(0)); + assertEquals(Tuples.pair("Volvo", 1), pairs.get(1)); + assertEquals(Tuples.pair("Toyota", 2), pairs.get(2)); + } +} From 9b2e8ec9f9868e490d3cf9e92ef18dfa99aa6f2f Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Sat, 12 Aug 2017 18:42:04 +0200 Subject: [PATCH 32/67] BAEL-1035 Introduction to Eclipse Collections (#2425) * Evaluation article: Different Types of Bean Injection in Spring * added tests & changed configuration to Java-based config * removed xml config files * rename unit tests * BAEL-972 - Apache Commons Text * remove code from evaluation article * remove code from evaluation article * BAEL-972 - Apache Commons Text - added another example * BAEL-972 - Apache Commons Text - just indentation * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java - fix problems * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * fix formatting * BAEL-1033 minor refactor * BAEL-1035 Introduction to Eclipse Collections * format * BAEL-1035 Introduction to Eclipse Collections * BAEL-1035 Introduction to Eclipse Collections * BAEL-1035 Introduction to Eclipse Collections * cleanup * cleanup --- .../AllSatisfyPatternTest.java | 10 +------ .../AnySatisfyPatternTest.java | 10 +------ .../CollectPatternTest.java | 7 +++-- .../ConvertContainerToAnotherTest.java | 12 ++++---- .../eclipsecollections/DetectPatternTest.java | 16 +++-------- .../eclipsecollections/FlatCollectTest.java | 18 ++++++++---- .../ForEachPatternTest.java | 7 ++--- .../eclipsecollections/LazyIterationTest.java | 8 ++---- .../PartitionPatternTest.java | 28 ++++--------------- .../eclipsecollections/RejectPatternTest.java | 23 +++++---------- .../eclipsecollections/SelectPatternTest.java | 22 ++++----------- .../baeldung/eclipsecollections/ZipTest.java | 20 ++++++++++--- .../eclipsecollections/ZipWithIndexTest.java | 21 ++++++++++---- 13 files changed, 84 insertions(+), 118 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java index 1ea10317c7..ee369fc75b 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java @@ -14,15 +14,7 @@ public class AllSatisfyPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java index 58f8ad40af..a3314ebee6 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java @@ -14,15 +14,7 @@ public class AnySatisfyPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java index 5fb63794a1..ee384c2f9d 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java @@ -2,7 +2,8 @@ package com.baeldung.eclipsecollections; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; + +import org.assertj.core.api.Assertions; import org.junit.Test; public class CollectPatternTest { @@ -16,7 +17,7 @@ public class CollectPatternTest { MutableList lastNames = students.collect(Student::getLastName); - assertEquals("Hopkins", lastNames.get(0)); - assertEquals("Adams", lastNames.get(1)); + Assertions.assertThat(lastNames) + .containsExactly("Hopkins", "Adams"); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java index b538abfa6e..4655431872 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java @@ -1,9 +1,8 @@ package com.baeldung.eclipsecollections; -import static org.junit.Assert.assertTrue; - +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; import org.junit.Test; public class ConvertContainerToAnotherTest { @@ -12,9 +11,8 @@ public class ConvertContainerToAnotherTest { @Test public void whenConvertContainerToAnother_thenCorrect() { MutableList cars = (MutableList) ConvertContainerToAnother.convertToList(); - - assertTrue(cars.anySatisfy(Predicates.equal("Toyota"))); - assertTrue(cars.anySatisfy(Predicates.equal("Mercedes"))); - assertTrue(cars.anySatisfy(Predicates.equal("Volkswagen"))); + + Assertions.assertThat(cars) + .containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java index fc643f2840..c5b5e1c412 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java @@ -1,10 +1,9 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; - import org.junit.Before; import org.junit.Test; @@ -14,21 +13,14 @@ public class DetectPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test public void whenDetect_thenCorrect() { Integer result = list.detect(Predicates.greaterThan(30)); - assertEquals((int) result, 41); + Assertions.assertThat(result) + .isEqualTo(41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java index 3d1453e557..021c72e91e 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java @@ -1,8 +1,12 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + import org.junit.Before; import org.junit.Test; @@ -13,6 +17,7 @@ public class FlatCollectTest { MutableList addresses3; MutableList addresses4; + List expectedAddresses; MutableList students; @Before @@ -28,15 +33,18 @@ public class FlatCollectTest { Student student2 = new Student("George", "Adams", addresses2); this.addresses2 = FastList.newListWith(address3, address4); this.students = FastList.newListWith(student1, student2); + this.expectedAddresses = new ArrayList<>(); + this.expectedAddresses.add("73 Pacific St., Forest Hills, NY 11375"); + this.expectedAddresses.add("93 Bayport Ave., South Richmond Hill, NY 11419"); + this.expectedAddresses.add("548 Market St, San Francisco, CA 94104"); + this.expectedAddresses.add("8605 Santa Monica Blvd, West Hollywood, CA 90069"); } @Test public void whenFlatCollect_thenCorrect() { MutableList addresses = students.flatCollect(Student::getAddresses); - assertEquals("73 Pacific St., Forest Hills, NY 11375", addresses.get(0)); - assertEquals("93 Bayport Ave., South Richmond Hill, NY 11419", addresses.get(1)); - assertEquals("548 Market St, San Francisco, CA 94104", addresses.get(2)); - assertEquals("8605 Santa Monica Blvd, West Hollywood, CA 90069", addresses.get(3)); + Assertions.assertThat(addresses) + .containsExactlyElementsOf(this.expectedAddresses); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java index e8d93a2af6..8cea575222 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java @@ -1,13 +1,10 @@ package com.baeldung.eclipsecollections; -import org.eclipse.collections.api.block.procedure.Procedure; +import static org.junit.Assert.assertEquals; + import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.impl.map.mutable.UnifiedMap; import org.eclipse.collections.impl.tuple.Tuples; -import static org.junit.Assert.assertEquals; - -import java.util.Map; - import org.junit.Test; public class ForEachPatternTest { diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java index 8fe1286d41..9c216ecc87 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java @@ -1,10 +1,9 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.LazyIterable; import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.factory.Lists; -import static org.junit.Assert.assertTrue; import org.junit.Test; public class LazyIterationTest { @@ -19,8 +18,7 @@ public class LazyIterationTest { LazyIterable lazyStudents = students.asLazy(); LazyIterable lastNames = lazyStudents.collect(Student::getLastName); - assertTrue(lastNames.anySatisfy(Predicates.equal("Hopkins"))); - assertTrue(lastNames.anySatisfy(Predicates.equal("Adams"))); - assertTrue(lastNames.anySatisfy(Predicates.equal("Rodriguez"))); + Assertions.assertThat(lastNames) + .containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez")); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java index 4d9619817b..c055413cd9 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java @@ -1,12 +1,9 @@ package com.baeldung.eclipsecollections; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.block.predicate.Predicate; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.partition.list.PartitionMutableList; -import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.list.mutable.FastList; import org.junit.Before; import org.junit.Test; @@ -17,15 +14,7 @@ public class PartitionPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test @@ -47,14 +36,9 @@ public class PartitionPatternTest { MutableList smallerThanThirty = partitionedFolks.getRejected() .sortThis(); - assertEquals(1, (int) smallerThanThirty.getFirst()); - assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(5))); - assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(8))); - assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(17))); - assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(23))); - - assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(31))); - assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(38))); - assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(41))); + Assertions.assertThat(smallerThanThirty) + .containsExactly(1, 5, 8, 17, 23); + Assertions.assertThat(greaterThanThirty) + .containsExactly(31, 38, 41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java index 044a8203d6..1666c86333 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java @@ -1,27 +1,21 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; public class RejectPatternTest { MutableList list; + MutableList expectedList; @Before - public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + public void setup() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + this.expectedList = FastList.newListWith(1, 5, 8, 17, 23); } @Test @@ -29,10 +23,7 @@ public class RejectPatternTest { MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)) .sortThis(); - assertEquals(1, (int) notGreaterThanThirty.getFirst()); - assertEquals(5, (int) notGreaterThanThirty.get(1)); - assertEquals(8, (int) notGreaterThanThirty.get(2)); - assertEquals(17, (int) notGreaterThanThirty.get(3)); - assertEquals(23, (int) notGreaterThanThirty.getLast()); + Assertions.assertThat(notGreaterThanThirty) + .containsExactlyElementsOf(this.expectedList); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java index 20c94f6028..d79c864fc5 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java @@ -1,9 +1,9 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; @@ -13,15 +13,7 @@ public class SelectPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test @@ -29,9 +21,8 @@ public class SelectPatternTest { MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)) .sortThis(); - assertEquals(31, (int) greaterThanThirty.getFirst()); - assertEquals(38, (int) greaterThanThirty.get(1)); - assertEquals(41, (int) greaterThanThirty.getLast()); + Assertions.assertThat(greaterThanThirty) + .containsExactly(31, 38, 41); } @SuppressWarnings("rawtypes") @@ -45,8 +36,7 @@ public class SelectPatternTest { public void givenListwhenSelectUsingLambda_thenCorrect() { MutableList greaterThanThirty = selectUsingLambda(); - assertEquals(31, (int) greaterThanThirty.getFirst()); - assertEquals(38, (int) greaterThanThirty.get(1)); - assertEquals(41, (int) greaterThanThirty.getLast()); + Assertions.assertThat(greaterThanThirty) + .containsExactly(31, 38, 41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java index 9dfab8f32d..29f0c23954 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java @@ -4,19 +4,31 @@ import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.tuple.Tuples; -import static org.junit.Assert.assertEquals; + +import org.assertj.core.api.Assertions; +import org.junit.Before; import org.junit.Test; public class ZipTest { + MutableList> expectedPairs; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + Pair pair1 = Tuples.pair("1", "Porsche"); + Pair pair2 = Tuples.pair("2", "Volvo"); + Pair pair3 = Tuples.pair("3", "Toyota"); + expectedPairs = Lists.mutable.of(pair1, pair2, pair3); + } + @Test public void whenZip_thenCorrect() { MutableList numbers = Lists.mutable.with("1", "2", "3", "Ignored"); MutableList cars = Lists.mutable.with("Porsche", "Volvo", "Toyota"); MutableList> pairs = numbers.zip(cars); - assertEquals(Tuples.pair("1", "Porsche"), pairs.get(0)); - assertEquals(Tuples.pair("2", "Volvo"), pairs.get(1)); - assertEquals(Tuples.pair("3", "Toyota"), pairs.get(2)); + Assertions.assertThat(pairs) + .containsExactlyElementsOf(this.expectedPairs); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java index 3e8fe9b410..a2d8be44ec 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java @@ -1,22 +1,33 @@ package com.baeldung.eclipsecollections; -import static org.junit.Assert.assertEquals; - +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.list.mutable.FastList; import org.eclipse.collections.impl.tuple.Tuples; +import org.junit.Before; import org.junit.Test; public class ZipWithIndexTest { + MutableList> expectedPairs; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + Pair pair1 = Tuples.pair("Porsche", 0); + Pair pair2 = Tuples.pair("Volvo", 1); + Pair pair3 = Tuples.pair("Toyota", 2); + expectedPairs = Lists.mutable.of(pair1, pair2, pair3); + } + @Test public void whenZip_thenCorrect() { MutableList cars = FastList.newListWith("Porsche", "Volvo", "Toyota"); MutableList> pairs = cars.zipWithIndex(); - assertEquals(Tuples.pair("Porsche", 0), pairs.get(0)); - assertEquals(Tuples.pair("Volvo", 1), pairs.get(1)); - assertEquals(Tuples.pair("Toyota", 2), pairs.get(2)); + Assertions.assertThat(pairs) + .containsExactlyElementsOf(this.expectedPairs); } } From e13204ca96a30cc5db83cd248288d16d95c9ef4a Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Sat, 12 Aug 2017 23:02:09 -0300 Subject: [PATCH 33/67] Introduction to EJB JNDI Lookup on WildFly Application Server - Alejandro Gervasio | alejandro.gervasio@gmail.com (#2417) * Initial Commit * jboss-ejb-client.properties file * Updated jboss-ejb-client.properties file --- .../resources/jboss-ejb-client.properties | 8 ++-- .../application/TextApplication.java | 42 +++++++++++++++++++ .../resources/jboss-ejb-client.properties | 8 ++++ .../application/TextApplicationTest.java | 31 ++++++++++++++ .../baeldung/ejbmodule/TextProcessorBean.java | 10 +++++ .../ejbmodule/TextProcessorRemote.java | 9 ++++ .../ejbmodule/TextProcessorBeanTest.java | 12 ++++++ 7 files changed, 116 insertions(+), 4 deletions(-) create mode 100644 ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java create mode 100644 ejb/ejbclient/src/main/resources/jboss-ejb-client.properties create mode 100644 ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java create mode 100644 ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java create mode 100644 ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java create mode 100644 ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java diff --git a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties index a01a675e44..67533b7825 100755 --- a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties +++ b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties @@ -1,8 +1,8 @@ +endpoint.name=client-endpoint +remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false remote.connections=default remote.connection.default.host=127.0.0.1 remote.connection.default.port=8080 remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false -remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false -remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER} -remote.connection.default.username=testUser -remote.connection.default.password=admin1234! +remote.connection.default.username=myusername +remote.connection.default.password=mypassword \ No newline at end of file diff --git a/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java b/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java new file mode 100644 index 0000000000..b65c21100d --- /dev/null +++ b/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java @@ -0,0 +1,42 @@ +package com.baeldung.ejbclient.application; + +import com.baeldung.ejbmodule.TextProcessorBean; +import com.baeldung.ejbmodule.TextProcessorRemote; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import java.util.Properties; + +public class TextApplication { + + public static void main(String[] args) throws NamingException { + TextProcessorRemote textProcessor = EJBFactory.createTextProcessorBeanFromJNDI("ejb:"); + System.out.print(textProcessor.processText("sample text")); + } + + private static class EJBFactory { + + private static TextProcessorRemote createTextProcessorBeanFromJNDI(String namespace) throws NamingException { + return lookupTextProcessorBean(namespace); + } + + private static TextProcessorRemote lookupTextProcessorBean(String namespace) throws NamingException { + Context ctx = createInitialContext(); + final String appName = ""; + final String moduleName = "EJBModule"; + final String distinctName = ""; + final String beanName = TextProcessorBean.class.getSimpleName(); + final String viewClassName = TextProcessorRemote.class.getName(); + return (TextProcessorRemote) ctx.lookup(namespace + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName); + } + + private static Context createInitialContext() throws NamingException { + Properties jndiProperties = new Properties(); + jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); + jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); + jndiProperties.put(Context.PROVIDER_URL, "http-remoting://localhost:8080"); + jndiProperties.put("jboss.naming.client.ejb.context", true); + return new InitialContext(jndiProperties); + } + } +} diff --git a/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties b/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties new file mode 100644 index 0000000000..67533b7825 --- /dev/null +++ b/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties @@ -0,0 +1,8 @@ +endpoint.name=client-endpoint +remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false +remote.connections=default +remote.connection.default.host=127.0.0.1 +remote.connection.default.port=8080 +remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false +remote.connection.default.username=myusername +remote.connection.default.password=mypassword \ No newline at end of file diff --git a/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java b/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java new file mode 100644 index 0000000000..947c72d0b0 --- /dev/null +++ b/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.ejbclient.application; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.naming.NamingException; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import static org.junit.Assert.*; + +public class TextApplicationTest { + + private static ByteArrayOutputStream outContent; + + @BeforeClass + public static void setUpPrintStreamInstance() { + outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + } + + @AfterClass + public static void tearDownByteArrayOutputStream() { + outContent = null; + } + + @Test + public void givenInputString_whenCompareTtoStringPrintedToConsole_thenSuccessful() throws NamingException { + TextApplication.main(new String[]{}); + assertEquals("SAMPLE TEXT", outContent.toString()); + } +} \ No newline at end of file diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java new file mode 100644 index 0000000000..dc0db5fc53 --- /dev/null +++ b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java @@ -0,0 +1,10 @@ +package com.baeldung.ejbmodule; + +import javax.ejb.Stateless; + +@Stateless +public class TextProcessorBean implements TextProcessorRemote { + public String processText(String text) { + return text.toUpperCase(); + } +} diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java new file mode 100644 index 0000000000..680d8f4e10 --- /dev/null +++ b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java @@ -0,0 +1,9 @@ +package com.baeldung.ejbmodule; + +import javax.ejb.Remote; + +@Remote +public interface TextProcessorRemote { + + String processText(String text); +} \ No newline at end of file diff --git a/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java b/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java new file mode 100644 index 0000000000..d8693420d4 --- /dev/null +++ b/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java @@ -0,0 +1,12 @@ +package com.baeldung.ejbmodule; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class TextProcessorBeanTest { + @Test + public void givenInputString_whenComparedToStringParsedByBean_thenSuccessful() { + TextProcessorBean textProcessor = new TextProcessorBean(); + assertEquals("TEST", textProcessor.processText("test")); + } +} \ No newline at end of file From 299432df1178fccc62772ef60a6116ec68153d51 Mon Sep 17 00:00:00 2001 From: Mohamed Sanaulla Date: Sun, 13 Aug 2017 21:06:42 +0300 Subject: [PATCH 34/67] updating Java9ObjectsAPIUnitTest (#2430) * updating Java9ObjectsAPIUnitTest * some more changes to test --- .../language/Java9ObjectsAPIUnitTest.java | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java index 93abe4e185..93579019a1 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java @@ -10,17 +10,27 @@ import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.assertThat; public class Java9ObjectsAPIUnitTest { - + + private List aMethodReturningNullList(){ + return null; + } + @Test public void givenNullObject_whenRequireNonNullElse_thenElse(){ - assertThat(Objects.requireNonNullElse(null, Collections.EMPTY_LIST), - is(Collections.EMPTY_LIST)); + List aList = Objects.requireNonNullElse( + aMethodReturningNullList(), Collections.EMPTY_LIST); + assertThat(aList, is(Collections.EMPTY_LIST)); + } + + private List aMethodReturningNonNullList(){ + return List.of("item1", "item2"); } @Test public void givenObject_whenRequireNonNullElse_thenObject(){ - assertThat(Objects.requireNonNullElse(List.of("item1", "item2"), - Collections.EMPTY_LIST), is(List.of("item1", "item2"))); + List aList = Objects.requireNonNullElse( + aMethodReturningNonNullList(), Collections.EMPTY_LIST); + assertThat(aList, is(List.of("item1", "item2"))); } @Test(expected = NullPointerException.class) @@ -30,8 +40,8 @@ public class Java9ObjectsAPIUnitTest { @Test public void givenObject_whenRequireNonNullElseGet_thenObject(){ - assertThat(Objects.requireNonNullElseGet(null, List::of), - is(List.of())); + List aList = Objects.requireNonNullElseGet(null, List::of); + assertThat(aList, is(List.of())); } @Test From 290e759d4ae6599d690c56a11c20f49cd8408162 Mon Sep 17 00:00:00 2001 From: deep20jain Date: Mon, 14 Aug 2017 07:41:49 +0530 Subject: [PATCH 35/67] BAEL1053 - deep20jain@gmail.com - Broadcasting and Multicasting in Java (#2368) * Adding code for java broadcasting and multicasting * Changing multicast ip * Adding code to iterate thorugh all network interfaces * Formatting again and fixing bug * Applying formatting rules on all classes * Fixing formatting --- .../udp/broadcast/BroadcastingClient.java | 85 +++++++++++++++++++ .../udp/broadcast/BroadcastingEchoServer.java | 44 ++++++++++ .../udp/multicast/MulticastEchoServer.java | 41 +++++++++ .../udp/multicast/MulticastingClient.java | 53 ++++++++++++ .../broadcast/BroadcastIntegrationTest.java | 39 +++++++++ .../multicast/MulticastIntegrationTest.java | 39 +++++++++ 6 files changed, 301 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java create mode 100644 core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java create mode 100644 core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java create mode 100644 core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java create mode 100644 core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java new file mode 100644 index 0000000000..3162ff0b1e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java @@ -0,0 +1,85 @@ +package com.baeldung.java.networking.udp.broadcast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.stream.Collectors; + +public class BroadcastingClient { + private DatagramSocket socket; + private InetAddress address; + private int expectedServerCount; + private byte[] buf; + + public BroadcastingClient(int expectedServerCount) throws Exception { + this.expectedServerCount = expectedServerCount; + this.address = InetAddress.getByName("255.255.255.255"); + } + + public int discoverServers(String msg) throws IOException { + initializeSocketForBroadcasting(); + copyMessageOnBuffer(msg); + + // When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value. + broadcastPacket(address); + + return receivePackets(); + } + + List listAllBroadcastAddresses() throws SocketException { + List broadcastList = new ArrayList<>(); + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces.hasMoreElements()) { + NetworkInterface networkInterface = interfaces.nextElement(); + + if (networkInterface.isLoopback() || !networkInterface.isUp()) { + continue; + } + + broadcastList.addAll(networkInterface.getInterfaceAddresses() + .stream() + .filter(address -> address.getBroadcast() != null) + .map(address -> address.getBroadcast()) + .collect(Collectors.toList())); + } + return broadcastList; + } + + private void initializeSocketForBroadcasting() throws SocketException { + socket = new DatagramSocket(); + socket.setBroadcast(true); + } + + private void copyMessageOnBuffer(String msg) { + buf = msg.getBytes(); + } + + private void broadcastPacket(InetAddress address) throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); + socket.send(packet); + } + + private int receivePackets() throws IOException { + int serversDiscovered = 0; + while (serversDiscovered != expectedServerCount) { + receivePacket(); + serversDiscovered++; + } + return serversDiscovered; + } + + private void receivePacket() throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + } + + public void close() { + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java b/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java new file mode 100644 index 0000000000..afc50e1f40 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java @@ -0,0 +1,44 @@ +package com.baeldung.java.networking.udp.broadcast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.InetSocketAddress; + +public class BroadcastingEchoServer extends Thread { + + protected DatagramSocket socket = null; + protected boolean running; + protected byte[] buf = new byte[256]; + + public BroadcastingEchoServer() throws IOException { + socket = new DatagramSocket(null); + socket.setReuseAddress(true); + socket.bind(new InetSocketAddress(4445)); + } + + public void run() { + running = true; + + while (running) { + try { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + InetAddress address = packet.getAddress(); + int port = packet.getPort(); + packet = new DatagramPacket(buf, buf.length, address, port); + String received = new String(packet.getData(), 0, packet.getLength()); + if (received.equals("end")) { + running = false; + continue; + } + socket.send(packet); + } catch (IOException e) { + e.printStackTrace(); + running = false; + } + } + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java b/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java new file mode 100644 index 0000000000..cae5c27d95 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java @@ -0,0 +1,41 @@ +package com.baeldung.java.networking.udp.multicast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; + +public class MulticastEchoServer extends Thread { + + protected MulticastSocket socket = null; + protected byte[] buf = new byte[256]; + protected InetAddress group = null; + + public MulticastEchoServer() throws IOException { + socket = new MulticastSocket(4446); + socket.setReuseAddress(true); + group = InetAddress.getByName("230.0.0.0"); + socket.joinGroup(group); + } + + public void run() { + try { + while (true) { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + InetAddress address = packet.getAddress(); + int port = packet.getPort(); + packet = new DatagramPacket(buf, buf.length, address, port); + String received = new String(packet.getData(), 0, packet.getLength()); + if (received.equals("end")) { + break; + } + socket.send(packet); + } + socket.leaveGroup(group); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java new file mode 100644 index 0000000000..4e425055fe --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java @@ -0,0 +1,53 @@ +package com.baeldung.java.networking.udp.multicast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +public class MulticastingClient { + private DatagramSocket socket; + private InetAddress group; + private int expectedServerCount; + private byte[] buf; + + public MulticastingClient(int expectedServerCount) throws Exception { + this.expectedServerCount = expectedServerCount; + this.socket = new DatagramSocket(); + this.group = InetAddress.getByName("230.0.0.0"); + } + + public int discoverServers(String msg) throws IOException { + copyMessageOnBuffer(msg); + multicastPacket(); + + return receivePackets(); + } + + private void copyMessageOnBuffer(String msg) { + buf = msg.getBytes(); + } + + private void multicastPacket() throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446); + socket.send(packet); + } + + private int receivePackets() throws IOException { + int serversDiscovered = 0; + while (serversDiscovered != expectedServerCount) { + receivePacket(); + serversDiscovered++; + } + return serversDiscovered; + } + + private void receivePacket() throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + } + + public void close() { + socket.close(); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java new file mode 100644 index 0000000000..e3ffbcc052 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.java.networking.udp.broadcast; + +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class BroadcastIntegrationTest { + private BroadcastingClient client; + + @Test + public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception { + int expectedServers = 4; + initializeForExpectedServers(expectedServers); + + int serversDiscovered = client.discoverServers("hello server"); + assertEquals(expectedServers, serversDiscovered); + } + + private void initializeForExpectedServers(int expectedServers) throws Exception { + for (int i = 0; i < expectedServers; i++) { + new BroadcastingEchoServer().start(); + } + + client = new BroadcastingClient(expectedServers); + } + + @After + public void tearDown() throws IOException { + stopEchoServer(); + client.close(); + } + + private void stopEchoServer() throws IOException { + client.discoverServers("end"); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java new file mode 100644 index 0000000000..26c0704b01 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.java.networking.udp.multicast; + +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class MulticastIntegrationTest { + private MulticastingClient client; + + @Test + public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception { + int expectedServers = 4; + initializeForExpectedServers(expectedServers); + + int serversDiscovered = client.discoverServers("hello server"); + assertEquals(expectedServers, serversDiscovered); + } + + private void initializeForExpectedServers(int expectedServers) throws Exception { + for (int i = 0; i < expectedServers; i++) { + new MulticastEchoServer().start(); + } + + client = new MulticastingClient(expectedServers); + } + + @After + public void tearDown() throws IOException { + stopEchoServer(); + client.close(); + } + + private void stopEchoServer() throws IOException { + client.discoverServers("end"); + } +} From 87cdf5d9dd2891eb97c08b96cc3b96e632186c52 Mon Sep 17 00:00:00 2001 From: mokhan Date: Mon, 14 Aug 2017 11:51:46 +0530 Subject: [PATCH 36/67] Spring Data Ldap --- spring-ldap/pom.xml | 246 +++++++++--------- .../baeldung/ldap/data/repository/User.java | 55 ++++ .../ldap/data/repository/UserRepository.java | 17 ++ .../ldap/data/service/LdapClient.java | 83 ++++++ .../ldap/data/service/UserService.java | 66 +++++ .../baeldung/ldap/javaconfig/AppConfig.java | 2 + .../ldap/client/LdapDataRepositoryTest.java | 68 +++++ .../baeldung/ldap/javaconfig/TestConfig.java | 2 + 8 files changed, 422 insertions(+), 117 deletions(-) create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java create mode 100644 spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index 16d4879f10..f000b07a09 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -1,131 +1,143 @@ - 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-ldap - 0.1-SNAPSHOT - jar + com.baeldung + spring-ldap + 0.1-SNAPSHOT + jar - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - 2.3.1.RELEASE - 4.3.6.RELEASE - 1.5.5 - 0.9.15 - + + 2.3.1.RELEASE + 4.3.6.RELEASE + 1.5.5 + 0.9.15 + - - spring-ldap - + + spring-ldap + - + - - org.springframework.ldap - spring-ldap-core - ${spring-ldap.version} - - - commons-logging - commons-logging - - - + + org.springframework.ldap + spring-ldap-core + ${spring-ldap.version} + + + commons-logging + commons-logging + + + - - org.springframework - spring-context - ${spring-context.version} - + + org.springframework + spring-context + ${spring-context.version} + - - - org.springframework.ldap - spring-ldap-test - ${spring-ldap.version} - test - - - commons-logging - commons-logging - - - + + + org.springframework.ldap + spring-ldap-test + ${spring-ldap.version} + test + + + commons-logging + commons-logging + + + - - - org.apache.directory.server - apacheds-core - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-core-entry - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-shared - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-ldap - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-server-jndi - ${apacheds.version} - test - - - org.apache.directory.shared - shared-ldap - ${shared-ldap.version} - test - + + + org.apache.directory.server + apacheds-core + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-core-entry + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-shared + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-ldap + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-server-jndi + ${apacheds.version} + test + + + org.apache.directory.shared + shared-ldap + ${shared-ldap.version} + test + - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - - - **/*LiveTest.java - - - - - - - - - + + + org.springframework.data + spring-data-ldap + 1.0.6.RELEASE + + + org.springframework.data + spring-data-jpa + 1.11.6.RELEASE + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + + + \ No newline at end of file diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java new file mode 100644 index 0000000000..726fa53b02 --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java @@ -0,0 +1,55 @@ +package com.baeldung.ldap.data.repository; + +import javax.naming.Name; + +import org.springframework.ldap.odm.annotations.Attribute; +import org.springframework.ldap.odm.annotations.Entry; +import org.springframework.ldap.odm.annotations.Id; + +@Entry(base = "ou=users", objectClasses = { "person", "inetOrgPerson", "top" }) +public class User { + + @Id + private Name id; + + private @Attribute(name = "cn") String username; + private @Attribute(name = "sn") String password; + + public User() { + } + + public User(String username, String password) { + this.username = username; + this.password = password; + } + + public Name getId() { + return id; + } + + public void setId(Name id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return username; + } + +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java new file mode 100644 index 0000000000..9140616eee --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.ldap.data.repository; + +import java.util.List; + +import org.springframework.data.ldap.repository.LdapRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends LdapRepository { + + public User findByUsername(String username); + + public User findByUsernameAndPassword(String username, String password); + + public List findByUsernameLikeIgnoreCase(String username); + +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java new file mode 100644 index 0000000000..753c5f6c34 --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java @@ -0,0 +1,83 @@ +package com.baeldung.ldap.data.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.ldap.core.*; +import org.springframework.ldap.support.LdapNameBuilder; + +import javax.naming.Name; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.List; + +public class LdapClient { + + @Autowired + private Environment env; + + @Autowired + private ContextSource contextSource; + + @Autowired + private LdapTemplate ldapTemplate; + + public void authenticate(final String username, final String password) { + contextSource.getContext("cn=" + username + ",ou=users," + env.getRequiredProperty("ldap.partitionSuffix"), password); + } + + public List search(final String username) { + return ldapTemplate.search( + "ou=users", + "cn=" + username, + (AttributesMapper) attrs -> (String) attrs + .get("cn") + .get()); + } + + public void create(final String username, final String password) { + Name dn = LdapNameBuilder + .newInstance() + .add("ou", "users") + .add("cn", username) + .build(); + DirContextAdapter context = new DirContextAdapter(dn); + + context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValue("cn", username); + context.setAttributeValue("sn", username); + context.setAttributeValue("userPassword", digestSHA(password)); + + ldapTemplate.bind(context); + } + + public void modify(final String username, final String password) { + Name dn = LdapNameBuilder + .newInstance() + .add("ou", "users") + .add("cn", username) + .build(); + DirContextOperations context = ldapTemplate.lookupContext(dn); + + context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValue("cn", username); + context.setAttributeValue("sn", username); + context.setAttributeValue("userPassword", digestSHA(password)); + + ldapTemplate.modifyAttributes(context); + } + + private String digestSHA(final String password) { + String base64; + try { + MessageDigest digest = MessageDigest.getInstance("SHA"); + digest.update(password.getBytes()); + base64 = Base64 + .getEncoder() + .encodeToString(digest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return "{SHA}" + base64; + } +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java new file mode 100644 index 0000000000..39d4df1cd6 --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java @@ -0,0 +1,66 @@ +package com.baeldung.ldap.data.service; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.stereotype.Service; + +import com.baeldung.ldap.data.repository.User; +import com.baeldung.ldap.data.repository.UserRepository; + +@Service +public class UserService { + + @Autowired + private UserRepository userRepository; + + public Boolean authenticate(final String username, final String password) { + User user = userRepository.findByUsernameAndPassword(username, password); + return user != null ? true : false; + } + + public List search(final String username) { + List userList = userRepository.findByUsernameLikeIgnoreCase(username); + List users = null; + if (null != userList) { + users = new ArrayList(); + for (User user : userList) { + users.add(user.getUsername()); + } + } + return users; + + } + + public void create(final String username, final String password) { + User newUser = new User(username,digestSHA(password)); + newUser.setId(LdapUtils.emptyLdapName()); + userRepository.save(newUser); + + } + + public void modify(final String username, final String password) { + User user = userRepository.findByUsername(username); + user.setPassword(password); + userRepository.save(user); + + } + + private String digestSHA(final String password) { + String base64; + try { + MessageDigest digest = MessageDigest.getInstance("SHA"); + digest.update(password.getBytes()); + base64 = Base64.getEncoder() + .encodeToString(digest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return "{SHA}" + base64; + } +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java index 8572e5d1be..9330da7ab7 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java @@ -7,6 +7,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; +import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; @@ -16,6 +17,7 @@ import com.baeldung.ldap.client.LdapClient; @PropertySource("classpath:application.properties") @ComponentScan(basePackages = { "com.baeldung.ldap.*" }) @Profile("default") +@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") public class AppConfig { @Autowired diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java new file mode 100644 index 0000000000..8460fb3eb9 --- /dev/null +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java @@ -0,0 +1,68 @@ +package com.baeldung.ldap.client; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.ldap.data.service.UserService; +import com.baeldung.ldap.javaconfig.TestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ActiveProfiles("testlive") +@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class LdapDataRepositoryTest { + + private static final String USER2 = "TEST02"; + private static final String USER3 = "TEST03"; + private static final String USER4 = "TEST04"; + + private static final String USER2_PWD = "TEST02"; + private static final String USER3_PWD = "TEST03"; + private static final String USER4_PWD = "TEST04"; + + private static final String SEARCH_STRING = "TEST*"; + + @Autowired + private UserService userService; + + @Test + public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() { + Boolean isValid = userService.authenticate(USER3, USER3_PWD); + assertEquals(true, isValid); + } + + @Test + public void givenLdapClient_whenIncorrectCredentials_thenFailedLogin() { + Boolean isValid = userService.authenticate(USER3, USER2_PWD); + assertEquals(false, isValid); + } + + @Test + public void givenLdapClient_whenCorrectSearchFilter_thenEntriesReturned() { + List userList = userService.search(SEARCH_STRING); + assertThat(userList, Matchers.containsInAnyOrder(USER2, USER3)); + } + + @Test + public void givenLdapClientNotExists_whenDataProvided_thenNewUserCreated() { + userService.create(USER4, USER4_PWD); + userService.authenticate(USER4, USER4_PWD); + } + + @Test + public void givenLdapClientExists_whenDataProvided_thenExistingUserModified() { + userService.modify(USER2, USER3_PWD); + userService.authenticate(USER2, USER3_PWD); + } + +} diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java index e2968e977c..0752262159 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java @@ -8,6 +8,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; +import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.test.TestContextSourceFactoryBean; @@ -17,6 +18,7 @@ import com.baeldung.ldap.client.LdapClient; @Configuration @PropertySource("classpath:test_application.properties") @ComponentScan(basePackages = { "com.baeldung.ldap.*" }) +@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") @Profile("testlive") public class TestConfig { @Autowired From 43357b0809a079381c9980149236dc22af4ce19a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 14 Aug 2017 11:00:51 +0200 Subject: [PATCH 37/67] Partitioner Refactor (#2434) * Refactor Batch * Refactor Batch --- .../{spring_batch_intro => batch}/App.java | 2 +- .../SpringBatchConfig.java | 20 +++---- .../SpringConfig.java | 2 +- .../model/Transaction.java | 2 +- .../CustomMultiResourcePartitioner.java | 2 +- .../SpringbatchPartitionConfig.java | 57 +++++++++---------- .../SpringbatchPartitionerApp.java | 2 +- .../service/CustomItemProcessor.java | 4 +- .../service/RecordFieldSetMapper.java | 4 +- .../src/main/resources/spring-batch-intro.xml | 6 +- 10 files changed, 49 insertions(+), 52 deletions(-) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/App.java (96%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/SpringBatchConfig.java (85%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/SpringConfig.java (98%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/model/Transaction.java (96%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/partitioner/CustomMultiResourcePartitioner.java (97%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/partitioner/SpringbatchPartitionConfig.java (84%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/partitioner/SpringbatchPartitionerApp.java (95%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/service/CustomItemProcessor.java (71%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/service/RecordFieldSetMapper.java (91%) diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch/src/main/java/org/baeldung/batch/App.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java rename to spring-batch/src/main/java/org/baeldung/batch/App.java index 2ce4dae6e6..cea4e8d486 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch/src/main/java/org/baeldung/batch/App.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java similarity index 85% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java index 9973005c7c..7b19935cc8 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java @@ -1,11 +1,8 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; -import java.net.MalformedURLException; -import java.text.ParseException; - -import org.baeldung.spring_batch_intro.model.Transaction; -import org.baeldung.spring_batch_intro.service.CustomItemProcessor; -import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.baeldung.batch.model.Transaction; +import org.baeldung.batch.service.CustomItemProcessor; +import org.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; @@ -26,6 +23,9 @@ import org.springframework.core.io.Resource; import org.springframework.oxm.Marshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import java.net.MalformedURLException; +import java.text.ParseException; + public class SpringBatchConfig { @Autowired private JobBuilderFactory jobs; @@ -43,7 +43,7 @@ public class SpringBatchConfig { public ItemReader itemReader() throws UnexpectedInputException, ParseException { FlatFileItemReader reader = new FlatFileItemReader(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = { "username", "userid", "transactiondate", "amount" }; + String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(inputCsv); DefaultLineMapper lineMapper = new DefaultLineMapper(); @@ -71,13 +71,13 @@ public class SpringBatchConfig { @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean protected Step step1(ItemReader reader, ItemProcessor processor, ItemWriter writer) { - return steps.get("step1"). chunk(10).reader(reader).processor(processor).writer(writer).build(); + return steps.get("step1").chunk(10).reader(reader).processor(processor).writer(writer).build(); } @Bean(name = "firstBatchJob") diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java index ed7d302047..35abcb2d16 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; import java.net.MalformedURLException; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java rename to spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java index 3b2b9610f2..0ce3a413ab 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java +++ b/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro.model; +package org.baeldung.batch.model; import java.util.Date; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java similarity index 97% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java rename to spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java index 4cae69efbd..667e013c35 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.baeldung.spring_batch_intro.partitioner; +package org.baeldung.batch.partitioner; import java.util.HashMap; import java.util.Map; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java similarity index 84% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java index fe8339a8b4..ad3aee4a2e 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java @@ -1,13 +1,7 @@ -package org.baeldung.spring_batch_intro.partitioner; +package org.baeldung.batch.partitioner; -import java.io.IOException; -import java.net.MalformedURLException; -import java.text.ParseException; - -import javax.sql.DataSource; - -import org.baeldung.spring_batch_intro.model.Transaction; -import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.baeldung.batch.model.Transaction; +import org.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; @@ -33,7 +27,6 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.task.TaskExecutor; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.oxm.Marshaller; @@ -41,6 +34,11 @@ import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; +import javax.sql.DataSource; +import java.io.IOException; +import java.net.MalformedURLException; +import java.text.ParseException; + @Configuration @EnableBatchProcessing public class SpringbatchPartitionConfig { @@ -57,26 +55,26 @@ public class SpringbatchPartitionConfig { @Bean(name = "partitionerJob") public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException { return jobs.get("partitionerJob") - .start(partitionStep()) - .build(); + .start(partitionStep()) + .build(); } @Bean public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException { return steps.get("partitionStep") - .partitioner("slaveStep", partitioner()) - .step(slaveStep()) - .taskExecutor(taskExecutor()) - .build(); + .partitioner("slaveStep", partitioner()) + .step(slaveStep()) + .taskExecutor(taskExecutor()) + .build(); } @Bean public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException { return steps.get("slaveStep") - . chunk(1) - .reader(itemReader(null)) - .writer(itemWriter(marshaller(), null)) - .build(); + .chunk(1) + .reader(itemReader(null)) + .writer(itemWriter(marshaller(), null)) + .build(); } @Bean @@ -95,12 +93,12 @@ public class SpringbatchPartitionConfig { @Bean @StepScope public FlatFileItemReader itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { - FlatFileItemReader reader = new FlatFileItemReader(); + FlatFileItemReader reader = new FlatFileItemReader<>(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = { "username", "userid", "transactiondate", "amount" }; + String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(new ClassPathResource("input/partitioner/" + filename)); - DefaultLineMapper lineMapper = new DefaultLineMapper(); + DefaultLineMapper lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); reader.setLinesToSkip(1); @@ -121,7 +119,7 @@ public class SpringbatchPartitionConfig { @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @@ -142,16 +140,15 @@ public class SpringbatchPartitionConfig { // JobRepositoryFactoryBean's methods Throws Generic Exception, // it would have been better to have a specific one factory.afterPropertiesSet(); - return (JobRepository) factory.getObject(); + return factory.getObject(); } private DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL) - .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") - .addScript("classpath:org/springframework/batch/core/schema-h2.sql") - .build(); - return db; + return builder.setType(EmbeddedDatabaseType.HSQL) + .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") + .addScript("classpath:org/springframework/batch/core/schema-h2.sql") + .build(); } private PlatformTransactionManager getTransactionManager() { diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java similarity index 95% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java rename to spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java index 1d6d922969..e56afc591c 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro.partitioner; +package org.baeldung.batch.partitioner; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java similarity index 71% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java rename to spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java index ebee1d2802..8ca7892fec 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java +++ b/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.spring_batch_intro.service; +package org.baeldung.batch.service; -import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements ItemProcessor { diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java similarity index 91% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java rename to spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java index 94f9e7d94e..fa6f0870aa 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java +++ b/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java @@ -1,9 +1,9 @@ -package org.baeldung.spring_batch_intro.service; +package org.baeldung.batch.service; import java.text.ParseException; import java.text.SimpleDateFormat; -import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.batch.model.Transaction; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.validation.BindException; diff --git a/spring-batch/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml index 93606d232f..0f76dd50ff 100644 --- a/spring-batch/src/main/resources/spring-batch-intro.xml +++ b/spring-batch/src/main/resources/spring-batch-intro.xml @@ -22,14 +22,14 @@ + class="org.baeldung.batch.service.RecordFieldSetMapper" /> - + @@ -40,7 +40,7 @@ - org.baeldung.spring_batch_intro.model.Transaction + org.baeldung.batch.model.Transaction From 8d9a7b0ecff611b751f103537b20b78ae1c5464d Mon Sep 17 00:00:00 2001 From: Roman Seleznov Date: Mon, 14 Aug 2017 14:12:29 +0100 Subject: [PATCH 38/67] BAEL-764 Automatic Property Expansion with Spring Boot (#2435) * Create pom.xml Initial import * First submit * Second submit * Different Types of Bean Injection in Spring * Different Types of Bean Injection in Spring * Added spring-core-di into the main build * Revert "Create pom.xml" This reverts commit 1bdc5443125df19575605f41ab28c9e8b6c69a32. * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot Make executable jars for property-exp-default project and use mvn exec:java to run property-exp-default project * BAEL-764 Automatic Property Expansion with Spring Boot Rename modules as per code reivew * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review --- spring-boot-property-exp/README.md | 18 +++++++++++++++++- .../property-exp-custom-config/pom.xml | 2 +- .../property-exp-default-config/pom.xml | 2 +- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/spring-boot-property-exp/README.md b/spring-boot-property-exp/README.md index 5b2552ade7..8a598e7a05 100644 --- a/spring-boot-property-exp/README.md +++ b/spring-boot-property-exp/README.md @@ -1,2 +1,18 @@ ## The Module Holds Sources for the Following Articles - - [Automatic Property Expansion with Spring Boot] (http://www.baeldung.com/property-expansion-spring-boot) \ No newline at end of file + - [Automatic Property Expansion with Spring Boot](http://www.baeldung.com/property-expansion-spring-boot) + +### Module property-exp-default-config + This module contains both a standard Maven Spring Boot build and the Gradle build which is Maven compatible. + + In order to execute the Maven example, run the following command: + + `mvn spring-boot:run` + + To execute the Gradle example: + +`gradle bootRun` + + ### Module property-exp-custom-config + This project is not using the standard Spring Boot parent and is configured manually. Run the following command: + + `mvn exec:java` \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml index cfce323eab..7822b31cf2 100644 --- a/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -9,7 +9,7 @@ 4.0.0 com.baeldung - property-exp-custom + property-exp-custom-config 0.0.1-SNAPSHOT jar diff --git a/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml index 2544800e6a..0625916d32 100644 --- a/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -11,7 +11,7 @@ com.baeldung - property-exp-default + property-exp-default-config 0.0.1-SNAPSHOT jar From 99eee4df2cd1a0dbf9e4011864bf16f1d90b35be Mon Sep 17 00:00:00 2001 From: baljeet20 Date: Mon, 14 Aug 2017 22:38:01 +0530 Subject: [PATCH 39/67] BAEL-1077 Guide to volatile keyword (#2433) * review changes * BAEL-1024 Removed the proxy reference * BAEL-1024 Renamed methods * BAEL-1077 Guide to volatile keyword --- .../volatilekeyword/SharedObject.java | 13 +++ .../SharedObjectManualTest.java | 99 +++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java create mode 100644 core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java new file mode 100644 index 0000000000..3f24df5059 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.volatilekeyword; + + +public class SharedObject { + private volatile int count=0; + + public void increamentCount(){ + count++; + } + public int getCount(){ + return count; + } +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java new file mode 100644 index 0000000000..260a7c060b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java @@ -0,0 +1,99 @@ +package com.baeldung.concurrent.volatilekeyword; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static junit.framework.Assert.assertEquals; + +public class SharedObjectManualTest { + + SharedObject sharedObject; + int valueReadByThread2; + int valueReadByThread3; + + @Before + public void setUp(){ + sharedObject = new SharedObject(); + } + + @Test + public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { + Thread writer = new Thread(){ + public void run(){ + sharedObject.increamentCount(); + } + }; + writer.start(); + + + Thread readerOne = new Thread(){ + public void run(){ + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + valueReadByThread2= sharedObject.getCount(); + } + }; + readerOne.start(); + + Thread readerTwo = new Thread(){ + public void run(){ + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + valueReadByThread3=sharedObject.getCount(); + } + }; + readerTwo.start(); + + assertEquals(1,valueReadByThread2); + assertEquals(1,valueReadByThread3); + + } + + @Test + public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { + Thread writerOne = new Thread(){ + public void run(){ + sharedObject.increamentCount(); + } + }; + writerOne.start(); + Thread.sleep(100); + + Thread writerTwo = new Thread(){ + public void run(){ + sharedObject.increamentCount(); + } + }; + writerTwo.start(); + Thread.sleep(100); + + Thread readerOne = new Thread(){ + public void run(){ + valueReadByThread2= sharedObject.getCount(); + } + }; + readerOne.start(); + + Thread readerTwo = new Thread(){ + public void run(){ + valueReadByThread3=sharedObject.getCount(); + } + }; + readerTwo.start(); + + assertEquals(2,valueReadByThread2); + assertEquals(2,valueReadByThread3); + + } + @After + public void cleanup(){ + sharedObject = null; + } +} From 58469d79bf11cb7349e220588d7472a499108acd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Ju=C3=A1rez?= Date: Mon, 14 Aug 2017 12:45:30 -0500 Subject: [PATCH 40/67] BAEL-864 Difference between URL and URI (#2438) --- .../uriurl/URIvsURLUnitTest.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java new file mode 100644 index 0000000000..ed36951f73 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.javanetworking.uriurl; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import org.apache.commons.io.IOUtils; +import static org.junit.Assert.*; +import org.junit.Test; + +public class URIvsURLUnitTest { + + @Test + public void whenCreatingURIs_thenSameInfo() throws URISyntaxException { + URI firstURI = new URI("somescheme://theuser:thepassword@someauthority:80/some/path?thequery#somefragment"); + URI secondURI = new URI("somescheme", "theuser:thepassword", "someuthority", 80, "/some/path", "thequery", "somefragment"); + + assertEquals(firstURI.getScheme(), secondURI.getScheme()); + assertEquals(firstURI.getPath(), secondURI.getPath()); + } + + @Test + public void whenCreatingURLs_thenSameInfo() throws MalformedURLException { + URL firstURL = new URL("http://theuser:thepassword@somehost:80/path/to/file?thequery#somefragment"); + URL secondURL = new URL("http", "somehost", 80, "/path/to/file"); + + assertEquals(firstURL.getHost(), secondURL.getHost()); + assertEquals(firstURL.getPath(), secondURL.getPath()); + } + + @Test + public void whenCreatingURI_thenCorrect() { + URI uri = URI.create("urn:isbn:1234567890"); + + assertNotNull(uri); + } + + @Test(expected = MalformedURLException.class) + public void whenCreatingURLs_thenException() throws MalformedURLException { + URL theURL = new URL("otherprotocol://somehost/path/to/file"); + + assertNotNull(theURL); + } + + @Test + public void givenObjects_whenConverting_thenCorrect() throws MalformedURLException, URISyntaxException { + String aURIString = "http://somehost:80/path?thequery"; + URI uri = new URI(aURIString); + URL url = new URL(aURIString); + + URL toURL = uri.toURL(); + URI toURI = url.toURI(); + + assertNotNull(url); + assertNotNull(uri); + assertEquals(toURL.toString(), toURI.toString()); + } + + @Test(expected = MalformedURLException.class) + public void givenURI_whenConvertingToURL_thenException() throws MalformedURLException, URISyntaxException { + URI uri = new URI("somescheme://someauthority/path?thequery"); + + URL url = uri.toURL(); + + assertNotNull(url); + } + + @Test + public void givenURL_whenGettingContents_thenCorrect() throws MalformedURLException, IOException { + URL url = new URL("http://courses.baeldung.com"); + + String contents = IOUtils.toString(url.openStream()); + + assertTrue(contents.contains("")); + } + +} From 0de69c346c87c2f628cfe93dc6688312cb8db580 Mon Sep 17 00:00:00 2001 From: lor6 Date: Mon, 14 Aug 2017 20:46:16 +0300 Subject: [PATCH 41/67] add dependency management (#2382) --- spring-boot-bootstrap/pom.xml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 697a139eb5..9da37a3261 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -17,6 +17,25 @@ 1.5.3.RELEASE + + UTF-8 From dc9ecc143df547e16725fbad678fe75211f8f423 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Mon, 14 Aug 2017 23:59:36 +0530 Subject: [PATCH 42/67] Added test cases for BAEL-897 (#2436) --- .../test/JacksonDeserializationUnitTest.java | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java index 45d957b90b..035ff8ca9c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java @@ -1,19 +1,23 @@ package com.baeldung.jackson.test; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import java.io.IOException; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Test; import com.baeldung.jackson.deserialization.ItemDeserializer; import com.baeldung.jackson.dtos.Item; import com.baeldung.jackson.dtos.ItemWithSerializer; import com.baeldung.jackson.dtos.MyDto; import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreUnknown; -import org.junit.Test; - import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; @@ -21,6 +25,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.fasterxml.jackson.databind.module.SimpleModule; @@ -165,4 +170,35 @@ public class JacksonDeserializationUnitTest { assertThat(readValue, notNullValue()); } + @Test + public void whenDeserialisingZonedDateTimeWithDefaults_thenTimeZoneIsNotPreserved() throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + // construct a new instance of ZonedDateTime + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); + String converted = objectMapper.writeValueAsString(now); + // restore an instance of ZonedDateTime from String + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(not(restored))); + } + + @Test + public void whenDeserialisingZonedDateTimeWithFeaturesDisabled_thenTimeZoneIsPreserved() throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); + // construct a new instance of ZonedDateTime + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); + String converted = objectMapper.writeValueAsString(now); + // restore an instance of ZonedDateTime from String + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(restored)); + } + } From bcc122b7247753923d34e593665c84af3aa8c3a4 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 14 Aug 2017 21:46:04 +0200 Subject: [PATCH 43/67] Refactor Batch (#2439) --- spring-ldap/pom.xml | 256 +++++++++--------- .../ldap/data/repository/UserRepository.java | 6 +- .../ldap/data/service/LdapClient.java | 14 +- .../ldap/data/service/UserService.java | 31 +-- .../baeldung/ldap/javaconfig/AppConfig.java | 7 +- spring-ldap/src/main/resources/logback.xml | 8 +- .../ldap/client/LdapClientLiveTest.java | 7 +- .../ldap/client/LdapDataRepositoryTest.java | 15 +- .../baeldung/ldap/javaconfig/TestConfig.java | 7 +- 9 files changed, 174 insertions(+), 177 deletions(-) diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index f000b07a09..05baf8c66d 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -1,143 +1,143 @@ - 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-ldap - 0.1-SNAPSHOT - jar + com.baeldung + spring-ldap + 0.1-SNAPSHOT + jar - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - 2.3.1.RELEASE - 4.3.6.RELEASE - 1.5.5 - 0.9.15 - + + 2.3.1.RELEASE + 4.3.6.RELEASE + 1.5.5 + 0.9.15 + - - spring-ldap - + + spring-ldap + - + - - org.springframework.ldap - spring-ldap-core - ${spring-ldap.version} - - - commons-logging - commons-logging - - - + + org.springframework.ldap + spring-ldap-core + ${spring-ldap.version} + + + commons-logging + commons-logging + + + - - org.springframework - spring-context - ${spring-context.version} - + + org.springframework + spring-context + ${spring-context.version} + - - - org.springframework.ldap - spring-ldap-test - ${spring-ldap.version} - test - - - commons-logging - commons-logging - - - + + + org.springframework.ldap + spring-ldap-test + ${spring-ldap.version} + test + + + commons-logging + commons-logging + + + - - - org.apache.directory.server - apacheds-core - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-core-entry - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-shared - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-ldap - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-server-jndi - ${apacheds.version} - test - - - org.apache.directory.shared - shared-ldap - ${shared-ldap.version} - test - + + + org.apache.directory.server + apacheds-core + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-core-entry + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-shared + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-ldap + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-server-jndi + ${apacheds.version} + test + + + org.apache.directory.shared + shared-ldap + ${shared-ldap.version} + test + - - - org.springframework.data - spring-data-ldap - 1.0.6.RELEASE - - - org.springframework.data - spring-data-jpa - 1.11.6.RELEASE - - + + + org.springframework.data + spring-data-ldap + 1.0.6.RELEASE + + + org.springframework.data + spring-data-jpa + 1.11.6.RELEASE + + - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - - - **/*LiveTest.java - - - - - - - - - + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + + + \ No newline at end of file diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java index 9140616eee..12dc0f7f14 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java @@ -8,10 +8,10 @@ import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends LdapRepository { - public User findByUsername(String username); + User findByUsername(String username); - public User findByUsernameAndPassword(String username, String password); + User findByUsernameAndPassword(String username, String password); - public List findByUsernameLikeIgnoreCase(String username); + List findByUsernameLikeIgnoreCase(String username); } diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java index 753c5f6c34..1b04edb35b 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java @@ -2,7 +2,11 @@ package com.baeldung.ldap.data.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.ldap.core.*; +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.support.LdapNameBuilder; import javax.naming.Name; @@ -31,8 +35,8 @@ public class LdapClient { "ou=users", "cn=" + username, (AttributesMapper) attrs -> (String) attrs - .get("cn") - .get()); + .get("cn") + .get()); } public void create(final String username, final String password) { @@ -43,7 +47,7 @@ public class LdapClient { .build(); DirContextAdapter context = new DirContextAdapter(dn); - context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); context.setAttributeValue("cn", username); context.setAttributeValue("sn", username); context.setAttributeValue("userPassword", digestSHA(password)); @@ -59,7 +63,7 @@ public class LdapClient { .build(); DirContextOperations context = ldapTemplate.lookupContext(dn); - context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); context.setAttributeValue("cn", username); context.setAttributeValue("sn", username); context.setAttributeValue("userPassword", digestSHA(password)); diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java index 39d4df1cd6..54954e3c9d 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java @@ -1,17 +1,17 @@ package com.baeldung.ldap.data.service; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; - +import com.baeldung.ldap.data.repository.User; +import com.baeldung.ldap.data.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ldap.support.LdapUtils; import org.springframework.stereotype.Service; -import com.baeldung.ldap.data.repository.User; -import com.baeldung.ldap.data.repository.UserRepository; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; @Service public class UserService { @@ -21,20 +21,18 @@ public class UserService { public Boolean authenticate(final String username, final String password) { User user = userRepository.findByUsernameAndPassword(username, password); - return user != null ? true : false; + return user != null; } public List search(final String username) { List userList = userRepository.findByUsernameLikeIgnoreCase(username); - List users = null; - if (null != userList) { - users = new ArrayList(); - for (User user : userList) { - users.add(user.getUsername()); - } + if (userList == null) { + return Collections.emptyList(); } - return users; + return userList.stream() + .map(User::getUsername) + .collect(Collectors.toList()); } public void create(final String username, final String password) { @@ -48,7 +46,6 @@ public class UserService { User user = userRepository.findByUsername(username); user.setPassword(password); userRepository.save(user); - } private String digestSHA(final String password) { diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java index 9330da7ab7..fb3000b2bd 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java @@ -1,5 +1,6 @@ package com.baeldung.ldap.javaconfig; +import com.baeldung.ldap.client.LdapClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -11,13 +12,11 @@ import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; -import com.baeldung.ldap.client.LdapClient; - @Configuration @PropertySource("classpath:application.properties") -@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) +@ComponentScan(basePackages = {"com.baeldung.ldap.*"}) @Profile("default") -@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") +@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**") public class AppConfig { @Autowired diff --git a/spring-ldap/src/main/resources/logback.xml b/spring-ldap/src/main/resources/logback.xml index ec0dc2469a..32b78577ee 100644 --- a/spring-ldap/src/main/resources/logback.xml +++ b/spring-ldap/src/main/resources/logback.xml @@ -7,13 +7,13 @@ - - + + - + - + \ No newline at end of file diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java index b65588dc38..f5b74d64c6 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java @@ -1,7 +1,6 @@ package com.baeldung.ldap.client; -import java.util.List; - +import com.baeldung.ldap.javaconfig.TestConfig; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; @@ -13,11 +12,11 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.ldap.javaconfig.TestConfig; +import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("testlive") -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) public class LdapClientLiveTest { private static final String USER2 = "TEST02"; diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java index 8460fb3eb9..9f38af9263 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java @@ -1,10 +1,7 @@ package com.baeldung.ldap.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.util.List; - +import com.baeldung.ldap.data.service.UserService; +import com.baeldung.ldap.javaconfig.TestConfig; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,12 +11,14 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.ldap.data.service.UserService; -import com.baeldung.ldap.javaconfig.TestConfig; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("testlive") -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) public class LdapDataRepositoryTest { private static final String USER2 = "TEST02"; diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java index 0752262159..c6293982da 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java @@ -1,5 +1,6 @@ package com.baeldung.ldap.javaconfig; +import com.baeldung.ldap.client.LdapClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -13,12 +14,10 @@ import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.test.TestContextSourceFactoryBean; -import com.baeldung.ldap.client.LdapClient; - @Configuration @PropertySource("classpath:test_application.properties") -@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) -@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") +@ComponentScan(basePackages = {"com.baeldung.ldap.*"}) +@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**") @Profile("testlive") public class TestConfig { @Autowired From 9308baeb9c6ca5b449746bb02935f69391e3746c Mon Sep 17 00:00:00 2001 From: Mohit Sinha Date: Tue, 15 Aug 2017 14:52:38 +0530 Subject: [PATCH 44/67] BAEL-1105: Apache Commons CSV, Test cases --- libraries/pom.xml | 8 ++- .../commons/csv/CSVReaderWriterTest.java | 60 +++++++++++++++++++ libraries/src/test/resources/book.csv | 3 + 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java create mode 100644 libraries/src/test/resources/book.csv diff --git a/libraries/pom.xml b/libraries/pom.xml index a16a4de59d..c70db4ffb2 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -212,6 +212,11 @@ commons-chain ${commons-chain.version} + + org.apache.commons + commons-csv + ${commons-csv.version} + commons-dbutils commons-dbutils @@ -480,6 +485,7 @@ 1.1 1.9.3 1.2 + 1.4 1.9.2 1.2 3.21.0-GA @@ -515,4 +521,4 @@ 1.0 8.2.0 - \ No newline at end of file + diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java new file mode 100644 index 0000000000..deab15a812 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java @@ -0,0 +1,60 @@ +package com.baeldung.commons.csv; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.CSVRecord; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringWriter; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class CSVReaderWriterTest { + + public static final Map AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap() { + { + put("Dan Simmons", "Hyperion"); + put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy"); + } + }); + public static final String[] HEADERS = { "author", "title" }; + public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy"; + + @Test + public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { + Reader in = new FileReader("src/test/resources/book.csv"); + Iterable records = CSVFormat.DEFAULT + .withHeader(HEADERS) + .withFirstRecordAsHeader() + .parse(in); + for (CSVRecord record : records) { + String author = record.get("author"); + String title = record.get("title"); + assertEquals(AUTHOR_BOOK_MAP.get(author), title); + } + } + + @Test + public void givenAuthorBookMap_whenProcessed_thenFileCreatedAsExpected() throws IOException { + StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { + AUTHOR_BOOK_MAP.forEach((author, title) -> { + try { + printer.printRecord(author, title); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } + assertEquals(EXPECTED_FILESTREAM, sw + .toString() + .trim()); + } + +} diff --git a/libraries/src/test/resources/book.csv b/libraries/src/test/resources/book.csv new file mode 100644 index 0000000000..d709152a5e --- /dev/null +++ b/libraries/src/test/resources/book.csv @@ -0,0 +1,3 @@ +author,title +Dan Simmons,Hyperion +Douglas Adams,The Hitchhiker's Guide to the Galaxy From 299be4a62916101e53483de9ad5784c0c450ba5a Mon Sep 17 00:00:00 2001 From: Mohit Sinha Date: Tue, 15 Aug 2017 15:28:51 +0530 Subject: [PATCH 45/67] BAEL-1105: Apache Commons CSV, Changed name of testcase --- .../test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java index deab15a812..6f47b89396 100644 --- a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java +++ b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java @@ -41,7 +41,7 @@ public class CSVReaderWriterTest { } @Test - public void givenAuthorBookMap_whenProcessed_thenFileCreatedAsExpected() throws IOException { + public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { AUTHOR_BOOK_MAP.forEach((author, title) -> { From 00e3483531aeb25421d33e48c2aa7b7c5e430f46 Mon Sep 17 00:00:00 2001 From: deep20jain Date: Tue, 15 Aug 2017 17:12:33 +0530 Subject: [PATCH 46/67] Bael 1053 - Removing java from package name (#2443) * Adding code for java broadcasting and multicasting * Changing multicast ip * Adding code to iterate thorugh all network interfaces * Formatting again and fixing bug * Applying formatting rules on all classes * Fixing formatting * Removing java from package name * Deleting duplicate files * Removing unused imports --- .../src/main/java/com/baeldung/{java => }/networking/README.md | 0 .../{java => }/networking/cookies/PersistentCookieStore.java | 2 +- .../{java => }/networking/cookies/ProxyAcceptCookiePolicy.java | 2 +- .../java/com/baeldung/{java => }/networking/udp/EchoClient.java | 2 +- .../java/com/baeldung/{java => }/networking/udp/EchoServer.java | 2 +- .../{java => }/networking/udp/broadcast/BroadcastingClient.java | 2 +- .../networking/udp/broadcast/BroadcastingEchoServer.java | 2 +- .../networking/udp/multicast/MulticastEchoServer.java | 2 +- .../{java => }/networking/udp/multicast/MulticastingClient.java | 2 +- .../baeldung/{java => }/networking/udp/UDPIntegrationTest.java | 2 +- .../networking/udp/broadcast/BroadcastIntegrationTest.java | 2 +- .../networking/udp/multicast/MulticastIntegrationTest.java | 2 +- 12 files changed, 11 insertions(+), 11 deletions(-) rename core-java/src/main/java/com/baeldung/{java => }/networking/README.md (100%) rename core-java/src/main/java/com/baeldung/{java => }/networking/cookies/PersistentCookieStore.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/cookies/ProxyAcceptCookiePolicy.java (93%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/EchoClient.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/EchoServer.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/broadcast/BroadcastingClient.java (98%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/broadcast/BroadcastingEchoServer.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/multicast/MulticastEchoServer.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/multicast/MulticastingClient.java (96%) rename core-java/src/test/java/com/baeldung/{java => }/networking/udp/UDPIntegrationTest.java (95%) rename core-java/src/test/java/com/baeldung/{java => }/networking/udp/broadcast/BroadcastIntegrationTest.java (95%) rename core-java/src/test/java/com/baeldung/{java => }/networking/udp/multicast/MulticastIntegrationTest.java (95%) diff --git a/core-java/src/main/java/com/baeldung/java/networking/README.md b/core-java/src/main/java/com/baeldung/networking/README.md similarity index 100% rename from core-java/src/main/java/com/baeldung/java/networking/README.md rename to core-java/src/main/java/com/baeldung/networking/README.md diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java rename to core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java index 0d66406ac2..5d30491cfe 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java +++ b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.cookies; +package com.baeldung.networking.cookies; import java.net.*; import java.util.List; diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java b/core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java similarity index 93% rename from core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java rename to core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java index 6d6371bfe0..0b5f6d7714 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java +++ b/core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.cookies; +package com.baeldung.networking.cookies; import java.net.*; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java b/core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java rename to core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java index 916442533b..35a083de26 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp; +package com.baeldung.networking.udp; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java b/core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java rename to core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java index 900d330786..34f2971cc4 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp; +package com.baeldung.networking.udp; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java similarity index 98% rename from core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java rename to core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java index 3162ff0b1e..09794c2596 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.broadcast; +package com.baeldung.networking.udp.broadcast; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java rename to core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java index afc50e1f40..b519f899bb 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.broadcast; +package com.baeldung.networking.udp.broadcast; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java rename to core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java index cae5c27d95..9d63dd6386 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.multicast; +package com.baeldung.networking.udp.multicast; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java rename to core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java index 4e425055fe..e89abc939d 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.multicast; +package com.baeldung.networking.udp.multicast; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java index aff851ae4b..968c01d24e 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp; +package com.baeldung.networking.udp; import org.junit.After; import org.junit.Before; diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java index e3ffbcc052..c4f1e1f42c 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.broadcast; +package com.baeldung.networking.udp.broadcast; import org.junit.After; import org.junit.Test; diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java index 26c0704b01..404f6c4e85 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.multicast; +package com.baeldung.networking.udp.multicast; import org.junit.After; import org.junit.Test; From 1a9c33f76f5ecf270d417914b0adacf4032e5aa4 Mon Sep 17 00:00:00 2001 From: buddhini81 Date: Tue, 15 Aug 2017 17:25:07 +0530 Subject: [PATCH 47/67] Commit source code for BAEL-698 (#2429) * Commit source for BAEL-698 * Commit model classes for BAEL-698 * remove file BAEL-698 * Commit source for BAEL-698 * Commit util class for BAEL-698 * delete file * Commit source for BAEL-698 * Commit spring config class for BAEL-698 * delete file * Commit source for BAEL-698 * Commit DAO classes for BAEL-698 * delete file * Commit source for BAEL-698 * Commit DAO Impl classes for BAEL-698 * delete file * Add Hibernate config XML BAEL-698 * Commit source for BAEL-698 * Commit test classes for BAEL-698 * delete file * Upgrade versions Upgrade spring framework version & tomcat-dbcp.version version, add mysql-connector-java dependency * Fix typo in class name * Fix type in PersistenceConfig class name * Remove class with typo error * Create tst.txt * Commit the corrected class * Delete tst.txt * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues --- spring-hibernate5/pom.xml | 11 ++- .../hibernate/manytomany/model/Employee.java | 86 +++++++++++++++++++ .../hibernate/manytomany/model/Project.java | 61 +++++++++++++ .../manytomany/util/HibernateUtil.java | 41 +++++++++ .../manytomany/spring/PersistenceConfig.java | 70 +++++++++++++++ .../manytomany/dao/IEmployeeDao.java | 8 ++ .../manytomany/dao/IProjectDao.java | 8 ++ .../manytomany/dao/impl/EmployeeDao.java | 16 ++++ .../manytomany/dao/impl/ProjectDao.java | 17 ++++ .../src/main/resources/manytomany.cfg.xml | 27 ++++++ ...notationJavaConfigMainIntegrationTest.java | 53 ++++++++++++ ...nnotationXMLConfigMainIntegrationTest.java | 84 ++++++++++++++++++ 12 files changed, 480 insertions(+), 2 deletions(-) create mode 100644 spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java create mode 100644 spring-hibernate5/src/main/resources/manytomany.cfg.xml create mode 100644 spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java create mode 100644 spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java diff --git a/spring-hibernate5/pom.xml b/spring-hibernate5/pom.xml index e3309ff10b..dac43c4dd3 100644 --- a/spring-hibernate5/pom.xml +++ b/spring-hibernate5/pom.xml @@ -120,6 +120,12 @@ hsqldb ${hsqldb.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + com.h2database @@ -167,7 +173,7 @@ - 4.3.5.RELEASE + 4.3.10.RELEASE 1.10.6.RELEASE @@ -177,7 +183,8 @@ 5.2.10.Final - 8.5.15 + 8.0.7-dmr + 9.0.0.M26 1.1 2.3.4 1.4.195 diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java new file mode 100644 index 0000000000..f1ad30b090 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java @@ -0,0 +1,86 @@ +package com.baeldung.hibernate.manytomany.model; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinTable; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "Employee") +public class Employee implements Serializable { + @Id + @Column(name = "employee_id") + @GeneratedValue + private Long employeeId; + + @Column(name = "first_name") + private String firstName; + + @Column(name = "last_name") + private String lastName; + + @ManyToMany(cascade = { CascadeType.ALL }) + @JoinTable( + name = "Employee_Project", + joinColumns = { @JoinColumn(name = "employee_id") }, + inverseJoinColumns = { @JoinColumn(name = "project_id") } + ) + Set projects = new HashSet(); + + + public Employee() { + super(); + } + + public Employee(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public Employee(String firstName, String lastName, Set projects) { + this.firstName = firstName; + this.lastName = lastName; + this.projects = projects; + } + + + public Long getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Long employeeId) { + this.employeeId = employeeId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Set getProjects() { + return projects; + } + + public void setProjects(Set projects) { + this.projects = projects; + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java new file mode 100644 index 0000000000..d6c049f33e --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.manytomany.model; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "Project") +public class Project implements Serializable { + + @Id + @Column(name = "project_id") + @GeneratedValue + private Long projectId; + + @Column(name = "title") + private String title; + + @ManyToMany(mappedBy = "projects") + private Set employees = new HashSet(); + + public Project() { + super(); + } + + public Project(String title) { + this.title = title; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Set getEmployees() { + return employees; + } + + public void setEmployees(Set employees) { + this.employees = employees; + } + + +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java new file mode 100644 index 0000000000..5f489dd027 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.manytomany.util; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + private static SessionFactory buildSessionFactory() { + try { + // Create the SessionFactory from hibernate-annotation.cfg.xml + Configuration configuration = new Configuration(); + configuration.addAnnotatedClass(Employee.class); + configuration.addAnnotatedClass(Project.class); + configuration.configure("manytomany.cfg.xml"); + System.out.println("Hibernate Annotation Configuration loaded"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + System.out.println("Hibernate Annotation serviceRegistry created"); + + SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); + + return sessionFactory; + } catch (Throwable ex) { + System.err.println("Initial SessionFactory creation failed." + ex); + ex.printStackTrace(); + throw new ExceptionInInitializerError(ex); + } + } + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) + sessionFactory = buildSessionFactory(); + return sessionFactory; + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java new file mode 100644 index 0000000000..6f359054b6 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java @@ -0,0 +1,70 @@ +package com.baeldung.manytomany.spring; + +import java.util.Properties; +import javax.sql.DataSource; +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +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.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + + + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-mysql.properties" }) +@ComponentScan({ "com.baeldung.hibernate.manytomany" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource restDataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); + + return dataSource; + } + + @Bean + public PlatformTransactionManager hibernateTransactionManager() { + final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + private 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.show_sql", "true"); + + return hibernateProperties; + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java new file mode 100644 index 0000000000..d619807b64 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.manytomany.dao; + +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IEmployeeDao extends IOperations{ + +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java new file mode 100644 index 0000000000..4a55714f8d --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.manytomany.dao; + +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IProjectDao extends IOperations{ + +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java new file mode 100644 index 0000000000..b062c00ff9 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java @@ -0,0 +1,16 @@ +package com.baeldung.persistence.manytomany.dao.impl; + +import org.springframework.stereotype.Repository; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.manytomany.dao.IEmployeeDao; + +@Repository +public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao { + + public EmployeeDao() { + super(); + + setClazz(Employee.class); + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java new file mode 100644 index 0000000000..772026fbc1 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java @@ -0,0 +1,17 @@ +package com.baeldung.persistence.manytomany.dao.impl; + +import org.springframework.stereotype.Repository; +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.manytomany.dao.IProjectDao; + + +@Repository +public class ProjectDao extends AbstractHibernateDao implements IProjectDao { + + public ProjectDao() { + super(); + + setClazz(Project.class); + } +} diff --git a/spring-hibernate5/src/main/resources/manytomany.cfg.xml b/spring-hibernate5/src/main/resources/manytomany.cfg.xml new file mode 100644 index 0000000000..8a10fc1580 --- /dev/null +++ b/spring-hibernate5/src/main/resources/manytomany.cfg.xml @@ -0,0 +1,27 @@ + + + + + + com.mysql.jdbc.Driver + + + buddhinisam123 + + + jdbc:mysql://localhost:3306/spring_hibernate_many_to_many + + + root + + + org.hibernate.dialect.MySQLDialect + + + thread + + true + + diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java new file mode 100644 index 0000000000..61d821e85e --- /dev/null +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java @@ -0,0 +1,53 @@ +package com.baeldung.hibernate.manytomany; + + +import java.util.HashSet; +import java.util.Set; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.manytomany.spring.PersistenceConfig; + + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { + + @Autowired + private SessionFactory sessionFactory; + + private Session session; + + + @Before + public final void before() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @After + public final void after() { + session.getTransaction().commit(); + session.close(); + } + + @Test + public final void whenEntitiesAreCreated_thenNoExceptions() { + Set projects = new HashSet(); + projects.add(new Project("IT Project")); + projects.add(new Project("Networking Project")); + session.persist(new Employee("Peter", "Oven", projects)); + session.persist(new Employee("Allan", "Norman", projects)); + } + +} diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java new file mode 100644 index 0000000000..5308134fac --- /dev/null +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java @@ -0,0 +1,84 @@ +package com.baeldung.hibernate.manytomany; + +import static org.junit.Assert.assertNotNull; +import static junit.framework.TestCase.assertEquals; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import com.baeldung.hibernate.manytomany.util.HibernateUtil; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; + + +public class HibernateManyToManyAnnotationXMLConfigMainIntegrationTest { + private static SessionFactory sessionFactory; + + private Session session; + + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + + @Test + public void givenSession_checkIfDatabaseIsPopulated() { + Employee employee1 = new Employee("Peter", "Oven"); + Set projects = new HashSet(); + projects = employee1.getProjects(); + int noProjects = projects.size(); + assertEquals(0,noProjects); + Project project1 = new Project("IT Project"); + assertNotNull(project1); + projects.add(project1); + Project project2 = new Project("Networking Project"); + assertNotNull(project2); + projects.add(project2); + employee1.setProjects(projects); + assertNotNull(employee1); + Employee employee2 = new Employee("Allan", "Norman"); + employee2.setProjects(projects); + assertNotNull(employee2); + + session.persist(employee1); + session.persist(employee2); + session.getTransaction().commit(); + session.close(); + + session = sessionFactory.openSession(); + session.beginTransaction(); + @SuppressWarnings("unchecked") + List projectList = session.createQuery("FROM Project").list(); + assertNotNull(projectList); + @SuppressWarnings("unchecked") + List employeeList = session.createQuery("FROM Employee").list(); + assertNotNull(employeeList); + } + + + @After + public void tearDown() { + session.getTransaction().commit(); + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + +} From 3b5d9585ed6a7c8e8d0d23cdcb5a3ef34107032c Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Tue, 15 Aug 2017 13:41:02 +0100 Subject: [PATCH 48/67] Example Code for Apache Shiro (#2441) * added updated example codes * updated example code StringToCharStream * deleted StringToCharStream.java locally * removed redundant file * added code for apache commons collection SetUtils * refactored example code * added example code for bytebuddy * added example code for PCollections * update pom * refactored tests for PCollections * spring security xml config * spring security xml config * remove redundant comment * example code for apache-shiro * Fixed indentation. * Fix formatting issues --- apache-shiro/.gitignore | 4 + apache-shiro/README.md | 0 apache-shiro/pom.xml | 65 +++++++++++ .../src/main/java/com/baeldung/Main.java | 84 +++++++++++++++ .../main/java/com/baeldung/MyCustomRealm.java | 102 ++++++++++++++++++ .../src/main/resources/log4j.properties | 12 +++ apache-shiro/src/main/resources/shiro.ini | 3 + 7 files changed, 270 insertions(+) create mode 100644 apache-shiro/.gitignore create mode 100644 apache-shiro/README.md create mode 100644 apache-shiro/pom.xml create mode 100644 apache-shiro/src/main/java/com/baeldung/Main.java create mode 100644 apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java create mode 100644 apache-shiro/src/main/resources/log4j.properties create mode 100644 apache-shiro/src/main/resources/shiro.ini diff --git a/apache-shiro/.gitignore b/apache-shiro/.gitignore new file mode 100644 index 0000000000..020cda4898 --- /dev/null +++ b/apache-shiro/.gitignore @@ -0,0 +1,4 @@ + +/.idea/ +/target/ +/apache-shiro.iml \ No newline at end of file diff --git a/apache-shiro/README.md b/apache-shiro/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml new file mode 100644 index 0000000000..97ed872a26 --- /dev/null +++ b/apache-shiro/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + com.baeldung + apache-shiro + 1.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.4.0 + 1.2.17 + 1.7.25 + + + + + org.apache.shiro + shiro-core + ${apache-shiro-core-version} + + + org.slf4j + jcl-over-slf4j + ${slf4j-version} + runtime + + + org.slf4j + slf4j-log4j12 + ${slf4j-version} + runtime + + + log4j + log4j + ${log4j-version} + runtime + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.2 + + 1.8 + 1.8 + + + + + + + \ No newline at end of file diff --git a/apache-shiro/src/main/java/com/baeldung/Main.java b/apache-shiro/src/main/java/com/baeldung/Main.java new file mode 100644 index 0000000000..68af5d7b46 --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/Main.java @@ -0,0 +1,84 @@ +package com.baeldung; + +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.*; +import org.apache.shiro.config.IniSecurityManagerFactory; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.session.Session; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.util.Factory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Main { + private static final transient Logger log = LoggerFactory.getLogger(Main.class); + + public static void main(String[] args) { + + Factory factory + = new IniSecurityManagerFactory("classpath:shiro.ini"); + SecurityManager securityManager = factory.getInstance(); + + SecurityUtils.setSecurityManager(securityManager); + Subject currentUser = SecurityUtils.getSubject(); + + if (!currentUser.isAuthenticated()) { + UsernamePasswordToken token + = new UsernamePasswordToken("user", "password"); + token.setRememberMe(true); + try { + currentUser.login(token); + } catch (UnknownAccountException uae) { + log.error("Username Not Found!", uae); + } catch (IncorrectCredentialsException ice) { + log.error("Invalid Credentials!", ice); + } catch (LockedAccountException lae) { + log.error("Your Account is Locked!", lae); + } catch (AuthenticationException ae) { + log.error("Unexpected Error!", ae); + } + } + + log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); + + if (currentUser.hasRole("admin")) { + log.info("Welcome Admin"); + } else if(currentUser.hasRole("editor")) { + log.info("Welcome, Editor!"); + } else if(currentUser.hasRole("author")) { + log.info("Welcome, Author"); + } else { + log.info("Welcome, Guest"); + } + + if(currentUser.isPermitted("articles:compose")) { + log.info("You can compose an article"); + } else { + log.info("You are not permitted to compose an article!"); + } + + if(currentUser.isPermitted("articles:save")) { + log.info("You can save articles"); + } else { + log.info("You can not save articles"); + } + + if(currentUser.isPermitted("articles:publish")) { + log.info("You can publish articles"); + } else { + log.info("You can not publish articles"); + } + + Session session = currentUser.getSession(); + session.setAttribute("key", "value"); + String value = (String) session.getAttribute("key"); + if (value.equals("value")) { + log.info("Retrieved the correct value! [" + value + "]"); + } + + currentUser.logout(); + + System.exit(0); + } + +} diff --git a/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java new file mode 100644 index 0000000000..8d792c76a5 --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java @@ -0,0 +1,102 @@ +package com.baeldung; + +import org.apache.shiro.authc.*; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.jdbc.JdbcRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.*; + +public class MyCustomRealm extends JdbcRealm { + + private Map credentials = new HashMap<>(); + private Map> roles = new HashMap<>(); + private Map> perm = new HashMap<>(); + + { + credentials.put("user", "password"); + credentials.put("user2", "password2"); + credentials.put("user3", "password3"); + + roles.put("user", new HashSet<>(Arrays.asList("admin"))); + roles.put("user2", new HashSet<>(Arrays.asList("editor"))); + roles.put("user3", new HashSet<>(Arrays.asList("author"))); + + perm.put("admin", new HashSet<>(Arrays.asList("*"))); + perm.put("editor", new HashSet<>(Arrays.asList("articles:*"))); + perm.put("author", + new HashSet<>(Arrays.asList("articles:compose", + "articles:save"))); + + } + + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) + throws AuthenticationException { + + UsernamePasswordToken uToken = (UsernamePasswordToken) token; + + if(uToken.getUsername() == null + || uToken.getUsername().isEmpty() + || !credentials.containsKey(uToken.getUsername()) + ) { + throw new UnknownAccountException("username not found!"); + } + + + return new SimpleAuthenticationInfo( + uToken.getUsername(), credentials.get(uToken.getUsername()), + getName()); + } + + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { + Set roleNames = new HashSet<>(); + Set permissions = new HashSet<>(); + + principals.forEach(p -> { + try { + Set roles = getRoleNamesForUser(null, (String) p); + roleNames.addAll(roles); + permissions.addAll(getPermissions(null, null,roles)); + } catch (SQLException e) { + e.printStackTrace(); + } + }); + + SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); + info.setStringPermissions(permissions); + return info; + } + + @Override + protected Set getRoleNamesForUser(Connection conn, String username) throws SQLException { + if(!roles.containsKey(username)) { + throw new SQLException("username not found!"); + } + + return roles.get(username); + } + + @Override + protected Set getPermissions(Connection conn, String username, Collection roleNames) throws SQLException { + for (String role : roleNames) { + if (!perm.containsKey(role)) { + throw new SQLException("role not found!"); + } + } + + Set finalSet = new HashSet<>(); + for (String role : roleNames) { + finalSet.addAll(perm.get(role)); + } + + return finalSet; + } + +} diff --git a/apache-shiro/src/main/resources/log4j.properties b/apache-shiro/src/main/resources/log4j.properties new file mode 100644 index 0000000000..897bf08221 --- /dev/null +++ b/apache-shiro/src/main/resources/log4j.properties @@ -0,0 +1,12 @@ +log4j.rootLogger=INFO, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n + +log4j.logger.org.apache=WARN + +log4j.logger.org.apache.shiro=INFO + +log4j.logger.org.apache.shiro.util.ThreadContext=WARN +log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN \ No newline at end of file diff --git a/apache-shiro/src/main/resources/shiro.ini b/apache-shiro/src/main/resources/shiro.ini new file mode 100644 index 0000000000..a75f591015 --- /dev/null +++ b/apache-shiro/src/main/resources/shiro.ini @@ -0,0 +1,3 @@ +jdbcRealm = com.baeldung.MyCustomRealm + +securityManager.realms = $jdbcRealm \ No newline at end of file From 6db067d2c9d433828d49cd4d697ddc145019b433 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 15 Aug 2017 15:17:24 +0200 Subject: [PATCH 49/67] Refactor volatile (#2444) --- .../volatilekeyword/SharedObject.java | 2 +- .../SharedObjectManualTest.java | 82 ++++++------------- 2 files changed, 28 insertions(+), 56 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java index 3f24df5059..063c835481 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java +++ b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java @@ -4,7 +4,7 @@ package com.baeldung.concurrent.volatilekeyword; public class SharedObject { private volatile int count=0; - public void increamentCount(){ + void increamentCount(){ count++; } public int getCount(){ diff --git a/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java index 260a7c060b..8770cb4e90 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java @@ -8,92 +8,64 @@ import static junit.framework.Assert.assertEquals; public class SharedObjectManualTest { - SharedObject sharedObject; - int valueReadByThread2; - int valueReadByThread3; + private SharedObject sharedObject; + private int valueReadByThread2; + private int valueReadByThread3; @Before - public void setUp(){ + public void setUp() { sharedObject = new SharedObject(); } @Test public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { - Thread writer = new Thread(){ - public void run(){ - sharedObject.increamentCount(); - } - }; + Thread writer = new Thread(() -> sharedObject.increamentCount()); writer.start(); - Thread readerOne = new Thread(){ - public void run(){ - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - valueReadByThread2= sharedObject.getCount(); + Thread readerOne = new Thread(() -> { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); } - }; + valueReadByThread2 = sharedObject.getCount(); + }); readerOne.start(); - Thread readerTwo = new Thread(){ - public void run(){ - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - valueReadByThread3=sharedObject.getCount(); + Thread readerTwo = new Thread(() -> { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); } - }; + valueReadByThread3 = sharedObject.getCount(); + }); readerTwo.start(); - assertEquals(1,valueReadByThread2); - assertEquals(1,valueReadByThread3); + assertEquals(1, valueReadByThread2); + assertEquals(1, valueReadByThread3); } @Test public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { - Thread writerOne = new Thread(){ - public void run(){ - sharedObject.increamentCount(); - } - }; + Thread writerOne = new Thread(() -> sharedObject.increamentCount()); writerOne.start(); Thread.sleep(100); - Thread writerTwo = new Thread(){ - public void run(){ - sharedObject.increamentCount(); - } - }; + Thread writerTwo = new Thread(() -> sharedObject.increamentCount()); writerTwo.start(); Thread.sleep(100); - Thread readerOne = new Thread(){ - public void run(){ - valueReadByThread2= sharedObject.getCount(); - } - }; + Thread readerOne = new Thread(() -> valueReadByThread2 = sharedObject.getCount()); readerOne.start(); - Thread readerTwo = new Thread(){ - public void run(){ - valueReadByThread3=sharedObject.getCount(); - } - }; + Thread readerTwo = new Thread(() -> valueReadByThread3 = sharedObject.getCount()); readerTwo.start(); - assertEquals(2,valueReadByThread2); - assertEquals(2,valueReadByThread3); + assertEquals(2, valueReadByThread2); + assertEquals(2, valueReadByThread3); } - @After - public void cleanup(){ - sharedObject = null; - } } From 7ec1db1be2c508793f16a6a317bf5d2eab49343a Mon Sep 17 00:00:00 2001 From: juan Date: Tue, 15 Aug 2017 23:48:47 -0300 Subject: [PATCH 50/67] Sample code for article - JIRA: (BAEL-1079) Java 8 Streams distinctBy() some property(+ external tools) --- libraries/pom.xml | 23 ++++--- .../distinct/DistinctWithJavaFunction.java | 15 +++++ .../java/com/baeldung/distinct/Person.java | 65 +++++++++++++++++++ ...istinctWithEclipseCollectionsUnitTest.java | 32 +++++++++ .../DistinctWithJavaFunctionUnitTest.java | 44 +++++++++++++ .../DistinctWithStreamexUnitTest.java | 36 ++++++++++ .../distinct/DistinctWithVavrUnitTest.java | 34 ++++++++++ .../distinct/PersonDataGenerator.java | 19 ++++++ 8 files changed, 260 insertions(+), 8 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java create mode 100644 libraries/src/main/java/com/baeldung/distinct/Person.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java diff --git a/libraries/pom.xml b/libraries/pom.xml index a16a4de59d..70ee008925 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -186,11 +186,11 @@ rome ${rome.version} - - io.specto - hoverfly-java - 0.8.0 - + + io.specto + hoverfly-java + 0.8.0 + org.apache.httpcomponents httpclient @@ -380,7 +380,7 @@ one.util streamex - 0.6.5 + ${streamex.version} org.jooq @@ -467,11 +467,16 @@ noexception 1.1.0 - + org.eclipse.collections eclipse-collections ${eclipse-collections.version} + + io.vavr + vavr + ${vavr.version} + 0.7.0 @@ -513,6 +518,8 @@ 1.7.1 2.1.2 1.0 - 8.2.0 + 8.2.0 + 0.6.5 + 0.9.0 \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java b/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java new file mode 100644 index 0000000000..0d08c94b47 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java @@ -0,0 +1,15 @@ +package com.baeldung.distinct; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; + +public class DistinctWithJavaFunction { + + public static Predicate distinctByKey(Function keyExtractor) { + Map seen = new ConcurrentHashMap<>(); + return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } + +} diff --git a/libraries/src/main/java/com/baeldung/distinct/Person.java b/libraries/src/main/java/com/baeldung/distinct/Person.java new file mode 100644 index 0000000000..8a2a5f7a45 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/distinct/Person.java @@ -0,0 +1,65 @@ +package com.baeldung.distinct; + +public class Person { + int age; + String name; + String email; + + public Person(int age, String name, String email) { + super(); + this.age = age; + this.name = name; + this.email = email; + } + + public int getAge() { + return age; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [age="); + builder.append(age); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Person other = (Person) obj; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + return true; + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java new file mode 100644 index 0000000000..dffde3917c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.eclipse.collections.impl.block.factory.HashingStrategies; +import org.eclipse.collections.impl.utility.ListIterate; +import org.junit.Before; +import org.junit.Test; + +public class DistinctWithEclipseCollectionsUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromFunction(Person::getName)); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromIntFunction(Person::getAge)); + assertTrue(personListFiltered.size() == 2); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java new file mode 100644 index 0000000000..68775fac66 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; +import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey; + +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +public class DistinctWithJavaFunctionUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = personList.stream() + .filter(distinctByKey(p -> p.getName())) + .collect(Collectors.toList()); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = personList.stream() + .filter(distinctByKey(p -> p.getAge())) + .collect(Collectors.toList()); + assertTrue(personListFiltered.size() == 2); + } + + @Test + public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() { + List personListFiltered = personList.stream() + .distinct() + .collect(Collectors.toList()); + assertTrue(personListFiltered.size() == 5); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java new file mode 100644 index 0000000000..f50c76a486 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import one.util.streamex.StreamEx; + +public class DistinctWithStreamexUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = StreamEx.of(personList) + .distinct(Person::getName) + .toList(); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = StreamEx.of(personList) + .distinct(Person::getAge) + .toList(); + assertTrue(personListFiltered.size() == 2); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java new file mode 100644 index 0000000000..b4025cd313 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class DistinctWithVavrUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = io.vavr.collection.List.ofAll(personList) + .distinctBy(Person::getName) + .toJavaList(); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = io.vavr.collection.List.ofAll(personList) + .distinctBy(Person::getAge) + .toJavaList(); + assertTrue(personListFiltered.size() == 2); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java b/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java new file mode 100644 index 0000000000..51590005ac --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java @@ -0,0 +1,19 @@ +package com.baeldung.distinct; + +import java.util.Arrays; +import java.util.List; + +public class PersonDataGenerator { + + public static List getPersonListWithFakeValues() { + // @formatter:off + return Arrays.asList( + new Person(20, "Jhon", "jhon@test.com"), + new Person(20, "Jhon", "jhon1@test.com"), + new Person(20, "Jhon", "jhon2@test.com"), + new Person(21, "Tom", "Tom@test.com"), + new Person(21, "Mark", "Mark@test.com"), + new Person(20, "Julia", "jhon@test.com")); + // @formatter:on + } +} From da3273af6ebe6c3223e5206b0a9ad4a724c485e3 Mon Sep 17 00:00:00 2001 From: Shivang Sarawagi Date: Wed, 16 Aug 2017 11:26:42 +0530 Subject: [PATCH 51/67] Binary Search algorithm (#2448) --- .../com/baeldung/algorithms/BinarySearch.java | 26 +++++++++++++++++++ .../java/algorithms/BinarySearchTest.java | 14 ++++++++++ 2 files changed, 40 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java create mode 100644 algorithms/src/test/java/algorithms/BinarySearchTest.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java new file mode 100644 index 0000000000..be4a9e578a --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java @@ -0,0 +1,26 @@ +public class BinarySearch { + + public int runBinarySearch() { + int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; + int key = 6; + + int low = 0; + int high = sortedArray.length - 1; + int index = Integer.MAX_VALUE; + + while (low <= high) { + + int mid = (low + high) / 2; + + if (sortedArray[mid] < key) { + low = mid + 1; + } else if (sortedArray[mid] > key) { + high = mid - 1; + } else if (sortedArray[mid] == key) { + index = mid; + break; + } + } + return index; + } +} diff --git a/algorithms/src/test/java/algorithms/BinarySearchTest.java b/algorithms/src/test/java/algorithms/BinarySearchTest.java new file mode 100644 index 0000000000..d53b074cc4 --- /dev/null +++ b/algorithms/src/test/java/algorithms/BinarySearchTest.java @@ -0,0 +1,14 @@ +import org.junit.Assert; +import org.junit.Test; + + +public class BinarySearchTest { + + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + int expectedIndexForSearchKey = 7; + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearch()); + } + +} From 491fc883bef942482a26710000df16dfe877d940 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Wed, 16 Aug 2017 18:17:07 +0100 Subject: [PATCH 52/67] Update Apache Shiro Example code (#2453) * added updated example codes * updated example code StringToCharStream * deleted StringToCharStream.java locally * removed redundant file * added code for apache commons collection SetUtils * refactored example code * added example code for bytebuddy * added example code for PCollections * update pom * refactored tests for PCollections * spring security xml config * spring security xml config * remove redundant comment * example code for apache-shiro --- apache-shiro/src/main/java/com/baeldung/Main.java | 11 ++++++----- apache-shiro/src/main/resources/shiro.ini | 10 ++++++++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/apache-shiro/src/main/java/com/baeldung/Main.java b/apache-shiro/src/main/java/com/baeldung/Main.java index 68af5d7b46..5e341f251b 100644 --- a/apache-shiro/src/main/java/com/baeldung/Main.java +++ b/apache-shiro/src/main/java/com/baeldung/Main.java @@ -2,22 +2,23 @@ package com.baeldung; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; -import org.apache.shiro.config.IniSecurityManagerFactory; +import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.realm.Realm; +import org.apache.shiro.realm.text.IniRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; -import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { + private static final transient Logger log = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { - Factory factory - = new IniSecurityManagerFactory("classpath:shiro.ini"); - SecurityManager securityManager = factory.getInstance(); + Realm realm = new MyCustomRealm(); + SecurityManager securityManager = new DefaultSecurityManager(realm); SecurityUtils.setSecurityManager(securityManager); Subject currentUser = SecurityUtils.getSubject(); diff --git a/apache-shiro/src/main/resources/shiro.ini b/apache-shiro/src/main/resources/shiro.ini index a75f591015..0bb7567d1e 100644 --- a/apache-shiro/src/main/resources/shiro.ini +++ b/apache-shiro/src/main/resources/shiro.ini @@ -1,3 +1,9 @@ -jdbcRealm = com.baeldung.MyCustomRealm +[users] +user = password,admin +user2 = password2,editor +user3 = password3,author -securityManager.realms = $jdbcRealm \ No newline at end of file +[roles] +admin = * +editor = articles:* +author = articles:compose,articles:save \ No newline at end of file From 4226100ea92afba457903442590127b732a555c8 Mon Sep 17 00:00:00 2001 From: Nancy Bosecker Date: Wed, 16 Aug 2017 12:10:01 -0700 Subject: [PATCH 53/67] moved test file to correct location (#2437) --- .../commons/collections4/BagTests.java | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java new file mode 100644 index 0000000000..1270c50008 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java @@ -0,0 +1,85 @@ +package com.baeldung.commons.collections4; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.Bag; +import org.apache.commons.collections4.bag.CollectionBag; +import org.apache.commons.collections4.bag.HashBag; +import org.apache.commons.collections4.bag.TreeBag; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class BagTests { + + Bag baseBag; + TreeBag treeBag; + + @Before + public void before() { + baseBag = new HashBag(); + treeBag = new TreeBag(); + treeBag = new TreeBag(); + } + + @Test + public void whenAdd_thenRemoveFromBaseBag_thenContainsCorrect() { + baseBag.add("apple", 2); + baseBag.add("lemon", 6); + baseBag.add("lime"); + + baseBag.remove("lemon"); + Assert.assertEquals(3, baseBag.size()); + Assert.assertFalse(baseBag.contains("lemon")); + + Assert.assertTrue(baseBag.uniqueSet().contains("apple")); + Assert.assertFalse(baseBag.uniqueSet().contains("lemon")); + Assert.assertTrue(baseBag.uniqueSet().contains("lime")); + + List containList = new ArrayList(); + containList.add("apple"); + containList.add("lemon"); + containList.add("lime"); + Assert.assertFalse(baseBag.containsAll(containList)); + } + + @Test + public void whenAdd_thenRemoveFromBaseCollectionBag_thenContainsCorrect() { + baseBag.add("apple", 2); + baseBag.add("lemon", 6); + baseBag.add("lime"); + + CollectionBag baseCollectionBag = new CollectionBag( + baseBag); + + baseCollectionBag.remove("lemon"); + Assert.assertEquals(8, baseCollectionBag.size()); + Assert.assertTrue(baseCollectionBag.contains("lemon")); + + Assert.assertTrue(baseBag.uniqueSet().contains("apple")); + Assert.assertTrue(baseBag.uniqueSet().contains("lemon")); + Assert.assertTrue(baseBag.uniqueSet().contains("lime")); + + List containList = new ArrayList(); + containList.add("apple"); + containList.add("lemon"); + containList.add("lime"); + Assert.assertTrue(baseBag.containsAll(containList)); + } + + @Test + public void whenAddtoTreeBag_thenRemove_thenContainsCorrect() { + treeBag.add("banana", 8); + treeBag.add("apple", 2); + treeBag.add("lime"); + + Assert.assertEquals(11, treeBag.size()); + Assert.assertEquals("apple", treeBag.first()); + Assert.assertEquals("lime", treeBag.last()); + + treeBag.remove("apple"); + Assert.assertEquals(9, treeBag.size()); + Assert.assertEquals("banana", treeBag.first()); + } +} From dc105bc6f22b2b4ab9d504fdbf0dd9988ba26ec1 Mon Sep 17 00:00:00 2001 From: felipeazv Date: Wed, 16 Aug 2017 21:58:42 +0200 Subject: [PATCH 54/67] BAEL-812: List of Rules Engines in Java (#2319) * spring beans DI examples * fix-1: shortening examples * List of Rules Engines in Java * BAEL-812: Openl-Tablets example added * BAEL-812: artifacts names changed --- easy-rules/pom.xml | 15 ++++ .../baeldung/easyrules/HelloWorldRule.java | 20 +++++ .../java/com/baeldung/easyrules/Launcher.java | 21 ++++++ openl-tablets/pom.xml | 23 ++++++ .../com/baeldung/openltablets/model/Case.java | 23 ++++++ .../baeldung/openltablets/model/Greeting.java | 20 +++++ .../com/baeldung/openltablets/model/User.java | 14 ++++ .../baeldung/openltablets/rules/IRule.java | 7 ++ .../com/baeldung/openltablets/rules/Main.java | 31 ++++++++ .../baeldung/openltablets/rules/Response.java | 24 ++++++ .../main/resources/openltablets/HelloUser.xls | Bin 0 -> 25088 bytes rulebook/pom.xml | 15 ++++ .../com/baeldung/rulebook/HelloWorldRule.java | 17 +++++ .../java/com/baeldung/rulebook/Launcher.java | 12 +++ .../autowired/TypesOfBeanInjectionSpring.java | 70 ++++++++++++++++++ ...sOfBeanInjectionSpringIntegrationTest.java | 25 +++++++ 16 files changed, 337 insertions(+) create mode 100644 easy-rules/pom.xml create mode 100644 easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java create mode 100644 easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java create mode 100644 openl-tablets/pom.xml create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java create mode 100644 openl-tablets/src/main/resources/openltablets/HelloUser.xls create mode 100644 rulebook/pom.xml create mode 100644 rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java create mode 100644 rulebook/src/main/java/com/baeldung/rulebook/Launcher.java create mode 100644 spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java create mode 100644 spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java diff --git a/easy-rules/pom.xml b/easy-rules/pom.xml new file mode 100644 index 0000000000..b74b16f34c --- /dev/null +++ b/easy-rules/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + com.baeldung.easyrules + easy-rules + 1.0.0-SNAPSHOT + + + + org.jeasy + easy-rules-core + 3.0.0 + + + \ No newline at end of file diff --git a/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java b/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java new file mode 100644 index 0000000000..5448eabf2a --- /dev/null +++ b/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java @@ -0,0 +1,20 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.annotation.Action; +import org.jeasy.rules.annotation.Condition; +import org.jeasy.rules.annotation.Rule; + +@Rule(name = "Hello World rule", description = "Always say hello world") +public class HelloWorldRule { + + @Condition + public boolean when() { + return true; + } + + @Action + public void then() throws Exception { + System.out.println("hello world"); + } + +} diff --git a/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java b/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java new file mode 100644 index 0000000000..427e3eace0 --- /dev/null +++ b/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java @@ -0,0 +1,21 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.api.Facts; +import org.jeasy.rules.api.Rules; +import org.jeasy.rules.api.RulesEngine; +import org.jeasy.rules.core.DefaultRulesEngine; + +public class Launcher { + public static void main(String... args) { + // create facts + Facts facts = new Facts(); + + // create rules + Rules rules = new Rules(); + rules.register(new HelloWorldRule()); + + // create a rules engine and fire rules on known facts + RulesEngine rulesEngine = new DefaultRulesEngine(); + rulesEngine.fire(rules, facts); + } +} diff --git a/openl-tablets/pom.xml b/openl-tablets/pom.xml new file mode 100644 index 0000000000..77b9f47b38 --- /dev/null +++ b/openl-tablets/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + com.baeldung.openltablets + openl-tablets + 0.0.1-SNAPSHOT + + UTF-8 + UTF-8 + 1.8 + + + + org.openl + org.openl.core + 5.19.4 + + + org.openl.rules + org.openl.rules + 5.19.4 + + + \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java new file mode 100644 index 0000000000..f9f5f4bd5f --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java @@ -0,0 +1,23 @@ +package com.baeldung.openltablets.model; + +public class Case { + + private User user; + private int hourOfDay; + + public User getUser() { + return user; + } + + public void setUser(final User user) { + this.user = user; + } + + public int getHourOfDay() { + return hourOfDay; + } + + public void setHourOfDay(final int hourOfDay) { + this.hourOfDay = hourOfDay; + } +} diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java new file mode 100644 index 0000000000..5dc7bcd117 --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java @@ -0,0 +1,20 @@ +package com.baeldung.openltablets.model; + +public enum Greeting { + + GOOD_MORNING("Good Morning"), + GOOD_AFTERNOON("Good Afternoon"), + GOOD_EVENING("Good Evening"), + GOOD_NIGHT("Good Night"); + + private final String literal; + + private Greeting(final String literal) { + this.literal = literal; + } + + public String getLiteral() { + return literal; + } + +} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java new file mode 100644 index 0000000000..8e45487497 --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java @@ -0,0 +1,14 @@ +package com.baeldung.openltablets.model; + +public class User { + + private String name; + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java new file mode 100644 index 0000000000..857a6433ef --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java @@ -0,0 +1,7 @@ +package com.baeldung.openltablets.rules; + +import com.baeldung.openltablets.model.Case; + +public interface IRule { + void helloUser(final Case aCase, final Response response); +} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java new file mode 100644 index 0000000000..34f5c48ed1 --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java @@ -0,0 +1,31 @@ +package com.baeldung.openltablets.rules; + + +import java.time.LocalDateTime; + +import org.openl.rules.runtime.RulesEngineFactory; +import org.openl.runtime.EngineFactory; + +import com.baeldung.openltablets.model.Case; +import com.baeldung.openltablets.model.User; + +public class Main { + private IRule instance; + + public static void main(String[] args) { + Main rules = new Main(); + User user = new User(); + user.setName("Donald Duck"); + Case aCase = new Case(); + aCase.setUser(user); + aCase.setHourOfDay(23); + rules.process(aCase); + } + + public void process(Case aCase) { + final EngineFactory engineFactory = new RulesEngineFactory(getClass().getClassLoader() + .getResource("openltablets/HelloUser.xls"), IRule.class); + instance = engineFactory.newEngineInstance(); + instance.helloUser(aCase, new Response()); + } +} diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java new file mode 100644 index 0000000000..27fa634866 --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java @@ -0,0 +1,24 @@ +package com.baeldung.openltablets.rules; + +import java.util.HashMap; +import java.util.Map; + +public class Response { + private String result; + private Map map = new HashMap<>(); + + public Response() { } + + public String getResult() { + return result; + } + + public void setResult(final String s) { + result = s; + } + + public Map getMap() { + return map; + } + +} diff --git a/openl-tablets/src/main/resources/openltablets/HelloUser.xls b/openl-tablets/src/main/resources/openltablets/HelloUser.xls new file mode 100644 index 0000000000000000000000000000000000000000..1e85d0ce2de54ddc812ec9639211a313a5024b45 GIT binary patch literal 25088 zcmeHv2Ut{B)9~44ft8{(5m8`4P>>?Uf-QiE9YLBEae)O^mt6u2q7lWGh%t&imY66p z8Vh!eVnK}s#S&{2dyR^QSYwI%&78aSvWw(>^Zn2Ne$RWCbN8M(b7tnunVD1WVb7el zzPWOX<1NCvJ|RZrgQ5{J(Smc}856y%2;ss5=07MD3I<3BJpT9k57NM2AgiCU58J`F zF(mABQ%HPBjUbspGKXXV$r4gyNKGJt2@q>YHjr!~*+FUw$sSTONDh#iLvn=F0#Zvz zPLP}-xj+&?a)smusTCx5NFI<{Luv!b6OtFCwvfCb`9Si8g!ZON|3Rw$|5DT#B7=_{ z`XYiz;X9j*0}VI)vImP%H4I~cfR9mukP3Pyz3|Je*6Eu(t8<*5Y)V zz&)FcA<0yZFPdzR(M4R3`|L6EQqX8C1P@PbGhBQ$zVa@^#ME%e4tJ>w6UAhzkT*5D#L31Tt4w`v+c4!z~UgGtztRG zcN}97j^j!wBpgQuKthUl0TIUv#OWoHh_k>=L*cpb&-=&KaRl=J&Q+iM+zTf!Eca_+ zHGeV4@AIY<F)Tz?^{T z0>S^As|S@qNMm~iD7!m{4?5>Uoad3{@NEq<3)CURf4JMy`zDILhu*u>SqUNULq50! z0|xfk5N;^N`-_zV7_t;@D-Dav6H!EoG~X1VzU_Hv4pTn$v=4c03a2V~Y?+LC++tqf7uHQ~fTYcgPL!BHjvW@g_3(GWFfc6t38aVA%x zHeXe{#*`CIbtQ&T9rYFfUW^#lAHm>|_9_Vt(9mkX0Sp2(l=?G>q1LcLj88sF!|tOP z-9CcBAzeSxT8ymqw}lJw$1p})k^vUnRgGcE>K6e-S}{onJCM^p^5J|;Cf-Leu7aI? ztX&+i6{Vf(=>Y+?MYZ?U@Hw$CKT8K&6%hf6Cw+-C&kzs^L${118bcmUk%;}t!ISm;D^F0s4I&X2*GB@fV4P< zglKrSht(9U_0&97^_3#1>Qc^{dN-AG)|U!Uiu$S$ARGfFg}+c0)DOoHrVrl`9I5KV z|Gy09pz*0MMxQv#pnBM@EZ}`h^ELb) zg`cOBO9*a^J>YCmm;OGAUl+c^0Gy#;7k`@pd`6#j@tOAGZjf%f7(L?-k*=H@DSZw^ zGYYQ-1bV6BMq9mboK@@6Vfr0+s3?57wY9yuJ?N9MXPhtSqmQd^3J3i&dS>*`foQA` zA9uAVoE6`2cCQbPs{(y+2NnE0T{OTZ7}H+dC8PKZ9LO?o+&NRi1+eac>MS@*9^7S9 z;tL7+L`|Oq5ud_YdIofe-9S1EpYUSno5B-?=To2>jyVdCHUJOR2ZvVVtMt6gPBo5j zaE#99Sa&68=WMtNe?t=uK4?izhk-M4)}^n3>(bZ2_0b19{z|w~57-(ir@xX88y;*3 zA2&v!U2J@RefoiJwK4!_^@}l;2k`T;Mj_~Jh70NkR%ak5g)0eZ_hVf+B2oNkCAyBB zu;;7Rvv$7-U`eae8w1zai3+aWUx4pvO|_t_2MV_;cLMo!_=5g}b>(5&>#Eb<34A*; z0hhw+YdA484W3iL4HyS2_!LI>CuulvV!N}JDBB)2hL@*pSfC#=jFiZqv=SPWD4XD3& zFwi!DNd3J7{?QO3_4f{j@CHayfA4??G=xa~y@P{510<=xcko@!M~MUm)!#e#vZnz= z>hB%g0c-$~`g;dP!iEs3zjp);BT|3wKrm~FB=z@>o0W%>(fXMVx(;Fbq9men2ntii3YGV1!&KgsIX3S4ZzR)C@Es7s`CLx?Cslu^n6kuD7( zqMke`iLf;cyPQf5>uW!^fFIB5l5S9eXL!1gHo>n zGkC8K&$t8uOYy+f2ePqdvk9!r#;qPUff_c(qO|vSFY0Gw!)6mymrd(>*q{R{TVo<^jKP}de~@N zTGfC*Pi)lB#(~X7kEOM#hmE$SRSl@FuGY_{Ih&0hOY^RWjkcv#4N%-)qMwZ;n~fez zYgZ2&ZA+^fu=mna{cKvW+32yfpnBM7TUynCBR99}XVVhdbgbXf1i+?a11v2tX!ef= z`o@XPMvtYr*TY8J(gK5CY@VjSHO_1{dMwSe9yZ#R78q1nS*f3m3!9A|OY^CRjkcu) z1}QG5>1QKgv(aN|{`IiYwzR;YWe4x;XXDCdqsP+P*TY8J(gK5iJTqG#8$NM^z(;z> zGUxF->yDWmM}-mTK~Ej1f}=4^op70o<0C%fT2?teTEL-DSU!Z`lBDEHWb^prbcu28 z6{aK{4y#B=3LK%609l+T;-HI!a5|_Wifda+)CA71Vj)hyIDo93Ez~f9pQ9p zQxN8%Bv&F7q>2OyqHJ-RI7Rs24v4mpC0a8@QxNST2!(aRSIFRjO79@(byJR!5~OCF0`Ogv{q!!0}z^HTAS9OqUVQ33|=YR0)nY zW&d2a`AD>lhA0FSHc?j=QSBf?$diHq{X{)AL?L{ziF&YzYKIJF2ck|#p`>0Kq7W?D zM7>xffXa8IPfq+dkfJIc>`Qe4p#@_mg z`XJE=sXUvS8QW*=fT-%AvC614K8vesm4V?BT*vtTzRxy>c{!~5`$|(}+1VmF_-TZ$ zF>+eKe>mWY+Z6D^Z1{-aBn*ZTX5xmCLIG=Ql}NY%SH>nD@hjvh=J5r(1dVxs90?>u zN{1of5j@ha&=hbzS-7UaT!Skh!(re}1m;-B9G+qSWuPb*6giI{qFa^I5?pN{Fv$gZ zvz4By3VgT*S4#}5eYM1-kbo3!EK-D$!sg>qFo}|XBUr+~8gHOX4&0M{Jj7@uhz;LN!YzWYZ&*W6%GdY#` zOb*3wUuXj2_t6!=*hJAB1Q5X+Ry^R1Hjlbi4G5VKWF>F_3(G{Xbkwy1ThalBArdFb zm&3Ck1bfE9=9vf!F48pF9-5xf*c>s65sBY8kP2OzkPR#^m^w9+E%VX6mjw;1XX z`B@Se&E(=dV9=Mvpo79%hd~6e$^yBWK@1P6=dswJvntt`lTK*LaZluQ6c5s+ZPWxz zCJwqst{%e~VNGEU(KBu|rNWudwS-rLu>5AI2w*wRa%Cec1z(4bK)DFVhHKN};(%oe zw#^JRNV&5XWf)x8l&$MfW`-97locVXe!2x#hm^Z$QHBwQP1&XnWoC>qK$)3!b1CJn zT9jd!>BQ2iZ5_%u(A3o|Y(tolZsHS4{>1MBqzu z_!kv?iiDI3wuk>d5eOlIu|l~PhW7Esj$|IWt$e=>^C|+40ItB?@ZUx#1Re?zq`Vcv zcOhorp`xM!z6!~bB?_`6C=DiORip~=)8L~3I7x$i6%vFniywTX^e6>NgE9mhtXBo~ z6^bQf3FH+^pf1pb@s9+hDM(ON6~F--(-KH&Kt62=S+r;o0R$4X1OQ+vJ$v>9SqPOU zC};_Bb8{mjtQzC=n=+@(Bctfy=IL-$)UgM`o3Ia%PX`y-)DMez1kaIA2bAWKm^UTL z6YIPR}G2r4sDuI*bC0b<&p9LkI;8V)s!4rqq3`__2 zZjF>8_7TL0a-Fk3PrAps}$cxj@wl$o7`WQU#H+ zY$;TR;g)8@(&VCSsZ1tSl}F@>u-r^pK2V&VAqV-joB{elB9x}*3e!cAmn)5}NGcTgdAT#j6n=_kvT z`(=Sn0RHJiQ7) zn)YZ_Ok82iDnlfZ$f&F+I3vD3o3a3#Y6>=`0RQI`C-4X898v+_o8a3YHr-vo2M)vc zcKA-=+e3l^Z-n0sR2A%Clg*L~hkz31C+`PNXr$HOT{XCGZPq2kyQcl*j;x2}nQ z_jF(JAWk#)P8Djt<>~ ztDAiNV)wp1o}IoZ>|3-nX7y+Hv(g7_?LNCW+okyXvu}gBCpzS{F8r&o@yXmlR~;S~ z%?-X&8Gh-WQQ2mvA>E(ed-JvX?c(jbLpl!J&@Y@nbz8-}^EGSV^s2P);dgvjo0opy zdl#)dIrL!Mo93H;8!77WONX`B1<%Z9*&NzzQIvE#UC`Y3{{F5jifXDa4wdY=Hhb&r z2^~jP4LqQ*8}%~eH`{YnlZHgSoLjtSNTLmk}7GLg^Qtla%y!AwB`708>+%fFv zcW1w?zI5--)J~^v*j-rG-*TwWa#PEhqLY3zcGgbtS<_J3=dlO(HabM;#*X`ZPA9{|vTV$Qz zEQo7zEiQh`kofoO;_m*{uC&$Y#N;D=ZC*`|zNj}R ze6XO?s@`9X-T=h2Oyu3xZ*U;O)_enE-yB~Ol=IVtw;dATI) z)!Oc(yEqm^Ow8&1U|*XM$GvXH@0NFcF~8Dk!`ffGSIxR!z4EomwF7+?Z<-PK_G06L z^6M_UG9&l7nRykp%Uk<+?r@_oZjCSbQQvWP zPAPG>7LA|WdO~`iM=76vJ2&n{O&h_5(&9buo|f;F?JIb9|99E`w~wAI+kZdDdywOe zR(9>yPq?9Y*h%r`P`izj6i?>dnDke*T(xU~NeXTlph8&6u zx)Z+L#xt;J`N|mymJ_G+%!tX}oi=fyw8}Vte33Z$E2FAiMGs~j81FrBk{LfG@10j- z?=Bv;cMrNh=Xvy9n7v?xMY!GS)>piW4z+!fGLhptbHnqVUmuIIE%@Tt*jl5RuXn%m zIIy%_W-_H2DUDy)k>j?1Xu#BVF1LGrdE?{S1m$$csO%0njy5kMczub9oLj+boYrn_8g zvUx-EmGKj1yUwpkzL*%FGx)--LUZ4zSDii`HipK*#6d;fS5zQF3($0y6T+!u`b`tZdJZ?XxhC# zk|U2tc5a;5cJ82^SC&0Z^cpEHk4wDRgH!n~pkG|;a|<&Z7i2V>dbZEHHRip7JXa>X z>bw0n$L+uM`D6O}yzS&dzfBcUQuB#xUrSCK+mD)()^fpv$uDB>KRQ@`e956?a_UTb(M2o$b8p$kDgE%Rl|` zhZXIoFKyCeOi8cu=dQle$760*A2D$pJa@{Gi}9zW9lG>m} zncaR=XmHDx!Am+AaoY$ziZgG^yaVoS9^QRsOu&M#S}pzD^R#EY|LJ2*7c73XcIR1> zg*zvl9Cc=9-)B98laBL-cUZS5^2CO@4>xyue7(xucQEH<L(KCW{m89Vc`8uq+74( zd!-q9r%uM^&mUBIE+_5ertiL++QquDi_Jo}(q=v}RY;#tdUW%uuW z@3lNH_2%WbF49M__;kDkpxD)rhsZ{dZX zdv_gk!n5>1+^EWfqia0}^&8ziYD$NjO|N>`q}R&AY-<-s^);KFvh~HikR(?V>GyL| z{+#?+?&$Q>aQE|H_FQ;dII`P@nAWmEcl}MS-x>Oqu{8GFeb2sky8hIDMA`1CCziGQ zz96sT?y3Fb7ax3iz-ZeGrxDKl#hv?cv!2>7C-*JFjHK(vk0OfCY*Vg1E4W_?wYbw(Islms3lM2YhH}6O@hf| z-RY&}FU8-MK}idkeB$nf_6&`gQ&Wi6BvU!Zjx;;yZ#V7rl(Br7?A&gvxvj6wIJ5D* z(X_iAEIWp{52|@$S?a_0`$D*HiMV|6HV719-=W z@813M4RzBwTwgepWoXd_Xj+$^C0KNST>|V?h^Dqb=u>M=!mh}k)oUs?hvklTC$QDe zro^6NYbagRM~P0j*)-TjprMfu>s@VW>M@Dv{>HG|fSX0eBoSJl1N%ILEQ39{Wm+p= zC?K-{HcJbJc(BVsm|upl()ncwb1v*`zy)og|FYyCPRP7o`0Ez%v6)do~pLcerH}84 zdti4cb6hw>f%bsBvA=slVsfzC4Vc&ySjGdaaOiJU&In$LqxP{3->3G#m*~nIVxq>G zGNg&R#+(UY_JVI!j!Sye-4~|J2!5XiHMpqNMR!F(j-FA)K`0!rj@M#JwaFdui=pvR9Dr9emxxsP$C_CCH8EU_p>B#@;E`oU(kAO*ITVaq=! zC0m>fZvbH65#)$6g;KdVB?plZAWXqmB=9Jd3&x5i5<#*^Aj%h|m zmW>qv@f?u^HjDx6nIe;>im_gf0Nw>4nG~5MHxshq0Ro{kRS+I15M~26c>j`Il%A+x^khCVjjG|p-n;ZS=q1?pDjp%eP-a8BZhX#vAqo2 zE&@00Hvq7|&E%Ck{*V{RQ~U&iuoQW&P$C(})D`6mGqXSlAd{PeZyk_P6m0kpXami{ zB2+AWgQV7|5VVj5Ki-6G!ltK*vvcGE3A|HL=@T~o1#VjJ6x{r}f#HB4`Iw&n{T z9`9eWG|luENwpgY%ZjM~9BcdMr@sTirZm&v%+8uTT3cT;O`cAFJvDhc{cWttGt*y9 zo|*n?@-QLdxHkfY&_f9agTFC3Y{3w^sJH~v z=`84i@4#4zhHCpQOgsLz-$I>#!EbS;hklDek;7qTYN%*b??=2C>eY7{ z!+KIiPx)uUaXLI*`}cm2I2a_r37YDvkC&zcFm9 zc;k0ND&j;kvmuBL#QD4Y8%VanX#W;}^b4JHadZnobNr21fXQNy;qP#u=Az+{lUR}= z%mKI6l%VtWg)=hQu<(-Q2nNbBMZ#2>1_z4uUL5#UX;_HRJ`}KiJKPm&sJIDIWr9d? zO13OVmL?ZOA9?7n=b;ZtE9JUUc62sa~%C1*$agKS6v! A1ONa4 literal 0 HcmV?d00001 diff --git a/rulebook/pom.xml b/rulebook/pom.xml new file mode 100644 index 0000000000..2a42e36d93 --- /dev/null +++ b/rulebook/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + com.baeldung.rulebook + rulebook + 1.0.0-SNAPSHOT + + + + com.deliveredtechnologies + rulebook-core + 0.6.2 + + + \ No newline at end of file diff --git a/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java b/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java new file mode 100644 index 0000000000..c09772a3c6 --- /dev/null +++ b/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java @@ -0,0 +1,17 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder; +import com.deliveredtechnologies.rulebook.model.RuleBook; + +public class HelloWorldRule { + public RuleBook defineHelloWorldRules() { + + return RuleBookBuilder.create() + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.print("Hello "))) + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.println("World"))) + .build(); + + } +} diff --git a/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java b/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java new file mode 100644 index 0000000000..57965457ec --- /dev/null +++ b/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java @@ -0,0 +1,12 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.FactMap; + +public class Launcher { + + public static void main(String[] args) { + HelloWorldRule ruleBook = new HelloWorldRule(); + ruleBook.defineHelloWorldRules() + .run(new FactMap<>()); + } +} diff --git a/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java b/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java new file mode 100644 index 0000000000..ca6018a21e --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java @@ -0,0 +1,70 @@ +package com.baeldung.autowired; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Service; + +@SpringBootApplication +public class TypesOfBeanInjectionSpring { + private final UserService userService; + + @Autowired // the @Autowired can even be omitted, in case there's only one explicit constructor + public TypesOfBeanInjectionSpring(UserService userService) { + this.userService = userService; + } + + public static void main(String[] args) { + SpringApplication.run(TypesOfBeanInjectionSpring.class, args); + } + + @Bean + CommandLineRunner runIt() { + return args -> { + userService.listUsers() + .stream() + .forEach(System.out::println); + }; + } +} + +class User { + private String name; + + public User(String name) { + this.name = name; + } + + // getters and setters ... + public String getName() { + return this.name; + } + + public String toString() { + return name; + } + +} + +interface UserService { + List listUsers(); +} + +@Service +class UserServiceImpl implements UserService { + + @Override + public List listUsers() { + ArrayList users = new ArrayList<>(3); + users.add(new User("Snoopy")); + users.add(new User("Woodstock")); + users.add(new User("Charlie Brown")); + return users; + } + +} diff --git a/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java b/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java new file mode 100644 index 0000000000..206a062a57 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.autowired; + +import org.junit.Assert; +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; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TypesOfBeanInjectionSpringIntegrationTest { + @Autowired + UserService userService; + + private static final String[] expected = new String[] { "Snoopy", "Woodstock", "Charlie Brown" }; + + @Test + public void givenDI_whenInjectObject_thenUserNamesAreListed() { + Assert.assertArrayEquals(expected, userService.listUsers() + .stream() + .map(User::getName) + .toArray()); + } +} From c8c0c1e51dcd611f111bf7baf887ddd71e24bec9 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Thu, 17 Aug 2017 03:12:07 +0530 Subject: [PATCH 55/67] undertow (#2426) * moving jmh into libraries module * refactoring jmh * Update pom.xml * manual algorightm * with BM result * fix for space issue * Fixed indentation * change as per suggestion * vavr either * adding unit test and othe rutilities * adding concurrent module * concurrent package description * concurrent package description * Update EitherUnitTest.java * introducing lambda expression * jooby project * jooby project * reducing employee bean content * bootique module * bootique * bootique * undertow module * undertow module * refactoring * using lambda * as per baeldung formatter --- pom.xml | 1 + undertow/pom.xml | 58 ++++++++++++++ .../com/baeldung/undertow/SimpleServer.java | 16 ++++ .../com/baeldung/undertow/ftp/FileServer.java | 20 +++++ .../secure/CustomIdentityManager.java | 77 +++++++++++++++++++ .../undertow/secure/SecureServer.java | 52 +++++++++++++ .../undertow/socket/SocketServer.java | 36 +++++++++ 7 files changed, 260 insertions(+) create mode 100644 undertow/pom.xml create mode 100644 undertow/src/main/java/com/baeldung/undertow/SimpleServer.java create mode 100644 undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java create mode 100644 undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java create mode 100644 undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java create mode 100644 undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java diff --git a/pom.xml b/pom.xml index 8b3df8de0d..99e9d5a7e3 100644 --- a/pom.xml +++ b/pom.xml @@ -237,6 +237,7 @@ liquibase spring-boot-property-exp mockserver + undertow diff --git a/undertow/pom.xml b/undertow/pom.xml new file mode 100644 index 0000000000..a0f2dc53ee --- /dev/null +++ b/undertow/pom.xml @@ -0,0 +1,58 @@ + + 4.0.0 + com.baeldung.undertow + undertow + jar + 1.0-SNAPSHOT + undertow + http://maven.apache.org + + + 1.8 + 1.8 + + + + + io.undertow + undertow-core + 1.4.18.Final + + + io.undertow + undertow-servlet + 1.4.18.Final + + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.baeldung.undertow.SimpleServer + + + + + + + + \ No newline at end of file diff --git a/undertow/src/main/java/com/baeldung/undertow/SimpleServer.java b/undertow/src/main/java/com/baeldung/undertow/SimpleServer.java new file mode 100644 index 0000000000..7f869746be --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/SimpleServer.java @@ -0,0 +1,16 @@ +package com.baeldung.undertow; + +import io.undertow.Undertow; +import io.undertow.util.Headers; + +public class SimpleServer { + + public static void main(String[] args) { + Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(exchange -> { + exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); + exchange.getResponseSender().send("Hello Baeldung"); + }).build(); + server.start(); + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java new file mode 100644 index 0000000000..90cad9ebbd --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java @@ -0,0 +1,20 @@ +package com.baeldung.undertow.ftp; + +import java.nio.file.Paths; + +import io.undertow.Undertow; +import io.undertow.server.handlers.resource.PathResourceManager; + +import static io.undertow.Handlers.resource; + +public class FileServer { + + public static void main(String[] args) { + Undertow server = Undertow.builder().addHttpListener(8080, "localhost") + .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100)) + .setDirectoryListingEnabled(true)) + .build(); + server.start(); + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java new file mode 100644 index 0000000000..e0984f65a5 --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java @@ -0,0 +1,77 @@ +package com.baeldung.undertow.secure; + +import java.security.Principal; +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import io.undertow.security.idm.Account; +import io.undertow.security.idm.Credential; +import io.undertow.security.idm.PasswordCredential; + +public class CustomIdentityManager implements io.undertow.security.idm.IdentityManager { + + private final Map users; + + CustomIdentityManager(final Map users) { + this.users = users; + } + + @Override + public Account verify(Account account) { + return account; + } + + @Override + public Account verify(Credential credential) { + return null; + } + + @Override + public Account verify(String id, Credential credential) { + Account account = getAccount(id); + if (account != null && verifyCredential(account, credential)) { + return account; + } + return null; + } + + private boolean verifyCredential(Account account, Credential credential) { + if (credential instanceof PasswordCredential) { + char[] password = ((PasswordCredential) credential).getPassword(); + char[] expectedPassword = users.get(account.getPrincipal().getName()); + + return Arrays.equals(password, expectedPassword); + } + return false; + } + + private Account getAccount(final String id) { + if (users.containsKey(id)) { + return new Account() { + + private static final long serialVersionUID = 1L; + + private final Principal principal = new Principal() { + @Override + public String getName() { + return id; + } + }; + + @Override + public Principal getPrincipal() { + return principal; + } + + @Override + public Set getRoles() { + return Collections.emptySet(); + } + }; + } + return null; + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java new file mode 100644 index 0000000000..6f520944db --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java @@ -0,0 +1,52 @@ +package com.baeldung.undertow.secure; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.undertow.Undertow; +import io.undertow.io.IoCallback; +import io.undertow.security.api.AuthenticationMechanism; +import io.undertow.security.api.AuthenticationMode; +import io.undertow.security.api.SecurityContext; +import io.undertow.security.handlers.AuthenticationCallHandler; +import io.undertow.security.handlers.AuthenticationConstraintHandler; +import io.undertow.security.handlers.AuthenticationMechanismsHandler; +import io.undertow.security.handlers.SecurityInitialHandler; +import io.undertow.security.idm.IdentityManager; +import io.undertow.security.impl.BasicAuthenticationMechanism; +import io.undertow.server.HttpHandler; +import io.undertow.server.HttpServerExchange; + +public class SecureServer { + + public static void main(String[] args) { + final Map users = new HashMap<>(2); + users.put("root", "password".toCharArray()); + users.put("admin", "password".toCharArray()); + + final IdentityManager idm = new CustomIdentityManager(users); + + Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity((exchange) -> { + final SecurityContext context = exchange.getSecurityContext(); + exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), + IoCallback.END_EXCHANGE); + }, idm)).build(); + + server.start(); + + } + + private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) { + HttpHandler handler = toWrap; + handler = new AuthenticationCallHandler(handler); + handler = new AuthenticationConstraintHandler(handler); + final List mechanisms = Collections + . singletonList(new BasicAuthenticationMechanism("Baeldung_Realm")); + handler = new AuthenticationMechanismsHandler(handler, mechanisms); + handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler); + return handler; + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java new file mode 100644 index 0000000000..9e0e065c3a --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java @@ -0,0 +1,36 @@ +package com.baeldung.undertow.socket; + +import io.undertow.Undertow; +import io.undertow.server.handlers.resource.ClassPathResourceManager; +import io.undertow.websockets.core.AbstractReceiveListener; +import io.undertow.websockets.core.BufferedTextMessage; +import io.undertow.websockets.core.WebSocketChannel; +import io.undertow.websockets.core.WebSockets; + +import static io.undertow.Handlers.path; +import static io.undertow.Handlers.resource; +import static io.undertow.Handlers.websocket; + +public class SocketServer { + + public static void main(String[] args) { + Undertow server = Undertow.builder().addHttpListener(8080, "localhost") + .setHandler(path().addPrefixPath("/baeldungApp", websocket((exchange, channel) -> { + channel.getReceiveSetter().set(new AbstractReceiveListener() { + @Override + protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { + final String messageData = message.getData(); + for (WebSocketChannel session : channel.getPeerConnections()) { + WebSockets.sendText(messageData, session, null); + } + } + }); + channel.resumeReceives(); + })).addPrefixPath("/", resource(new ClassPathResourceManager(SocketServer.class.getClassLoader(), + SocketServer.class.getPackage())).addWelcomeFiles("index.html"))) + .build(); + + server.start(); + } + +} From 04689cc2498b6661dfdcbb06be239d7c091de0d9 Mon Sep 17 00:00:00 2001 From: Rokon Uddin Ahmed Date: Thu, 17 Aug 2017 21:41:57 +0600 Subject: [PATCH 56/67] pull 16.08 (#2454) * Update README.md * Update README.md * Create README.md * Create README.md * Create README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.MD * Create README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Update README.MD * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md --- asciidoctor/README.md | 3 ++- kotlin/README.md | 7 +++++++ libraries/README.md | 1 + ratpack/README.md | 1 + spring-5/README.md | 3 +-- spring-activiti/README.md | 3 +++ spring-cloud-bus/README.md | 3 +++ spring-core/README.md | 2 ++ spring-rest/README.md | 1 + testing/README.md | 1 + vavr/README.md | 1 + 11 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 spring-activiti/README.md create mode 100644 spring-cloud-bus/README.md diff --git a/asciidoctor/README.md b/asciidoctor/README.md index 164200d227..3c602b6abd 100644 --- a/asciidoctor/README.md +++ b/asciidoctor/README.md @@ -1,3 +1,4 @@ ### Relevant articles -- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor) \ No newline at end of file +- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor) +- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book) diff --git a/kotlin/README.md b/kotlin/README.md index 6b3fb93dcc..91933e94dc 100644 --- a/kotlin/README.md +++ b/kotlin/README.md @@ -7,3 +7,10 @@ - [Difference Between “==” and “===” in Kotlin](http://www.baeldung.com/kotlin-equality-operators) - [Generics in Kotlin](http://www.baeldung.com/kotlin-generics) - [Introduction to Kotlin Coroutines](http://www.baeldung.com/kotlin-coroutines) +- [Destructuring Declarations in Kotlin](http://www.baeldung.com/kotlin-destructuring-declarations) +- [Kotlin with Mockito](http://www.baeldung.com/kotlin-mockito) +- [Lazy Initialization in Kotlin](http://www.baeldung.com/kotlin-lazy-initialization) +- [Overview of Kotlin Collections API](http://www.baeldung.com/kotlin-collections-api) +- [Converting a List to Map in Kotlin](http://www.baeldung.com/kotlin-list-to-map) +- [Data Classes in Kotlin](http://www.baeldung.com/kotlin-data-classes) + diff --git a/libraries/README.md b/libraries/README.md index 88075af390..ed6d214c7a 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -23,6 +23,7 @@ - [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave) - [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) - [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) +- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text) - [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) diff --git a/ratpack/README.md b/ratpack/README.md index 91c8e025f0..8215f74148 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -2,3 +2,4 @@ - [Introduction to Ratpack](http://www.baeldung.com/ratpack) - [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice) +- [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) diff --git a/spring-5/README.md b/spring-5/README.md index 03b8121f90..4ce0fd4c79 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -8,5 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) - [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) - - +- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) diff --git a/spring-activiti/README.md b/spring-activiti/README.md new file mode 100644 index 0000000000..fc6eea7f87 --- /dev/null +++ b/spring-activiti/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [A Guide to Activiti with Java](http://www.baeldung.com/java-activiti) diff --git a/spring-cloud-bus/README.md b/spring-cloud-bus/README.md new file mode 100644 index 0000000000..c5410ca4e2 --- /dev/null +++ b/spring-cloud-bus/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [Spring Cloud Bus](http://www.baeldung.com/spring-cloud-bus) diff --git a/spring-core/README.md b/spring-core/README.md index b0d0b8408c..237f8cd4e9 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -6,4 +6,6 @@ - [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok) - [A Quick Guide to Spring @Value](http://www.baeldung.com/spring-value-annotation) - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) +- [Introduction to Spring’s StreamUtils](http://www.baeldung.com/spring-stream-utils) - [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) + diff --git a/spring-rest/README.md b/spring-rest/README.md index 66c893e45f..2cea315188 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -15,3 +15,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Custom Media Type for a Spring REST API](http://www.baeldung.com/spring-rest-custom-media-type) - [HTTP PUT vs HTTP PATCH in a REST API](http://www.baeldung.com/http-put-patch-difference-spring) - [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate) +- [Spring – Log Incoming Requests](http://www.baeldung.com/spring-http-logging) diff --git a/testing/README.md b/testing/README.md index 6338a52f3d..a691737e4f 100644 --- a/testing/README.md +++ b/testing/README.md @@ -12,3 +12,4 @@ - [Testing with Google Truth](http://www.baeldung.com/google-truth) - [Testing with JGoTesting](http://www.baeldung.com/jgotesting) - [Introduction to JUnitParams](http://www.baeldung.com/junit-params) +- [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support) diff --git a/vavr/README.md b/vavr/README.md index c4155c2680..d7816f3f9f 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -5,3 +5,4 @@ - [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing) - [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr) - [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr) + From ee9152a091831948b8cb7271d7ee331cb8f06cbe Mon Sep 17 00:00:00 2001 From: "Eunice A. Obugyei" Date: Sat, 19 Aug 2017 03:08:06 +0000 Subject: [PATCH 57/67] BAEL-1014 [Spring MVC with Kotlin] (#2459) * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Removed unnecessary comment * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] Added Exception test cases * Applied baeldung formatter in Eclipse * Merged from https://github.com/eugenp/tutorials Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Revert "Merged from https://github.com/eugenp/tutorials" This reverts commit 74447a163b9e3f244a2578315fbdb525d20cd16b. * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Spring Security for a Java EE Application[http://jira.baeldung.com/browse/BAEL-884] * Updated spring-security version to 4.2.3.RELEASE * Added spring-mvc-kotlin module for http://jira.baeldung.com/browse/BAEL-1014 --- pom.xml | 1 + spring-mvc-kotlin/pom.xml | 79 +++++++++++++++++++ .../kotlin/mvc/ApplicationWebConfig.kt | 37 +++++++++ .../kotlin/mvc/ApplicationWebInitializer.kt | 19 +++++ .../main/webapp/WEB-INF/spring-web-config.xml | 24 ++++++ .../src/main/webapp/WEB-INF/view/welcome.jsp | 7 ++ .../src/main/webapp/WEB-INF/web.xml | 24 ++++++ 7 files changed, 191 insertions(+) create mode 100644 spring-mvc-kotlin/pom.xml create mode 100644 spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt create mode 100644 spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt create mode 100644 spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml create mode 100644 spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp create mode 100755 spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml diff --git a/pom.xml b/pom.xml index 99e9d5a7e3..f2dd0ae48c 100644 --- a/pom.xml +++ b/pom.xml @@ -175,6 +175,7 @@ spring-mvc-webflow spring-mvc-xml spring-mvc-simple + spring-mvc-kotlin spring-security-openid spring-protobuf spring-quartz diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml new file mode 100644 index 0000000000..087f02fc68 --- /dev/null +++ b/spring-mvc-kotlin/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + spring-mvc-kotlin + 0.1-SNAPSHOT + + spring-mvc-kotlin + + war + + + + org.jetbrains.kotlin + kotlin-stdlib-jre8 + 1.1.4 + + + org.jetbrains.kotlin + kotlin-reflect + 1.1.4 + + + + org.springframework + spring-web + 4.3.10.RELEASE + + + org.springframework + spring-webmvc + 4.3.10.RELEASE + + + javax.servlet + jstl + 1.2 + + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + kotlin-maven-plugin + org.jetbrains.kotlin + 1.1.4 + + + + compile + compile + + compile + + + + + test-compile + test-compile + + test-compile + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt new file mode 100644 index 0000000000..4907e46efb --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt @@ -0,0 +1,37 @@ +package com.baeldung.kotlin.mvc + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.servlet.ViewResolver +import org.springframework.web.servlet.config.annotation.EnableWebMvc +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter +import org.springframework.web.servlet.view.InternalResourceViewResolver +import org.springframework.web.servlet.view.JstlView + + + + + +@EnableWebMvc +@Configuration +open class ApplicationWebConfig: WebMvcConfigurerAdapter() { + + override fun addViewControllers(registry: ViewControllerRegistry?) { + super.addViewControllers(registry) + + registry!!.addViewController("/welcome.html") + } + + @Bean + open fun viewResolver(): ViewResolver { + val bean = InternalResourceViewResolver() + + bean.setViewClass(JstlView::class.java) + bean.setPrefix("/WEB-INF/view/") + bean.setSuffix(".jsp") + + return bean + } + +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt new file mode 100644 index 0000000000..a4d1614271 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt @@ -0,0 +1,19 @@ +package com.baeldung.kotlin.mvc + +import com.baeldung.kotlin.mvc.ApplicationWebConfig +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer + +class ApplicationWebInitializer: AbstractAnnotationConfigDispatcherServletInitializer() { + + override fun getRootConfigClasses(): Array>? { + return null + } + + override fun getServletMappings(): Array { + return arrayOf("/") + } + + override fun getServletConfigClasses(): Array> { + return arrayOf(ApplicationWebConfig::class.java) + } +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml b/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml new file mode 100644 index 0000000000..ffe83a66fa --- /dev/null +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp new file mode 100644 index 0000000000..bdb6716889 --- /dev/null +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp @@ -0,0 +1,7 @@ + + Welcome + + +

This is the body of the welcome view 2

+ + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml b/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 0000000000..cbee6a1b11 --- /dev/null +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + Spring Kotlin MVC Application + + + spring-web-mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + contextConfigLocation + /WEB-INF/spring-web-config.xml + + + + + spring-web-mvc + / + + + \ No newline at end of file From f2efbd9a67ee3cadf256ef6bca332539befc8d13 Mon Sep 17 00:00:00 2001 From: felipeazv Date: Sat, 19 Aug 2017 16:40:45 +0200 Subject: [PATCH 58/67] BAEL-812: moving examples to rule-engines folder (#2461) * spring beans DI examples * fix-1: shortening examples * List of Rules Engines in Java * BAEL-812: Openl-Tablets example added * BAEL-812: artifacts names changed * BAEL-812: moving rule-engines examples to rule-engines folder * BAEL-812: removing evaluation article files * BAEL-812: folder renamed * BAEL-812: folder renamed * BAEL-812: pom.xml - parent added --- rule-engines/easy-rules/pom.xml | 24 ++++++++++++++ .../baeldung/easyrules/HelloWorldRule.java | 20 +++++++++++ .../java/com/baeldung/easyrules/Launcher.java | 21 ++++++++++++ rule-engines/openl-tablets/pom.xml | 29 ++++++++++++++++ .../com/baeldung/openltablets/model/Case.java | 23 +++++++++++++ .../baeldung/openltablets/model/Greeting.java | 20 +++++++++++ .../com/baeldung/openltablets/model/User.java | 14 ++++++++ .../baeldung/openltablets/rules/IRule.java | 7 ++++ .../com/baeldung/openltablets/rules/Main.java | 31 ++++++++++++++++++ .../baeldung/openltablets/rules/Response.java | 24 ++++++++++++++ .../main/resources/openltablets/HelloUser.xls | Bin 0 -> 25088 bytes rule-engines/rulebook/pom.xml | 24 ++++++++++++++ .../com/baeldung/rulebook/HelloWorldRule.java | 17 ++++++++++ .../java/com/baeldung/rulebook/Launcher.java | 12 +++++++ 14 files changed, 266 insertions(+) create mode 100644 rule-engines/easy-rules/pom.xml create mode 100644 rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java create mode 100644 rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java create mode 100644 rule-engines/openl-tablets/pom.xml create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java create mode 100644 rule-engines/openl-tablets/src/main/resources/openltablets/HelloUser.xls create mode 100644 rule-engines/rulebook/pom.xml create mode 100644 rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java create mode 100644 rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java diff --git a/rule-engines/easy-rules/pom.xml b/rule-engines/easy-rules/pom.xml new file mode 100644 index 0000000000..78edc09d1a --- /dev/null +++ b/rule-engines/easy-rules/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.baeldung.easyrules + easy-rules + 1.0 + + easy-rules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.jeasy + easy-rules-core + 3.0.0 + + + \ No newline at end of file diff --git a/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java new file mode 100644 index 0000000000..5448eabf2a --- /dev/null +++ b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java @@ -0,0 +1,20 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.annotation.Action; +import org.jeasy.rules.annotation.Condition; +import org.jeasy.rules.annotation.Rule; + +@Rule(name = "Hello World rule", description = "Always say hello world") +public class HelloWorldRule { + + @Condition + public boolean when() { + return true; + } + + @Action + public void then() throws Exception { + System.out.println("hello world"); + } + +} diff --git a/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java new file mode 100644 index 0000000000..427e3eace0 --- /dev/null +++ b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java @@ -0,0 +1,21 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.api.Facts; +import org.jeasy.rules.api.Rules; +import org.jeasy.rules.api.RulesEngine; +import org.jeasy.rules.core.DefaultRulesEngine; + +public class Launcher { + public static void main(String... args) { + // create facts + Facts facts = new Facts(); + + // create rules + Rules rules = new Rules(); + rules.register(new HelloWorldRule()); + + // create a rules engine and fire rules on known facts + RulesEngine rulesEngine = new DefaultRulesEngine(); + rulesEngine.fire(rules, facts); + } +} diff --git a/rule-engines/openl-tablets/pom.xml b/rule-engines/openl-tablets/pom.xml new file mode 100644 index 0000000000..e983d4e566 --- /dev/null +++ b/rule-engines/openl-tablets/pom.xml @@ -0,0 +1,29 @@ + + 4.0.0 + + com.baeldung.openltablets + openl-tablets + 1.0 + + openl-tablets + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.openl + org.openl.core + 5.19.4 + + + org.openl.rules + org.openl.rules + 5.19.4 + + + \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java new file mode 100644 index 0000000000..f9f5f4bd5f --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java @@ -0,0 +1,23 @@ +package com.baeldung.openltablets.model; + +public class Case { + + private User user; + private int hourOfDay; + + public User getUser() { + return user; + } + + public void setUser(final User user) { + this.user = user; + } + + public int getHourOfDay() { + return hourOfDay; + } + + public void setHourOfDay(final int hourOfDay) { + this.hourOfDay = hourOfDay; + } +} diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java new file mode 100644 index 0000000000..5dc7bcd117 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java @@ -0,0 +1,20 @@ +package com.baeldung.openltablets.model; + +public enum Greeting { + + GOOD_MORNING("Good Morning"), + GOOD_AFTERNOON("Good Afternoon"), + GOOD_EVENING("Good Evening"), + GOOD_NIGHT("Good Night"); + + private final String literal; + + private Greeting(final String literal) { + this.literal = literal; + } + + public String getLiteral() { + return literal; + } + +} \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java new file mode 100644 index 0000000000..8e45487497 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java @@ -0,0 +1,14 @@ +package com.baeldung.openltablets.model; + +public class User { + + private String name; + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java new file mode 100644 index 0000000000..857a6433ef --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java @@ -0,0 +1,7 @@ +package com.baeldung.openltablets.rules; + +import com.baeldung.openltablets.model.Case; + +public interface IRule { + void helloUser(final Case aCase, final Response response); +} \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java new file mode 100644 index 0000000000..34f5c48ed1 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java @@ -0,0 +1,31 @@ +package com.baeldung.openltablets.rules; + + +import java.time.LocalDateTime; + +import org.openl.rules.runtime.RulesEngineFactory; +import org.openl.runtime.EngineFactory; + +import com.baeldung.openltablets.model.Case; +import com.baeldung.openltablets.model.User; + +public class Main { + private IRule instance; + + public static void main(String[] args) { + Main rules = new Main(); + User user = new User(); + user.setName("Donald Duck"); + Case aCase = new Case(); + aCase.setUser(user); + aCase.setHourOfDay(23); + rules.process(aCase); + } + + public void process(Case aCase) { + final EngineFactory engineFactory = new RulesEngineFactory(getClass().getClassLoader() + .getResource("openltablets/HelloUser.xls"), IRule.class); + instance = engineFactory.newEngineInstance(); + instance.helloUser(aCase, new Response()); + } +} diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java new file mode 100644 index 0000000000..27fa634866 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java @@ -0,0 +1,24 @@ +package com.baeldung.openltablets.rules; + +import java.util.HashMap; +import java.util.Map; + +public class Response { + private String result; + private Map map = new HashMap<>(); + + public Response() { } + + public String getResult() { + return result; + } + + public void setResult(final String s) { + result = s; + } + + public Map getMap() { + return map; + } + +} diff --git a/rule-engines/openl-tablets/src/main/resources/openltablets/HelloUser.xls b/rule-engines/openl-tablets/src/main/resources/openltablets/HelloUser.xls new file mode 100644 index 0000000000000000000000000000000000000000..1e85d0ce2de54ddc812ec9639211a313a5024b45 GIT binary patch literal 25088 zcmeHv2Ut{B)9~44ft8{(5m8`4P>>?Uf-QiE9YLBEae)O^mt6u2q7lWGh%t&imY66p z8Vh!eVnK}s#S&{2dyR^QSYwI%&78aSvWw(>^Zn2Ne$RWCbN8M(b7tnunVD1WVb7el zzPWOX<1NCvJ|RZrgQ5{J(Smc}856y%2;ss5=07MD3I<3BJpT9k57NM2AgiCU58J`F zF(mABQ%HPBjUbspGKXXV$r4gyNKGJt2@q>YHjr!~*+FUw$sSTONDh#iLvn=F0#Zvz zPLP}-xj+&?a)smusTCx5NFI<{Luv!b6OtFCwvfCb`9Si8g!ZON|3Rw$|5DT#B7=_{ z`XYiz;X9j*0}VI)vImP%H4I~cfR9mukP3Pyz3|Je*6Eu(t8<*5Y)V zz&)FcA<0yZFPdzR(M4R3`|L6EQqX8C1P@PbGhBQ$zVa@^#ME%e4tJ>w6UAhzkT*5D#L31Tt4w`v+c4!z~UgGtztRG zcN}97j^j!wBpgQuKthUl0TIUv#OWoHh_k>=L*cpb&-=&KaRl=J&Q+iM+zTf!Eca_+ zHGeV4@AIY<F)Tz?^{T z0>S^As|S@qNMm~iD7!m{4?5>Uoad3{@NEq<3)CURf4JMy`zDILhu*u>SqUNULq50! z0|xfk5N;^N`-_zV7_t;@D-Dav6H!EoG~X1VzU_Hv4pTn$v=4c03a2V~Y?+LC++tqf7uHQ~fTYcgPL!BHjvW@g_3(GWFfc6t38aVA%x zHeXe{#*`CIbtQ&T9rYFfUW^#lAHm>|_9_Vt(9mkX0Sp2(l=?G>q1LcLj88sF!|tOP z-9CcBAzeSxT8ymqw}lJw$1p})k^vUnRgGcE>K6e-S}{onJCM^p^5J|;Cf-Leu7aI? ztX&+i6{Vf(=>Y+?MYZ?U@Hw$CKT8K&6%hf6Cw+-C&kzs^L${118bcmUk%;}t!ISm;D^F0s4I&X2*GB@fV4P< zglKrSht(9U_0&97^_3#1>Qc^{dN-AG)|U!Uiu$S$ARGfFg}+c0)DOoHrVrl`9I5KV z|Gy09pz*0MMxQv#pnBM@EZ}`h^ELb) zg`cOBO9*a^J>YCmm;OGAUl+c^0Gy#;7k`@pd`6#j@tOAGZjf%f7(L?-k*=H@DSZw^ zGYYQ-1bV6BMq9mboK@@6Vfr0+s3?57wY9yuJ?N9MXPhtSqmQd^3J3i&dS>*`foQA` zA9uAVoE6`2cCQbPs{(y+2NnE0T{OTZ7}H+dC8PKZ9LO?o+&NRi1+eac>MS@*9^7S9 z;tL7+L`|Oq5ud_YdIofe-9S1EpYUSno5B-?=To2>jyVdCHUJOR2ZvVVtMt6gPBo5j zaE#99Sa&68=WMtNe?t=uK4?izhk-M4)}^n3>(bZ2_0b19{z|w~57-(ir@xX88y;*3 zA2&v!U2J@RefoiJwK4!_^@}l;2k`T;Mj_~Jh70NkR%ak5g)0eZ_hVf+B2oNkCAyBB zu;;7Rvv$7-U`eae8w1zai3+aWUx4pvO|_t_2MV_;cLMo!_=5g}b>(5&>#Eb<34A*; z0hhw+YdA484W3iL4HyS2_!LI>CuulvV!N}JDBB)2hL@*pSfC#=jFiZqv=SPWD4XD3& zFwi!DNd3J7{?QO3_4f{j@CHayfA4??G=xa~y@P{510<=xcko@!M~MUm)!#e#vZnz= z>hB%g0c-$~`g;dP!iEs3zjp);BT|3wKrm~FB=z@>o0W%>(fXMVx(;Fbq9men2ntii3YGV1!&KgsIX3S4ZzR)C@Es7s`CLx?Cslu^n6kuD7( zqMke`iLf;cyPQf5>uW!^fFIB5l5S9eXL!1gHo>n zGkC8K&$t8uOYy+f2ePqdvk9!r#;qPUff_c(qO|vSFY0Gw!)6mymrd(>*q{R{TVo<^jKP}de~@N zTGfC*Pi)lB#(~X7kEOM#hmE$SRSl@FuGY_{Ih&0hOY^RWjkcv#4N%-)qMwZ;n~fez zYgZ2&ZA+^fu=mna{cKvW+32yfpnBM7TUynCBR99}XVVhdbgbXf1i+?a11v2tX!ef= z`o@XPMvtYr*TY8J(gK5CY@VjSHO_1{dMwSe9yZ#R78q1nS*f3m3!9A|OY^CRjkcu) z1}QG5>1QKgv(aN|{`IiYwzR;YWe4x;XXDCdqsP+P*TY8J(gK5iJTqG#8$NM^z(;z> zGUxF->yDWmM}-mTK~Ej1f}=4^op70o<0C%fT2?teTEL-DSU!Z`lBDEHWb^prbcu28 z6{aK{4y#B=3LK%609l+T;-HI!a5|_Wifda+)CA71Vj)hyIDo93Ez~f9pQ9p zQxN8%Bv&F7q>2OyqHJ-RI7Rs24v4mpC0a8@QxNST2!(aRSIFRjO79@(byJR!5~OCF0`Ogv{q!!0}z^HTAS9OqUVQ33|=YR0)nY zW&d2a`AD>lhA0FSHc?j=QSBf?$diHq{X{)AL?L{ziF&YzYKIJF2ck|#p`>0Kq7W?D zM7>xffXa8IPfq+dkfJIc>`Qe4p#@_mg z`XJE=sXUvS8QW*=fT-%AvC614K8vesm4V?BT*vtTzRxy>c{!~5`$|(}+1VmF_-TZ$ zF>+eKe>mWY+Z6D^Z1{-aBn*ZTX5xmCLIG=Ql}NY%SH>nD@hjvh=J5r(1dVxs90?>u zN{1of5j@ha&=hbzS-7UaT!Skh!(re}1m;-B9G+qSWuPb*6giI{qFa^I5?pN{Fv$gZ zvz4By3VgT*S4#}5eYM1-kbo3!EK-D$!sg>qFo}|XBUr+~8gHOX4&0M{Jj7@uhz;LN!YzWYZ&*W6%GdY#` zOb*3wUuXj2_t6!=*hJAB1Q5X+Ry^R1Hjlbi4G5VKWF>F_3(G{Xbkwy1ThalBArdFb zm&3Ck1bfE9=9vf!F48pF9-5xf*c>s65sBY8kP2OzkPR#^m^w9+E%VX6mjw;1XX z`B@Se&E(=dV9=Mvpo79%hd~6e$^yBWK@1P6=dswJvntt`lTK*LaZluQ6c5s+ZPWxz zCJwqst{%e~VNGEU(KBu|rNWudwS-rLu>5AI2w*wRa%Cec1z(4bK)DFVhHKN};(%oe zw#^JRNV&5XWf)x8l&$MfW`-97locVXe!2x#hm^Z$QHBwQP1&XnWoC>qK$)3!b1CJn zT9jd!>BQ2iZ5_%u(A3o|Y(tolZsHS4{>1MBqzu z_!kv?iiDI3wuk>d5eOlIu|l~PhW7Esj$|IWt$e=>^C|+40ItB?@ZUx#1Re?zq`Vcv zcOhorp`xM!z6!~bB?_`6C=DiORip~=)8L~3I7x$i6%vFniywTX^e6>NgE9mhtXBo~ z6^bQf3FH+^pf1pb@s9+hDM(ON6~F--(-KH&Kt62=S+r;o0R$4X1OQ+vJ$v>9SqPOU zC};_Bb8{mjtQzC=n=+@(Bctfy=IL-$)UgM`o3Ia%PX`y-)DMez1kaIA2bAWKm^UTL z6YIPR}G2r4sDuI*bC0b<&p9LkI;8V)s!4rqq3`__2 zZjF>8_7TL0a-Fk3PrAps}$cxj@wl$o7`WQU#H+ zY$;TR;g)8@(&VCSsZ1tSl}F@>u-r^pK2V&VAqV-joB{elB9x}*3e!cAmn)5}NGcTgdAT#j6n=_kvT z`(=Sn0RHJiQ7) zn)YZ_Ok82iDnlfZ$f&F+I3vD3o3a3#Y6>=`0RQI`C-4X898v+_o8a3YHr-vo2M)vc zcKA-=+e3l^Z-n0sR2A%Clg*L~hkz31C+`PNXr$HOT{XCGZPq2kyQcl*j;x2}nQ z_jF(JAWk#)P8Djt<>~ ztDAiNV)wp1o}IoZ>|3-nX7y+Hv(g7_?LNCW+okyXvu}gBCpzS{F8r&o@yXmlR~;S~ z%?-X&8Gh-WQQ2mvA>E(ed-JvX?c(jbLpl!J&@Y@nbz8-}^EGSV^s2P);dgvjo0opy zdl#)dIrL!Mo93H;8!77WONX`B1<%Z9*&NzzQIvE#UC`Y3{{F5jifXDa4wdY=Hhb&r z2^~jP4LqQ*8}%~eH`{YnlZHgSoLjtSNTLmk}7GLg^Qtla%y!AwB`708>+%fFv zcW1w?zI5--)J~^v*j-rG-*TwWa#PEhqLY3zcGgbtS<_J3=dlO(HabM;#*X`ZPA9{|vTV$Qz zEQo7zEiQh`kofoO;_m*{uC&$Y#N;D=ZC*`|zNj}R ze6XO?s@`9X-T=h2Oyu3xZ*U;O)_enE-yB~Ol=IVtw;dATI) z)!Oc(yEqm^Ow8&1U|*XM$GvXH@0NFcF~8Dk!`ffGSIxR!z4EomwF7+?Z<-PK_G06L z^6M_UG9&l7nRykp%Uk<+?r@_oZjCSbQQvWP zPAPG>7LA|WdO~`iM=76vJ2&n{O&h_5(&9buo|f;F?JIb9|99E`w~wAI+kZdDdywOe zR(9>yPq?9Y*h%r`P`izj6i?>dnDke*T(xU~NeXTlph8&6u zx)Z+L#xt;J`N|mymJ_G+%!tX}oi=fyw8}Vte33Z$E2FAiMGs~j81FrBk{LfG@10j- z?=Bv;cMrNh=Xvy9n7v?xMY!GS)>piW4z+!fGLhptbHnqVUmuIIE%@Tt*jl5RuXn%m zIIy%_W-_H2DUDy)k>j?1Xu#BVF1LGrdE?{S1m$$csO%0njy5kMczub9oLj+boYrn_8g zvUx-EmGKj1yUwpkzL*%FGx)--LUZ4zSDii`HipK*#6d;fS5zQF3($0y6T+!u`b`tZdJZ?XxhC# zk|U2tc5a;5cJ82^SC&0Z^cpEHk4wDRgH!n~pkG|;a|<&Z7i2V>dbZEHHRip7JXa>X z>bw0n$L+uM`D6O}yzS&dzfBcUQuB#xUrSCK+mD)()^fpv$uDB>KRQ@`e956?a_UTb(M2o$b8p$kDgE%Rl|` zhZXIoFKyCeOi8cu=dQle$760*A2D$pJa@{Gi}9zW9lG>m} zncaR=XmHDx!Am+AaoY$ziZgG^yaVoS9^QRsOu&M#S}pzD^R#EY|LJ2*7c73XcIR1> zg*zvl9Cc=9-)B98laBL-cUZS5^2CO@4>xyue7(xucQEH<L(KCW{m89Vc`8uq+74( zd!-q9r%uM^&mUBIE+_5ertiL++QquDi_Jo}(q=v}RY;#tdUW%uuW z@3lNH_2%WbF49M__;kDkpxD)rhsZ{dZX zdv_gk!n5>1+^EWfqia0}^&8ziYD$NjO|N>`q}R&AY-<-s^);KFvh~HikR(?V>GyL| z{+#?+?&$Q>aQE|H_FQ;dII`P@nAWmEcl}MS-x>Oqu{8GFeb2sky8hIDMA`1CCziGQ zz96sT?y3Fb7ax3iz-ZeGrxDKl#hv?cv!2>7C-*JFjHK(vk0OfCY*Vg1E4W_?wYbw(Islms3lM2YhH}6O@hf| z-RY&}FU8-MK}idkeB$nf_6&`gQ&Wi6BvU!Zjx;;yZ#V7rl(Br7?A&gvxvj6wIJ5D* z(X_iAEIWp{52|@$S?a_0`$D*HiMV|6HV719-=W z@813M4RzBwTwgepWoXd_Xj+$^C0KNST>|V?h^Dqb=u>M=!mh}k)oUs?hvklTC$QDe zro^6NYbagRM~P0j*)-TjprMfu>s@VW>M@Dv{>HG|fSX0eBoSJl1N%ILEQ39{Wm+p= zC?K-{HcJbJc(BVsm|upl()ncwb1v*`zy)og|FYyCPRP7o`0Ez%v6)do~pLcerH}84 zdti4cb6hw>f%bsBvA=slVsfzC4Vc&ySjGdaaOiJU&In$LqxP{3->3G#m*~nIVxq>G zGNg&R#+(UY_JVI!j!Sye-4~|J2!5XiHMpqNMR!F(j-FA)K`0!rj@M#JwaFdui=pvR9Dr9emxxsP$C_CCH8EU_p>B#@;E`oU(kAO*ITVaq=! zC0m>fZvbH65#)$6g;KdVB?plZAWXqmB=9Jd3&x5i5<#*^Aj%h|m zmW>qv@f?u^HjDx6nIe;>im_gf0Nw>4nG~5MHxshq0Ro{kRS+I15M~26c>j`Il%A+x^khCVjjG|p-n;ZS=q1?pDjp%eP-a8BZhX#vAqo2 zE&@00Hvq7|&E%Ck{*V{RQ~U&iuoQW&P$C(})D`6mGqXSlAd{PeZyk_P6m0kpXami{ zB2+AWgQV7|5VVj5Ki-6G!ltK*vvcGE3A|HL=@T~o1#VjJ6x{r}f#HB4`Iw&n{T z9`9eWG|luENwpgY%ZjM~9BcdMr@sTirZm&v%+8uTT3cT;O`cAFJvDhc{cWttGt*y9 zo|*n?@-QLdxHkfY&_f9agTFC3Y{3w^sJH~v z=`84i@4#4zhHCpQOgsLz-$I>#!EbS;hklDek;7qTYN%*b??=2C>eY7{ z!+KIiPx)uUaXLI*`}cm2I2a_r37YDvkC&zcFm9 zc;k0ND&j;kvmuBL#QD4Y8%VanX#W;}^b4JHadZnobNr21fXQNy;qP#u=Az+{lUR}= z%mKI6l%VtWg)=hQu<(-Q2nNbBMZ#2>1_z4uUL5#UX;_HRJ`}KiJKPm&sJIDIWr9d? zO13OVmL?ZOA9?7n=b;ZtE9JUUc62sa~%C1*$agKS6v! A1ONa4 literal 0 HcmV?d00001 diff --git a/rule-engines/rulebook/pom.xml b/rule-engines/rulebook/pom.xml new file mode 100644 index 0000000000..711bee8c91 --- /dev/null +++ b/rule-engines/rulebook/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.baeldung.rulebook + rulebook + 1.0 + + rulebook + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.deliveredtechnologies + rulebook-core + 0.6.2 + + + \ No newline at end of file diff --git a/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java new file mode 100644 index 0000000000..c09772a3c6 --- /dev/null +++ b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java @@ -0,0 +1,17 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder; +import com.deliveredtechnologies.rulebook.model.RuleBook; + +public class HelloWorldRule { + public RuleBook defineHelloWorldRules() { + + return RuleBookBuilder.create() + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.print("Hello "))) + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.println("World"))) + .build(); + + } +} diff --git a/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java new file mode 100644 index 0000000000..57965457ec --- /dev/null +++ b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java @@ -0,0 +1,12 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.FactMap; + +public class Launcher { + + public static void main(String[] args) { + HelloWorldRule ruleBook = new HelloWorldRule(); + ruleBook.defineHelloWorldRules() + .run(new FactMap<>()); + } +} From a3cbc25dd805b0e0c94c33d995ecc71727c97855 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 19 Aug 2017 18:13:57 +0200 Subject: [PATCH 59/67] Undertow refactor (#2464) --- undertow/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/undertow/pom.xml b/undertow/pom.xml index a0f2dc53ee..33bac57178 100644 --- a/undertow/pom.xml +++ b/undertow/pom.xml @@ -14,11 +14,6 @@ - - io.undertow - undertow-core - 1.4.18.Final - io.undertow undertow-servlet From b65bccabd19fa596fe95ca530b0c489991768d06 Mon Sep 17 00:00:00 2001 From: dimitarsazdovski Date: Sun, 20 Aug 2017 04:04:56 +0200 Subject: [PATCH 60/67] Bael 817 (#2411) * Stashed changes * Changed method access restriction * Added test class * Changes to pom file * Changed formatting. Changed file path variable * Changed pom file. Changed unit test name * pom file --- libraries/pom.xml | 1093 +++++++++-------- .../java/com/baeldung/geotools/ShapeFile.java | 187 +++ .../geotools/GeoToolsUnitTestTest.java | 27 + 3 files changed, 779 insertions(+), 528 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/geotools/ShapeFile.java create mode 100644 libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index ddfd75da82..cf77d197a2 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -1,531 +1,568 @@ - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - - 4.0.0 - libraries - libraries - - - - org.apache.maven.plugins - maven-dependency-plugin - - - org.apache.felix - maven-bundle-plugin - 3.3.0 - maven-plugin - - - true - - - maven-failsafe-plugin - 2.20 - - - chromedriver - - - - - net.serenity-bdd.maven.plugins - serenity-maven-plugin - ${serenity.plugin.version} - - - serenity-reports - post-integration-test - - aggregate - - - - - - - org.datanucleus - datanucleus-maven-plugin - 5.0.2 - - JDO - ${basedir}/datanucleus.properties - ${basedir}/log4j.properties - true - false - - - - - process-classes - - enhance - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.0.2 - - - **/log4j.properties - - - - com.baeldung.neuroph.NeurophXOR - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18.1 - - - test - test - - test - - - - test/java/com/baeldung/neuroph/XORTest.java - - - - - - - - - - - - org.beykery - neuroph - ${neuroph.version} - - - - cglib - cglib - ${cglib.version} - - - commons-beanutils - commons-beanutils - ${commons-beanutils.version} - - - org.apache.commons - commons-lang3 - ${commons-lang.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - org.apache.commons - commons-collections4 - ${commons.collections.version} - - - org.jasypt - jasypt - ${jasypt.version} - - - org.javatuples - javatuples - ${javatuples.version} - - - org.javassist - javassist - ${javaassist.version} - - - - org.assertj - assertj-core - ${assertj.version} - - - org.skyscreamer - jsonassert - ${jsonassert.version} - - - org.javers - javers-core - ${javers.version} - - - org.eclipse.jetty - jetty-server - ${jetty.version} - - - org.eclipse.jetty - jetty-servlet - ${jetty.version} - - - rome - rome - ${rome.version} - - - io.specto - hoverfly-java - 0.8.0 - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - commons-logging - commons-logging - - - - - commons-io - commons-io - ${commons.io.version} - - - commons-chain - commons-chain - ${commons-chain.version} - - - org.apache.commons - commons-csv - ${commons-csv.version} - - - commons-dbutils - commons-dbutils - ${commons.dbutils.version} - - - org.apache.flink - flink-core - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-java - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-test-utils_2.10 - ${flink.version} - test - - - org.apache.commons - commons-math3 - 3.6.1 - - - net.serenity-bdd - serenity-core - ${serenity.version} - test - - - net.serenity-bdd - serenity-junit - ${serenity.version} - test - - - net.serenity-bdd - serenity-jbehave - ${serenity.jbehave.version} - test - - - net.serenity-bdd - serenity-rest-assured - ${serenity.version} - test - - - net.serenity-bdd - serenity-jira-requirements-provider - ${serenity.jira.version} - test - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - org.datanucleus - javax.jdo - 3.2.0-m6 - - - org.datanucleus - datanucleus-core - 5.1.0-m1 - - - org.datanucleus - datanucleus-api-jdo - 5.1.0-m1 - - - org.datanucleus - datanucleus-rdbms - 5.1.0-m1 - - - org.datanucleus - datanucleus-maven-plugin - 5.0.2 - - - org.datanucleus - datanucleus-xml - 5.0.0-release - - - net.openhft - chronicle - 3.6.4 - - - org.springframework - spring-web - 4.3.8.RELEASE - - - net.serenity-bdd - serenity-spring - ${serenity.version} - test - - - net.serenity-bdd - serenity-screenplay - ${serenity.version} - test - - - net.serenity-bdd - serenity-screenplay-webdriver - ${serenity.version} - test - - - io.rest-assured - spring-mock-mvc - 3.0.3 - test - - - org.multiverse - multiverse-core - ${multiverse.version} - - - com.zaxxer - HikariCP - 2.6.1 - compile - - - com.h2database - h2 - ${h2.version} - - - pl.pragmatists - JUnitParams - ${jUnitParams.version} - test - - - org.quartz-scheduler - quartz - 2.3.0 - - - one.util - streamex - ${streamex.version} - - - org.jooq - jool - 0.9.12 - - - org.openjdk.jmh - jmh-core - 1.19 - - - org.openjdk.jmh - jmh-generator-annprocess - 1.19 - - - io.netty - netty-all - ${netty.version} - - - junit - junit - ${junit.version} - test - - - info.debatty - java-lsh - ${java-lsh.version} - - - au.com.dius - pact-jvm-consumer-junit_2.11 - ${pact.version} - test - - - org.codehaus.groovy - groovy-all - 2.4.10 - - - org.awaitility - awaitility - ${awaitility.version} - test - - - org.awaitility - awaitility-proxy - ${awaitility.version} - test - - - org.hamcrest - java-hamcrest - ${org.hamcrest.java-hamcrest.version} - test - - - net.agkn - hll - ${hll.version} - - - net.bytebuddy - byte-buddy - ${bytebuddy.version} - - - net.bytebuddy - byte-buddy-agent - ${bytebuddy.version} - - - org.pcollections - pcollections - ${pcollections.version} - - - com.machinezoo.noexception - noexception - 1.1.0 - - - org.eclipse.collections - eclipse-collections - ${eclipse-collections.version} - - - io.vavr - vavr - ${vavr.version} - - - - 0.7.0 - 3.2.4 - 3.5 - 1.1 - 1.9.3 - 1.2 - 1.4 - 1.9.2 - 1.2 - 3.21.0-GA - 3.6.2 - 1.5.0 - 3.1.0 - 9.4.3.v20170317 - 4.5.3 - 2.5 - 1.6 - 1.4.196 - 9.4.2.v20170220 - 4.5.3 - 2.5 - 1.2.0 - 2.8.5 - 2.92 - 1.4.0 - 1.24.0 - 1.1.3-rc.5 - 1.4.0 - 1.1.0 - 4.1.10.Final - 4.1 - 4.12 - 0.10 - 3.5.0 - 3.0.0 - 2.0.0.0 - 1.6.0 - 1.7.1 - 2.1.2 - 1.0 - 8.2.0 - 0.6.5 - 0.9.0 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + libraries + libraries + + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.apache.felix + maven-bundle-plugin + 3.3.0 + maven-plugin + + + true + + + maven-failsafe-plugin + 2.20 + + + chromedriver + + + + + net.serenity-bdd.maven.plugins + serenity-maven-plugin + ${serenity.plugin.version} + + + serenity-reports + post-integration-test + + aggregate + + + + + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + JDO + ${basedir}/datanucleus.properties + ${basedir}/log4j.properties + true + false + + + + + process-classes + + enhance + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + **/log4j.properties + + + + com.baeldung.neuroph.NeurophXOR + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18.1 + + + test + test + + test + + + + test/java/com/baeldung/neuroph/XORTest.java + + + + + + + + + + + + org.beykery + neuroph + ${neuroph.version} + + + + cglib + cglib + ${cglib.version} + + + commons-beanutils + commons-beanutils + ${commons-beanutils.version} + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + org.apache.commons + commons-collections4 + ${commons.collections.version} + + + org.jasypt + jasypt + ${jasypt.version} + + + org.javatuples + javatuples + ${javatuples.version} + + + org.javassist + javassist + ${javaassist.version} + + + + org.assertj + assertj-core + ${assertj.version} + + + org.skyscreamer + jsonassert + ${jsonassert.version} + + + org.javers + javers-core + ${javers.version} + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + rome + rome + ${rome.version} + + + io.specto + hoverfly-java + 0.8.0 + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-logging + commons-logging + + + + + commons-io + commons-io + ${commons.io.version} + + + commons-chain + commons-chain + ${commons-chain.version} + + + org.apache.commons + commons-csv + ${commons-csv.version} + + + commons-dbutils + commons-dbutils + ${commons.dbutils.version} + + + org.apache.flink + flink-core + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-java + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-test-utils_2.10 + ${flink.version} + test + + + org.apache.commons + commons-math3 + 3.6.1 + + + net.serenity-bdd + serenity-core + ${serenity.version} + test + + + net.serenity-bdd + serenity-junit + ${serenity.version} + test + + + net.serenity-bdd + serenity-jbehave + ${serenity.jbehave.version} + test + + + net.serenity-bdd + serenity-rest-assured + ${serenity.version} + test + + + net.serenity-bdd + serenity-jira-requirements-provider + ${serenity.jira.version} + test + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + org.datanucleus + javax.jdo + 3.2.0-m6 + + + org.datanucleus + datanucleus-core + 5.1.0-m1 + + + org.datanucleus + datanucleus-api-jdo + 5.1.0-m1 + + + org.datanucleus + datanucleus-rdbms + 5.1.0-m1 + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + + org.datanucleus + datanucleus-xml + 5.0.0-release + + + net.openhft + chronicle + 3.6.4 + + + org.springframework + spring-web + 4.3.8.RELEASE + + + net.serenity-bdd + serenity-spring + ${serenity.version} + test + + + net.serenity-bdd + serenity-screenplay + ${serenity.version} + test + + + net.serenity-bdd + serenity-screenplay-webdriver + ${serenity.version} + test + + + io.rest-assured + spring-mock-mvc + 3.0.3 + test + + + org.multiverse + multiverse-core + ${multiverse.version} + + + com.zaxxer + HikariCP + 2.6.1 + compile + + + com.h2database + h2 + ${h2.version} + + + pl.pragmatists + JUnitParams + ${jUnitParams.version} + test + + + org.quartz-scheduler + quartz + 2.3.0 + + + one.util + streamex + ${streamex.version} + + + org.jooq + jool + 0.9.12 + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + io.netty + netty-all + ${netty.version} + + + junit + junit + ${junit.version} + test + + + info.debatty + java-lsh + ${java-lsh.version} + + + au.com.dius + pact-jvm-consumer-junit_2.11 + ${pact.version} + test + + + org.codehaus.groovy + groovy-all + 2.4.10 + + + org.awaitility + awaitility + ${awaitility.version} + test + + + org.awaitility + awaitility-proxy + ${awaitility.version} + test + + + org.hamcrest + java-hamcrest + ${org.hamcrest.java-hamcrest.version} + test + + + net.agkn + hll + ${hll.version} + + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + net.bytebuddy + byte-buddy-agent + ${bytebuddy.version} + + + org.pcollections + pcollections + ${pcollections.version} + + + com.machinezoo.noexception + noexception + 1.1.0 + + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + + + io.vavr + vavr + ${vavr.version} + + + org.geotools + gt-shapefile + ${geotools.version} + + + org.geotools + gt-epsg-hsql + ${geotools.version} + + + org.geotools + gt-swing + ${geotools.version} + + + + + maven2-repository.dev.java.net + Java.net repository + http://download.java.net/maven/2 + + + osgeo + Open Source Geospatial Foundation Repository + http://download.osgeo.org/webdav/geotools/ + + + + true + + opengeo + OpenGeo Maven Repository + http://repo.opengeo.org + + + + 0.7.0 + 3.2.4 + 3.5 + 1.1 + 1.9.3 + 1.2 + 1.4 + 1.9.2 + 1.2 + 3.21.0-GA + 3.6.2 + 1.5.0 + 3.1.0 + 9.4.3.v20170317 + 4.5.3 + 2.5 + 1.6 + 1.4.196 + 9.4.2.v20170220 + 4.5.3 + 2.5 + 1.2.0 + 2.8.5 + 2.92 + 1.4.0 + 1.24.0 + 1.1.3-rc.5 + 1.4.0 + 1.1.0 + 4.1.10.Final + 4.1 + 4.12 + 0.10 + 3.5.0 + 3.0.0 + 2.0.0.0 + 1.6.0 + 1.7.1 + 2.1.2 + 1.0 + 8.2.0 + 0.6.5 + 0.9.0 + 15.2 + + diff --git a/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java b/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java new file mode 100644 index 0000000000..77c67abc84 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java @@ -0,0 +1,187 @@ +package com.baeldung.geotools; + +import java.io.File; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.geotools.data.DataUtilities; +import org.geotools.data.DefaultTransaction; +import org.geotools.data.Transaction; +import org.geotools.data.shapefile.ShapefileDataStore; +import org.geotools.data.shapefile.ShapefileDataStoreFactory; +import org.geotools.data.simple.SimpleFeatureSource; +import org.geotools.data.simple.SimpleFeatureStore; +import org.geotools.feature.DefaultFeatureCollection; +import org.geotools.feature.simple.SimpleFeatureBuilder; +import org.geotools.feature.simple.SimpleFeatureTypeBuilder; +import org.geotools.geometry.jts.JTSFactoryFinder; +import org.geotools.referencing.crs.DefaultGeographicCRS; +import org.geotools.swing.data.JFileDataStoreChooser; +import org.opengis.feature.simple.SimpleFeature; +import org.opengis.feature.simple.SimpleFeatureType; + +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.GeometryFactory; +import com.vividsolutions.jts.geom.Point; + +public class ShapeFile { + + private static final String FILE_NAME = "shapefile.shp"; + + public static void main(String[] args) throws Exception { + + DefaultFeatureCollection collection = new DefaultFeatureCollection(); + + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); + + SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String"); + + SimpleFeatureType CITY = createFeatureType(); + + SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); + + addLocations(featureBuilder, collection); + + File shapeFile = getNewShapeFile(); + + ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); + + Map params = new HashMap(); + params.put("url", shapeFile.toURI() + .toURL()); + params.put("create spatial index", Boolean.TRUE); + + ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); + dataStore.createSchema(CITY); + + // If you decide to use the TYPE type and create a Data Store with it, + // You will need to uncomment this line to set the Coordinate Reference System + // newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); + + Transaction transaction = new DefaultTransaction("create"); + + String typeName = dataStore.getTypeNames()[0]; + SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName); + + if (featureSource instanceof SimpleFeatureStore) { + SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; + + featureStore.setTransaction(transaction); + try { + featureStore.addFeatures(collection); + transaction.commit(); + + } catch (Exception problem) { + problem.printStackTrace(); + transaction.rollback(); + + } finally { + transaction.close(); + } + System.exit(0); // success! + } else { + System.out.println(typeName + " does not support read/write access"); + System.exit(1); + } + + } + + public static SimpleFeatureType createFeatureType() { + + SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); + builder.setName("Location"); + builder.setCRS(DefaultGeographicCRS.WGS84); + + builder.add("Location", Point.class); + builder.length(15) + .add("Name", String.class); + + SimpleFeatureType CITY = builder.buildFeatureType(); + + return CITY; + } + + public static void addLocations(SimpleFeatureBuilder featureBuilder, DefaultFeatureCollection collection) { + + Map> locations = new HashMap<>(); + + double lat = 13.752222; + double lng = 100.493889; + String name = "Bangkok"; + addToLocationMap(name, lat, lng, locations); + + lat = 53.083333; + lng = -0.15; + name = "New York"; + addToLocationMap(name, lat, lng, locations); + + lat = -33.925278; + lng = 18.423889; + name = "Cape Town"; + addToLocationMap(name, lat, lng, locations); + + lat = -33.859972; + lng = 151.211111; + name = "Sydney"; + addToLocationMap(name, lat, lng, locations); + + lat = 45.420833; + lng = -75.69; + name = "Ottawa"; + addToLocationMap(name, lat, lng, locations); + + lat = 30.07708; + lng = 31.285909; + name = "Cairo"; + addToLocationMap(name, lat, lng, locations); + + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); + + for (Map.Entry> location : locations.entrySet()) { + Point point = geometryFactory.createPoint(new Coordinate(location.getValue() + .get(0), + location.getValue() + .get(1))); + featureBuilder.add(point); + featureBuilder.add(name); + SimpleFeature feature = featureBuilder.buildFeature(null); + collection.add(feature); + } + + } + + private static void addToLocationMap(String name, double lat, double lng, Map> locations) { + List coordinates = new ArrayList<>(); + + coordinates.add(lat); + coordinates.add(lng); + locations.put(name, coordinates); + } + + private static File getNewShapeFile() { + String filePath = new File(".").getAbsolutePath() + FILE_NAME; + + + JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp"); + chooser.setDialogTitle("Save shapefile"); + chooser.setSelectedFile(new File(filePath)); + + int returnVal = chooser.showSaveDialog(null); + + if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) { + System.exit(0); + } + + File shapeFile = chooser.getSelectedFile(); + if (shapeFile.equals(filePath)) { + System.out.println("Error: cannot replace " + filePath); + System.exit(0); + } + + return shapeFile; + } + +} diff --git a/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java b/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java new file mode 100644 index 0000000000..44cd47edc3 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java @@ -0,0 +1,27 @@ +package com.baeldung.geotools; + +import static org.junit.Assert.assertNotNull; + +import org.geotools.feature.DefaultFeatureCollection; +import org.geotools.feature.simple.SimpleFeatureBuilder; +import org.junit.Test; +import org.opengis.feature.simple.SimpleFeatureType; + +public class GeoToolsUnitTestTest { + + @Test + public void givenFeatureType_whenAddLocations_returnFeatureCollection() { + + DefaultFeatureCollection collection = new DefaultFeatureCollection(); + + SimpleFeatureType CITY = ShapeFile.createFeatureType(); + + SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); + + ShapeFile.addLocations(featureBuilder, collection); + + assertNotNull(collection); + + } + +} From a0198e143ebf0f1783c24f3e3482e180895c0a88 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sun, 20 Aug 2017 08:17:05 +0200 Subject: [PATCH 61/67] upgrade jackson (#2465) * fix spring config * fix spring config * fix spring config * minor fix * fix spring-boot module * fix pom * upgrade jackson --- jackson/pom.xml | 2 +- .../java/com/baeldung/jackson/sandbox/SandboxUnitTest.java | 2 +- .../jackson/test/JacksonSerializationIgnoreUnitTest.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/jackson/pom.xml b/jackson/pom.xml index 1a538670c6..f970b6a68c 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -129,7 +129,7 @@ - 2.8.7 + 2.9.0 19.0 diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java index a600577cb0..33aca2a1ed 100644 --- a/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java @@ -17,7 +17,7 @@ public class SandboxUnitTest { testElement.setX(10); testElement.setY("adasd"); final ObjectMapper om = new ObjectMapper(); - om.setVisibilityChecker(om.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE)); + om.setVisibility(om.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE)); final String serialized = om.writeValueAsString(testElement); System.err.println(serialized); diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java index 71499b8a24..bc0e24cdfa 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -24,7 +24,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; import com.fasterxml.jackson.databind.ser.FilterProvider; @@ -194,7 +193,8 @@ public class JacksonSerializationIgnoreUnitTest { @Test public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); + // mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); + mapper.setSerializationInclusion(Include.NON_NULL); final MyDto dtoObject1 = new MyDto(); From a02e758d7078168e2a18eee4af1a18d7622d2959 Mon Sep 17 00:00:00 2001 From: lor6 Date: Sun, 20 Aug 2017 11:20:45 +0300 Subject: [PATCH 62/67] thread pools examples (#2400) * thread pools examples * add logs --- guest/thread-pools/pom.xml | 28 +++++ .../java/com/stackify/models/Employee.java | 28 +++++ .../stackify/services/EmployeeService.java | 9 ++ .../stackify/threadpools/FactorialTask.java | 64 +++++++++++ .../threadpools/ThreadsApplication.java | 102 ++++++++++++++++++ 5 files changed, 231 insertions(+) create mode 100644 guest/thread-pools/pom.xml create mode 100644 guest/thread-pools/src/main/java/com/stackify/models/Employee.java create mode 100644 guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java create mode 100644 guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java create mode 100644 guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java diff --git a/guest/thread-pools/pom.xml b/guest/thread-pools/pom.xml new file mode 100644 index 0000000000..72a10213c4 --- /dev/null +++ b/guest/thread-pools/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.stackify + thread-pools + 0.0.1-SNAPSHOT + + + + ch.qos.logback + logback-classic + 1.2.3 + + + + + + + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/guest/thread-pools/src/main/java/com/stackify/models/Employee.java b/guest/thread-pools/src/main/java/com/stackify/models/Employee.java new file mode 100644 index 0000000000..65661f38d5 --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/models/Employee.java @@ -0,0 +1,28 @@ +package com.stackify.models; + +public class Employee { + private String name; + private double salary; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + public Employee(String name, double salary) { + super(); + this.name = name; + this.salary = salary; + } +} diff --git a/guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java b/guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java new file mode 100644 index 0000000000..824f87a625 --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java @@ -0,0 +1,9 @@ +package com.stackify.services; + +import com.stackify.models.Employee; + +public class EmployeeService { + public double calculateBonus(Employee employee) { + return 0.1 * employee.getSalary(); + } +} diff --git a/guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java b/guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java new file mode 100644 index 0000000000..2dd83d9b20 --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java @@ -0,0 +1,64 @@ +package com.stackify.threadpools; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RecursiveTask; +import java.util.stream.IntStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class FactorialTask extends RecursiveTask { + + private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + private static final long serialVersionUID = 1L; + + private int start = 1; + private int n; + + private static final int THRESHOLD = 20; + + public FactorialTask(int n) { + this.n = n; + } + + public FactorialTask(int start, int n) { + logger.info("New FactorialTask Created"); + this.start = start; + this.n = n; + } + + @Override + protected BigInteger compute() { + if ((n - start) >= THRESHOLD) { + return ForkJoinTask.invokeAll(createSubtasks()) + .stream() + .map(ForkJoinTask::join) + .reduce(BigInteger.ONE, BigInteger::multiply); + } else { + return calculate(start, n); + } + } + + private Collection createSubtasks() { + List dividedTasks = new ArrayList<>(); + + int mid = (start + n) / 2; + + dividedTasks.add(new FactorialTask(start, mid)); + dividedTasks.add(new FactorialTask(mid + 1, n)); + return dividedTasks; + } + + private BigInteger calculate(int start, int n) { + logger.info("Calculate factorial from " + start + " to " + n); + return IntStream.rangeClosed(start, n) + .mapToObj(BigInteger::valueOf) + .reduce(BigInteger.ONE, BigInteger::multiply); + } + +} diff --git a/guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java b/guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java new file mode 100644 index 0000000000..cc9048eee7 --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java @@ -0,0 +1,102 @@ +package com.stackify.threadpools; + +import java.math.BigInteger; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.stackify.models.Employee; +import com.stackify.services.EmployeeService; + +public class ThreadsApplication { + + private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + public static void main(String[] args) { + testExecutor(); + testExecutorService(); + testScheduledExecutorService(); + testThreadPoolExecutor(); + testForkJoinPool(); + } + + private static EmployeeService employeeService = new EmployeeService(); + + public static void testExecutor() { + Executor executor = Executors.newSingleThreadExecutor(); + executor.execute(() -> System.out.println("Single thread pool test")); + } + + public static void testExecutorService() { + + Employee employee = new Employee("John", 2000); + + ExecutorService executor = Executors.newFixedThreadPool(10); + + Callable callableTask = () -> { + return employeeService.calculateBonus(employee); + }; + Future future = executor.submit(callableTask); + + try { + if (future.isDone()) { + double result = future.get(); + System.out.println("Bonus is:" + result); + } + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + + executor.shutdown(); + } + + public static void testScheduledExecutorService() { + Employee employee = new Employee("John", 2000); + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); + + Callable callableTask = () -> { + return employeeService.calculateBonus(employee); + }; + + Future futureScheduled = executor.schedule(callableTask, 2, TimeUnit.MILLISECONDS); + + try { + System.out.println("Bonus:" + futureScheduled.get()); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + + executor.scheduleAtFixedRate(() -> System.out.println("Fixed Rate Scheduled"), 2, 2000, TimeUnit.MILLISECONDS); + executor.scheduleWithFixedDelay(() -> System.out.println("Fixed Delay Scheduled"), 2, 2000, TimeUnit.MILLISECONDS); + } + + public static void testThreadPoolExecutor() { + ThreadPoolExecutor fixedPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10); + ThreadPoolExecutor cachedPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); + + ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 60, TimeUnit.SECONDS, new LinkedBlockingQueue()); + executor.setMaximumPoolSize(8); + + ScheduledThreadPoolExecutor scheduledExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5); + } + + public static void testForkJoinPool() { + ForkJoinPool pool = ForkJoinPool.commonPool(); + logger.info("Thread Pool Created"); + BigInteger result = pool.invoke(new FactorialTask(100)); + System.out.println(result.toString()); + } +} From b7ad275bdd3b9386798dc99d5234cd03eac45124 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sun, 20 Aug 2017 13:26:34 +0200 Subject: [PATCH 63/67] minor fix (#2468) * fix spring config * fix spring config * fix spring config * minor fix * fix spring-boot module * fix pom * upgrade jackson * minor fix --- .../src/main/java/org/baeldung/config/UiApplication.java | 3 +-- .../src/main/java/org/baeldung/config/UiSecurityConfig.java | 2 ++ 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java index 6e29879cb3..e186046e83 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -2,12 +2,11 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.web.context.request.RequestContextListener; -@EnableOAuth2Sso + @SpringBootApplication public class UiApplication extends SpringBootServletInitializer { diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java index 5dbe9ada34..f9119e20f5 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -1,9 +1,11 @@ package org.baeldung.config; +import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +@EnableOAuth2Sso @Configuration public class UiSecurityConfig extends WebSecurityConfigurerAdapter { From e6c2fd3bbec4e94e0482ea50ef61013354122143 Mon Sep 17 00:00:00 2001 From: adamd1985 Date: Sun, 20 Aug 2017 15:44:20 +0200 Subject: [PATCH 64/67] Revert "BAEL-812: List of Rules Engines in Java (#2319)" (#2455) This reverts commit dc105bc6f22b2b4ab9d504fdbf0dd9988ba26ec1. --- easy-rules/pom.xml | 15 ---- .../baeldung/easyrules/HelloWorldRule.java | 20 ----- .../java/com/baeldung/easyrules/Launcher.java | 21 ------ openl-tablets/pom.xml | 23 ------ .../com/baeldung/openltablets/model/Case.java | 23 ------ .../baeldung/openltablets/model/Greeting.java | 20 ----- .../com/baeldung/openltablets/model/User.java | 14 ---- .../baeldung/openltablets/rules/IRule.java | 7 -- .../com/baeldung/openltablets/rules/Main.java | 31 -------- .../baeldung/openltablets/rules/Response.java | 24 ------ .../main/resources/openltablets/HelloUser.xls | Bin 25088 -> 0 bytes rulebook/pom.xml | 15 ---- .../com/baeldung/rulebook/HelloWorldRule.java | 17 ----- .../java/com/baeldung/rulebook/Launcher.java | 12 --- .../autowired/TypesOfBeanInjectionSpring.java | 70 ------------------ ...sOfBeanInjectionSpringIntegrationTest.java | 25 ------- 16 files changed, 337 deletions(-) delete mode 100644 easy-rules/pom.xml delete mode 100644 easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java delete mode 100644 easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java delete mode 100644 openl-tablets/pom.xml delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java delete mode 100644 openl-tablets/src/main/resources/openltablets/HelloUser.xls delete mode 100644 rulebook/pom.xml delete mode 100644 rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java delete mode 100644 rulebook/src/main/java/com/baeldung/rulebook/Launcher.java delete mode 100644 spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java delete mode 100644 spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java diff --git a/easy-rules/pom.xml b/easy-rules/pom.xml deleted file mode 100644 index b74b16f34c..0000000000 --- a/easy-rules/pom.xml +++ /dev/null @@ -1,15 +0,0 @@ - - 4.0.0 - com.baeldung.easyrules - easy-rules - 1.0.0-SNAPSHOT - - - - org.jeasy - easy-rules-core - 3.0.0 - - - \ No newline at end of file diff --git a/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java b/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java deleted file mode 100644 index 5448eabf2a..0000000000 --- a/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.easyrules; - -import org.jeasy.rules.annotation.Action; -import org.jeasy.rules.annotation.Condition; -import org.jeasy.rules.annotation.Rule; - -@Rule(name = "Hello World rule", description = "Always say hello world") -public class HelloWorldRule { - - @Condition - public boolean when() { - return true; - } - - @Action - public void then() throws Exception { - System.out.println("hello world"); - } - -} diff --git a/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java b/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java deleted file mode 100644 index 427e3eace0..0000000000 --- a/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.easyrules; - -import org.jeasy.rules.api.Facts; -import org.jeasy.rules.api.Rules; -import org.jeasy.rules.api.RulesEngine; -import org.jeasy.rules.core.DefaultRulesEngine; - -public class Launcher { - public static void main(String... args) { - // create facts - Facts facts = new Facts(); - - // create rules - Rules rules = new Rules(); - rules.register(new HelloWorldRule()); - - // create a rules engine and fire rules on known facts - RulesEngine rulesEngine = new DefaultRulesEngine(); - rulesEngine.fire(rules, facts); - } -} diff --git a/openl-tablets/pom.xml b/openl-tablets/pom.xml deleted file mode 100644 index 77b9f47b38..0000000000 --- a/openl-tablets/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - 4.0.0 - com.baeldung.openltablets - openl-tablets - 0.0.1-SNAPSHOT - - UTF-8 - UTF-8 - 1.8 - - - - org.openl - org.openl.core - 5.19.4 - - - org.openl.rules - org.openl.rules - 5.19.4 - - - \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java deleted file mode 100644 index f9f5f4bd5f..0000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.openltablets.model; - -public class Case { - - private User user; - private int hourOfDay; - - public User getUser() { - return user; - } - - public void setUser(final User user) { - this.user = user; - } - - public int getHourOfDay() { - return hourOfDay; - } - - public void setHourOfDay(final int hourOfDay) { - this.hourOfDay = hourOfDay; - } -} diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java deleted file mode 100644 index 5dc7bcd117..0000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.openltablets.model; - -public enum Greeting { - - GOOD_MORNING("Good Morning"), - GOOD_AFTERNOON("Good Afternoon"), - GOOD_EVENING("Good Evening"), - GOOD_NIGHT("Good Night"); - - private final String literal; - - private Greeting(final String literal) { - this.literal = literal; - } - - public String getLiteral() { - return literal; - } - -} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java deleted file mode 100644 index 8e45487497..0000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.openltablets.model; - -public class User { - - private String name; - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java deleted file mode 100644 index 857a6433ef..0000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.openltablets.rules; - -import com.baeldung.openltablets.model.Case; - -public interface IRule { - void helloUser(final Case aCase, final Response response); -} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java deleted file mode 100644 index 34f5c48ed1..0000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.openltablets.rules; - - -import java.time.LocalDateTime; - -import org.openl.rules.runtime.RulesEngineFactory; -import org.openl.runtime.EngineFactory; - -import com.baeldung.openltablets.model.Case; -import com.baeldung.openltablets.model.User; - -public class Main { - private IRule instance; - - public static void main(String[] args) { - Main rules = new Main(); - User user = new User(); - user.setName("Donald Duck"); - Case aCase = new Case(); - aCase.setUser(user); - aCase.setHourOfDay(23); - rules.process(aCase); - } - - public void process(Case aCase) { - final EngineFactory engineFactory = new RulesEngineFactory(getClass().getClassLoader() - .getResource("openltablets/HelloUser.xls"), IRule.class); - instance = engineFactory.newEngineInstance(); - instance.helloUser(aCase, new Response()); - } -} diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java deleted file mode 100644 index 27fa634866..0000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.openltablets.rules; - -import java.util.HashMap; -import java.util.Map; - -public class Response { - private String result; - private Map map = new HashMap<>(); - - public Response() { } - - public String getResult() { - return result; - } - - public void setResult(final String s) { - result = s; - } - - public Map getMap() { - return map; - } - -} diff --git a/openl-tablets/src/main/resources/openltablets/HelloUser.xls b/openl-tablets/src/main/resources/openltablets/HelloUser.xls deleted file mode 100644 index 1e85d0ce2de54ddc812ec9639211a313a5024b45..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 25088 zcmeHv2Ut{B)9~44ft8{(5m8`4P>>?Uf-QiE9YLBEae)O^mt6u2q7lWGh%t&imY66p z8Vh!eVnK}s#S&{2dyR^QSYwI%&78aSvWw(>^Zn2Ne$RWCbN8M(b7tnunVD1WVb7el zzPWOX<1NCvJ|RZrgQ5{J(Smc}856y%2;ss5=07MD3I<3BJpT9k57NM2AgiCU58J`F zF(mABQ%HPBjUbspGKXXV$r4gyNKGJt2@q>YHjr!~*+FUw$sSTONDh#iLvn=F0#Zvz zPLP}-xj+&?a)smusTCx5NFI<{Luv!b6OtFCwvfCb`9Si8g!ZON|3Rw$|5DT#B7=_{ z`XYiz;X9j*0}VI)vImP%H4I~cfR9mukP3Pyz3|Je*6Eu(t8<*5Y)V zz&)FcA<0yZFPdzR(M4R3`|L6EQqX8C1P@PbGhBQ$zVa@^#ME%e4tJ>w6UAhzkT*5D#L31Tt4w`v+c4!z~UgGtztRG zcN}97j^j!wBpgQuKthUl0TIUv#OWoHh_k>=L*cpb&-=&KaRl=J&Q+iM+zTf!Eca_+ zHGeV4@AIY<F)Tz?^{T z0>S^As|S@qNMm~iD7!m{4?5>Uoad3{@NEq<3)CURf4JMy`zDILhu*u>SqUNULq50! z0|xfk5N;^N`-_zV7_t;@D-Dav6H!EoG~X1VzU_Hv4pTn$v=4c03a2V~Y?+LC++tqf7uHQ~fTYcgPL!BHjvW@g_3(GWFfc6t38aVA%x zHeXe{#*`CIbtQ&T9rYFfUW^#lAHm>|_9_Vt(9mkX0Sp2(l=?G>q1LcLj88sF!|tOP z-9CcBAzeSxT8ymqw}lJw$1p})k^vUnRgGcE>K6e-S}{onJCM^p^5J|;Cf-Leu7aI? ztX&+i6{Vf(=>Y+?MYZ?U@Hw$CKT8K&6%hf6Cw+-C&kzs^L${118bcmUk%;}t!ISm;D^F0s4I&X2*GB@fV4P< zglKrSht(9U_0&97^_3#1>Qc^{dN-AG)|U!Uiu$S$ARGfFg}+c0)DOoHrVrl`9I5KV z|Gy09pz*0MMxQv#pnBM@EZ}`h^ELb) zg`cOBO9*a^J>YCmm;OGAUl+c^0Gy#;7k`@pd`6#j@tOAGZjf%f7(L?-k*=H@DSZw^ zGYYQ-1bV6BMq9mboK@@6Vfr0+s3?57wY9yuJ?N9MXPhtSqmQd^3J3i&dS>*`foQA` zA9uAVoE6`2cCQbPs{(y+2NnE0T{OTZ7}H+dC8PKZ9LO?o+&NRi1+eac>MS@*9^7S9 z;tL7+L`|Oq5ud_YdIofe-9S1EpYUSno5B-?=To2>jyVdCHUJOR2ZvVVtMt6gPBo5j zaE#99Sa&68=WMtNe?t=uK4?izhk-M4)}^n3>(bZ2_0b19{z|w~57-(ir@xX88y;*3 zA2&v!U2J@RefoiJwK4!_^@}l;2k`T;Mj_~Jh70NkR%ak5g)0eZ_hVf+B2oNkCAyBB zu;;7Rvv$7-U`eae8w1zai3+aWUx4pvO|_t_2MV_;cLMo!_=5g}b>(5&>#Eb<34A*; z0hhw+YdA484W3iL4HyS2_!LI>CuulvV!N}JDBB)2hL@*pSfC#=jFiZqv=SPWD4XD3& zFwi!DNd3J7{?QO3_4f{j@CHayfA4??G=xa~y@P{510<=xcko@!M~MUm)!#e#vZnz= z>hB%g0c-$~`g;dP!iEs3zjp);BT|3wKrm~FB=z@>o0W%>(fXMVx(;Fbq9men2ntii3YGV1!&KgsIX3S4ZzR)C@Es7s`CLx?Cslu^n6kuD7( zqMke`iLf;cyPQf5>uW!^fFIB5l5S9eXL!1gHo>n zGkC8K&$t8uOYy+f2ePqdvk9!r#;qPUff_c(qO|vSFY0Gw!)6mymrd(>*q{R{TVo<^jKP}de~@N zTGfC*Pi)lB#(~X7kEOM#hmE$SRSl@FuGY_{Ih&0hOY^RWjkcv#4N%-)qMwZ;n~fez zYgZ2&ZA+^fu=mna{cKvW+32yfpnBM7TUynCBR99}XVVhdbgbXf1i+?a11v2tX!ef= z`o@XPMvtYr*TY8J(gK5CY@VjSHO_1{dMwSe9yZ#R78q1nS*f3m3!9A|OY^CRjkcu) z1}QG5>1QKgv(aN|{`IiYwzR;YWe4x;XXDCdqsP+P*TY8J(gK5iJTqG#8$NM^z(;z> zGUxF->yDWmM}-mTK~Ej1f}=4^op70o<0C%fT2?teTEL-DSU!Z`lBDEHWb^prbcu28 z6{aK{4y#B=3LK%609l+T;-HI!a5|_Wifda+)CA71Vj)hyIDo93Ez~f9pQ9p zQxN8%Bv&F7q>2OyqHJ-RI7Rs24v4mpC0a8@QxNST2!(aRSIFRjO79@(byJR!5~OCF0`Ogv{q!!0}z^HTAS9OqUVQ33|=YR0)nY zW&d2a`AD>lhA0FSHc?j=QSBf?$diHq{X{)AL?L{ziF&YzYKIJF2ck|#p`>0Kq7W?D zM7>xffXa8IPfq+dkfJIc>`Qe4p#@_mg z`XJE=sXUvS8QW*=fT-%AvC614K8vesm4V?BT*vtTzRxy>c{!~5`$|(}+1VmF_-TZ$ zF>+eKe>mWY+Z6D^Z1{-aBn*ZTX5xmCLIG=Ql}NY%SH>nD@hjvh=J5r(1dVxs90?>u zN{1of5j@ha&=hbzS-7UaT!Skh!(re}1m;-B9G+qSWuPb*6giI{qFa^I5?pN{Fv$gZ zvz4By3VgT*S4#}5eYM1-kbo3!EK-D$!sg>qFo}|XBUr+~8gHOX4&0M{Jj7@uhz;LN!YzWYZ&*W6%GdY#` zOb*3wUuXj2_t6!=*hJAB1Q5X+Ry^R1Hjlbi4G5VKWF>F_3(G{Xbkwy1ThalBArdFb zm&3Ck1bfE9=9vf!F48pF9-5xf*c>s65sBY8kP2OzkPR#^m^w9+E%VX6mjw;1XX z`B@Se&E(=dV9=Mvpo79%hd~6e$^yBWK@1P6=dswJvntt`lTK*LaZluQ6c5s+ZPWxz zCJwqst{%e~VNGEU(KBu|rNWudwS-rLu>5AI2w*wRa%Cec1z(4bK)DFVhHKN};(%oe zw#^JRNV&5XWf)x8l&$MfW`-97locVXe!2x#hm^Z$QHBwQP1&XnWoC>qK$)3!b1CJn zT9jd!>BQ2iZ5_%u(A3o|Y(tolZsHS4{>1MBqzu z_!kv?iiDI3wuk>d5eOlIu|l~PhW7Esj$|IWt$e=>^C|+40ItB?@ZUx#1Re?zq`Vcv zcOhorp`xM!z6!~bB?_`6C=DiORip~=)8L~3I7x$i6%vFniywTX^e6>NgE9mhtXBo~ z6^bQf3FH+^pf1pb@s9+hDM(ON6~F--(-KH&Kt62=S+r;o0R$4X1OQ+vJ$v>9SqPOU zC};_Bb8{mjtQzC=n=+@(Bctfy=IL-$)UgM`o3Ia%PX`y-)DMez1kaIA2bAWKm^UTL z6YIPR}G2r4sDuI*bC0b<&p9LkI;8V)s!4rqq3`__2 zZjF>8_7TL0a-Fk3PrAps}$cxj@wl$o7`WQU#H+ zY$;TR;g)8@(&VCSsZ1tSl}F@>u-r^pK2V&VAqV-joB{elB9x}*3e!cAmn)5}NGcTgdAT#j6n=_kvT z`(=Sn0RHJiQ7) zn)YZ_Ok82iDnlfZ$f&F+I3vD3o3a3#Y6>=`0RQI`C-4X898v+_o8a3YHr-vo2M)vc zcKA-=+e3l^Z-n0sR2A%Clg*L~hkz31C+`PNXr$HOT{XCGZPq2kyQcl*j;x2}nQ z_jF(JAWk#)P8Djt<>~ ztDAiNV)wp1o}IoZ>|3-nX7y+Hv(g7_?LNCW+okyXvu}gBCpzS{F8r&o@yXmlR~;S~ z%?-X&8Gh-WQQ2mvA>E(ed-JvX?c(jbLpl!J&@Y@nbz8-}^EGSV^s2P);dgvjo0opy zdl#)dIrL!Mo93H;8!77WONX`B1<%Z9*&NzzQIvE#UC`Y3{{F5jifXDa4wdY=Hhb&r z2^~jP4LqQ*8}%~eH`{YnlZHgSoLjtSNTLmk}7GLg^Qtla%y!AwB`708>+%fFv zcW1w?zI5--)J~^v*j-rG-*TwWa#PEhqLY3zcGgbtS<_J3=dlO(HabM;#*X`ZPA9{|vTV$Qz zEQo7zEiQh`kofoO;_m*{uC&$Y#N;D=ZC*`|zNj}R ze6XO?s@`9X-T=h2Oyu3xZ*U;O)_enE-yB~Ol=IVtw;dATI) z)!Oc(yEqm^Ow8&1U|*XM$GvXH@0NFcF~8Dk!`ffGSIxR!z4EomwF7+?Z<-PK_G06L z^6M_UG9&l7nRykp%Uk<+?r@_oZjCSbQQvWP zPAPG>7LA|WdO~`iM=76vJ2&n{O&h_5(&9buo|f;F?JIb9|99E`w~wAI+kZdDdywOe zR(9>yPq?9Y*h%r`P`izj6i?>dnDke*T(xU~NeXTlph8&6u zx)Z+L#xt;J`N|mymJ_G+%!tX}oi=fyw8}Vte33Z$E2FAiMGs~j81FrBk{LfG@10j- z?=Bv;cMrNh=Xvy9n7v?xMY!GS)>piW4z+!fGLhptbHnqVUmuIIE%@Tt*jl5RuXn%m zIIy%_W-_H2DUDy)k>j?1Xu#BVF1LGrdE?{S1m$$csO%0njy5kMczub9oLj+boYrn_8g zvUx-EmGKj1yUwpkzL*%FGx)--LUZ4zSDii`HipK*#6d;fS5zQF3($0y6T+!u`b`tZdJZ?XxhC# zk|U2tc5a;5cJ82^SC&0Z^cpEHk4wDRgH!n~pkG|;a|<&Z7i2V>dbZEHHRip7JXa>X z>bw0n$L+uM`D6O}yzS&dzfBcUQuB#xUrSCK+mD)()^fpv$uDB>KRQ@`e956?a_UTb(M2o$b8p$kDgE%Rl|` zhZXIoFKyCeOi8cu=dQle$760*A2D$pJa@{Gi}9zW9lG>m} zncaR=XmHDx!Am+AaoY$ziZgG^yaVoS9^QRsOu&M#S}pzD^R#EY|LJ2*7c73XcIR1> zg*zvl9Cc=9-)B98laBL-cUZS5^2CO@4>xyue7(xucQEH<L(KCW{m89Vc`8uq+74( zd!-q9r%uM^&mUBIE+_5ertiL++QquDi_Jo}(q=v}RY;#tdUW%uuW z@3lNH_2%WbF49M__;kDkpxD)rhsZ{dZX zdv_gk!n5>1+^EWfqia0}^&8ziYD$NjO|N>`q}R&AY-<-s^);KFvh~HikR(?V>GyL| z{+#?+?&$Q>aQE|H_FQ;dII`P@nAWmEcl}MS-x>Oqu{8GFeb2sky8hIDMA`1CCziGQ zz96sT?y3Fb7ax3iz-ZeGrxDKl#hv?cv!2>7C-*JFjHK(vk0OfCY*Vg1E4W_?wYbw(Islms3lM2YhH}6O@hf| z-RY&}FU8-MK}idkeB$nf_6&`gQ&Wi6BvU!Zjx;;yZ#V7rl(Br7?A&gvxvj6wIJ5D* z(X_iAEIWp{52|@$S?a_0`$D*HiMV|6HV719-=W z@813M4RzBwTwgepWoXd_Xj+$^C0KNST>|V?h^Dqb=u>M=!mh}k)oUs?hvklTC$QDe zro^6NYbagRM~P0j*)-TjprMfu>s@VW>M@Dv{>HG|fSX0eBoSJl1N%ILEQ39{Wm+p= zC?K-{HcJbJc(BVsm|upl()ncwb1v*`zy)og|FYyCPRP7o`0Ez%v6)do~pLcerH}84 zdti4cb6hw>f%bsBvA=slVsfzC4Vc&ySjGdaaOiJU&In$LqxP{3->3G#m*~nIVxq>G zGNg&R#+(UY_JVI!j!Sye-4~|J2!5XiHMpqNMR!F(j-FA)K`0!rj@M#JwaFdui=pvR9Dr9emxxsP$C_CCH8EU_p>B#@;E`oU(kAO*ITVaq=! zC0m>fZvbH65#)$6g;KdVB?plZAWXqmB=9Jd3&x5i5<#*^Aj%h|m zmW>qv@f?u^HjDx6nIe;>im_gf0Nw>4nG~5MHxshq0Ro{kRS+I15M~26c>j`Il%A+x^khCVjjG|p-n;ZS=q1?pDjp%eP-a8BZhX#vAqo2 zE&@00Hvq7|&E%Ck{*V{RQ~U&iuoQW&P$C(})D`6mGqXSlAd{PeZyk_P6m0kpXami{ zB2+AWgQV7|5VVj5Ki-6G!ltK*vvcGE3A|HL=@T~o1#VjJ6x{r}f#HB4`Iw&n{T z9`9eWG|luENwpgY%ZjM~9BcdMr@sTirZm&v%+8uTT3cT;O`cAFJvDhc{cWttGt*y9 zo|*n?@-QLdxHkfY&_f9agTFC3Y{3w^sJH~v z=`84i@4#4zhHCpQOgsLz-$I>#!EbS;hklDek;7qTYN%*b??=2C>eY7{ z!+KIiPx)uUaXLI*`}cm2I2a_r37YDvkC&zcFm9 zc;k0ND&j;kvmuBL#QD4Y8%VanX#W;}^b4JHadZnobNr21fXQNy;qP#u=Az+{lUR}= z%mKI6l%VtWg)=hQu<(-Q2nNbBMZ#2>1_z4uUL5#UX;_HRJ`}KiJKPm&sJIDIWr9d? zO13OVmL?ZOA9?7n=b;ZtE9JUUc62sa~%C1*$agKS6v! A1ONa4 diff --git a/rulebook/pom.xml b/rulebook/pom.xml deleted file mode 100644 index 2a42e36d93..0000000000 --- a/rulebook/pom.xml +++ /dev/null @@ -1,15 +0,0 @@ - - 4.0.0 - com.baeldung.rulebook - rulebook - 1.0.0-SNAPSHOT - - - - com.deliveredtechnologies - rulebook-core - 0.6.2 - - - \ No newline at end of file diff --git a/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java b/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java deleted file mode 100644 index c09772a3c6..0000000000 --- a/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.rulebook; - -import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder; -import com.deliveredtechnologies.rulebook.model.RuleBook; - -public class HelloWorldRule { - public RuleBook defineHelloWorldRules() { - - return RuleBookBuilder.create() - .addRule(rule -> rule.withNoSpecifiedFactType() - .then(f -> System.out.print("Hello "))) - .addRule(rule -> rule.withNoSpecifiedFactType() - .then(f -> System.out.println("World"))) - .build(); - - } -} diff --git a/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java b/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java deleted file mode 100644 index 57965457ec..0000000000 --- a/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.rulebook; - -import com.deliveredtechnologies.rulebook.FactMap; - -public class Launcher { - - public static void main(String[] args) { - HelloWorldRule ruleBook = new HelloWorldRule(); - ruleBook.defineHelloWorldRules() - .run(new FactMap<>()); - } -} diff --git a/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java b/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java deleted file mode 100644 index ca6018a21e..0000000000 --- a/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.autowired; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.stereotype.Service; - -@SpringBootApplication -public class TypesOfBeanInjectionSpring { - private final UserService userService; - - @Autowired // the @Autowired can even be omitted, in case there's only one explicit constructor - public TypesOfBeanInjectionSpring(UserService userService) { - this.userService = userService; - } - - public static void main(String[] args) { - SpringApplication.run(TypesOfBeanInjectionSpring.class, args); - } - - @Bean - CommandLineRunner runIt() { - return args -> { - userService.listUsers() - .stream() - .forEach(System.out::println); - }; - } -} - -class User { - private String name; - - public User(String name) { - this.name = name; - } - - // getters and setters ... - public String getName() { - return this.name; - } - - public String toString() { - return name; - } - -} - -interface UserService { - List listUsers(); -} - -@Service -class UserServiceImpl implements UserService { - - @Override - public List listUsers() { - ArrayList users = new ArrayList<>(3); - users.add(new User("Snoopy")); - users.add(new User("Woodstock")); - users.add(new User("Charlie Brown")); - return users; - } - -} diff --git a/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java b/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java deleted file mode 100644 index 206a062a57..0000000000 --- a/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.autowired; - -import org.junit.Assert; -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; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class TypesOfBeanInjectionSpringIntegrationTest { - @Autowired - UserService userService; - - private static final String[] expected = new String[] { "Snoopy", "Woodstock", "Charlie Brown" }; - - @Test - public void givenDI_whenInjectObject_thenUserNamesAreListed() { - Assert.assertArrayEquals(expected, userService.listUsers() - .stream() - .map(User::getName) - .toArray()); - } -} From def5758f0ae642851048fda8b8120b087b76b380 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Mon, 21 Aug 2017 16:30:44 +0530 Subject: [PATCH 65/67] easy code added for simplicity (#2473) * moving jmh into libraries module * refactoring jmh * Update pom.xml * manual algorightm * with BM result * fix for space issue * Fixed indentation * change as per suggestion * vavr either * adding unit test and othe rutilities * adding concurrent module * concurrent package description * concurrent package description * Update EitherUnitTest.java * introducing lambda expression * jooby project * jooby project * reducing employee bean content * bootique module * bootique * bootique * undertow module * undertow module * refactoring * using lambda * as per baeldung formatter * easy code added for simplicity --- .../baeldung/undertow/secure/CustomIdentityManager.java | 3 ++- .../java/com/baeldung/undertow/secure/SecureServer.java | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java index e0984f65a5..16231f036d 100644 --- a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java +++ b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java @@ -8,9 +8,10 @@ import java.util.Set; import io.undertow.security.idm.Account; import io.undertow.security.idm.Credential; +import io.undertow.security.idm.IdentityManager; import io.undertow.security.idm.PasswordCredential; -public class CustomIdentityManager implements io.undertow.security.idm.IdentityManager { +public class CustomIdentityManager implements IdentityManager { private final Map users; diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java index 6f520944db..9997883da6 100644 --- a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java +++ b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java @@ -29,13 +29,15 @@ public class SecureServer { final IdentityManager idm = new CustomIdentityManager(users); Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity((exchange) -> { - final SecurityContext context = exchange.getSecurityContext(); - exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), - IoCallback.END_EXCHANGE); + setExchange(exchange); }, idm)).build(); server.start(); + } + private static void setExchange(HttpServerExchange exchange) { + final SecurityContext context = exchange.getSecurityContext(); + exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(),IoCallback.END_EXCHANGE); } private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) { From 82c8d8888693e82504a1133fd20d7a37a4854a72 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Mon, 21 Aug 2017 17:55:21 +0530 Subject: [PATCH 66/67] simplifying (#2476) * moving jmh into libraries module * refactoring jmh * Update pom.xml * manual algorightm * with BM result * fix for space issue * Fixed indentation * change as per suggestion * vavr either * adding unit test and othe rutilities * adding concurrent module * concurrent package description * concurrent package description * Update EitherUnitTest.java * introducing lambda expression * jooby project * jooby project * reducing employee bean content * bootique module * bootique * bootique * undertow module * undertow module * refactoring * using lambda * as per baeldung formatter * easy code added for simplicity * simpliflying --- .../undertow/socket/SocketServer.java | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java index 9e0e065c3a..295586e16f 100644 --- a/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java +++ b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java @@ -16,15 +16,7 @@ public class SocketServer { public static void main(String[] args) { Undertow server = Undertow.builder().addHttpListener(8080, "localhost") .setHandler(path().addPrefixPath("/baeldungApp", websocket((exchange, channel) -> { - channel.getReceiveSetter().set(new AbstractReceiveListener() { - @Override - protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { - final String messageData = message.getData(); - for (WebSocketChannel session : channel.getPeerConnections()) { - WebSockets.sendText(messageData, session, null); - } - } - }); + channel.getReceiveSetter().set(getListener()); channel.resumeReceives(); })).addPrefixPath("/", resource(new ClassPathResourceManager(SocketServer.class.getClassLoader(), SocketServer.class.getPackage())).addWelcomeFiles("index.html"))) @@ -33,4 +25,16 @@ public class SocketServer { server.start(); } + private static AbstractReceiveListener getListener() { + return new AbstractReceiveListener() { + @Override + protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { + final String messageData = message.getData(); + for (WebSocketChannel session : channel.getPeerConnections()) { + WebSockets.sendText(messageData, session, null); + } + } + }; + } + } From 84cbc580e5460309f6d7da71fe266e84456ec05c Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 21 Aug 2017 14:52:31 +0200 Subject: [PATCH 67/67] Undertow refactor (#2462) --- .../com/baeldung/undertow/ftp/FileServer.java | 10 +++++----- .../secure/CustomIdentityManager.java | 7 +------ .../undertow/secure/SecureServer.java | 20 +++++++++---------- 3 files changed, 16 insertions(+), 21 deletions(-) diff --git a/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java index 90cad9ebbd..f5cdb827a6 100644 --- a/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java +++ b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java @@ -1,19 +1,19 @@ package com.baeldung.undertow.ftp; -import java.nio.file.Paths; - import io.undertow.Undertow; import io.undertow.server.handlers.resource.PathResourceManager; +import java.nio.file.Paths; + import static io.undertow.Handlers.resource; public class FileServer { public static void main(String[] args) { Undertow server = Undertow.builder().addHttpListener(8080, "localhost") - .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100)) - .setDirectoryListingEnabled(true)) - .build(); + .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100)) + .setDirectoryListingEnabled(true)) + .build(); server.start(); } diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java index 16231f036d..491941261a 100644 --- a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java +++ b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java @@ -54,12 +54,7 @@ public class CustomIdentityManager implements IdentityManager { private static final long serialVersionUID = 1L; - private final Principal principal = new Principal() { - @Override - public String getName() { - return id; - } - }; + private final Principal principal = () -> id; @Override public Principal getPrincipal() { diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java index 9997883da6..6532c3ed7c 100644 --- a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java +++ b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java @@ -1,10 +1,5 @@ package com.baeldung.undertow.secure; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import io.undertow.Undertow; import io.undertow.io.IoCallback; import io.undertow.security.api.AuthenticationMechanism; @@ -19,6 +14,11 @@ import io.undertow.security.impl.BasicAuthenticationMechanism; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + public class SecureServer { public static void main(String[] args) { @@ -28,16 +28,16 @@ public class SecureServer { final IdentityManager idm = new CustomIdentityManager(users); - Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity((exchange) -> { - setExchange(exchange); - }, idm)).build(); + Undertow server = Undertow.builder() + .addHttpListener(8080, "localhost") + .setHandler(addSecurity(SecureServer::setExchange, idm)).build(); server.start(); } private static void setExchange(HttpServerExchange exchange) { final SecurityContext context = exchange.getSecurityContext(); - exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(),IoCallback.END_EXCHANGE); + exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE); } private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) { @@ -45,7 +45,7 @@ public class SecureServer { handler = new AuthenticationCallHandler(handler); handler = new AuthenticationConstraintHandler(handler); final List mechanisms = Collections - . singletonList(new BasicAuthenticationMechanism("Baeldung_Realm")); + .singletonList(new BasicAuthenticationMechanism("Baeldung_Realm")); handler = new AuthenticationMechanismsHandler(handler, mechanisms); handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler); return handler;