From 7ec1db1be2c508793f16a6a317bf5d2eab49343a Mon Sep 17 00:00:00 2001 From: juan Date: Tue, 15 Aug 2017 23:48:47 -0300 Subject: [PATCH 01/33] 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 491fc883bef942482a26710000df16dfe877d940 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Wed, 16 Aug 2017 18:17:07 +0100 Subject: [PATCH 02/33] 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 03/33] 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 04/33] 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 05/33] 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 06/33] 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 07/33] 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 08/33] 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 09/33] 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 10/33] 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 11/33] 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 12/33] 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 13/33] 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 14/33] 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 15/33] 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 16/33] 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 17/33] 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; From 6d7fa197dd9982dbcaf0ae73ac43b00fa0ae9187 Mon Sep 17 00:00:00 2001 From: "Eunice A. Obugyei" Date: Mon, 21 Aug 2017 15:55:26 +0000 Subject: [PATCH 18/33] BAEL-1014 [Spring MVC with Kotlin] (#2475) * 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 * Removed dependency for kotlin-reflect --- spring-mvc-kotlin/pom.xml | 5 ----- spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index 087f02fc68..5375ecae7c 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -23,11 +23,6 @@ kotlin-stdlib-jre8 1.1.4 - - org.jetbrains.kotlin - kotlin-reflect - 1.1.4 - org.springframework 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 index bdb6716889..3f68f128bc 100644 --- a/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp @@ -2,6 +2,6 @@ Welcome -

This is the body of the welcome view 2

+

This is the body of the welcome view

\ No newline at end of file From 04fa1782a24f7ca9b257829b677d4ab3d170b1ea Mon Sep 17 00:00:00 2001 From: lor6 Date: Mon, 21 Aug 2017 21:25:12 +0300 Subject: [PATCH 19/33] reladomo example (#2469) * reladomo example * fix formatting * add plugin versions * fix closing streams --- libraries/pom.xml | 100 +++++++++++++++++- .../com/baeldung/reladomo/Department.java | 15 +++ .../reladomo/DepartmentDatabaseObject.java | 4 + .../com/baeldung/reladomo/DepartmentList.java | 25 +++++ .../java/com/baeldung/reladomo/Employee.java | 16 +++ .../reladomo/EmployeeDatabaseObject.java | 4 + .../com/baeldung/reladomo/EmployeeList.java | 25 +++++ .../reladomo/ReladomoApplication.java | 54 ++++++++++ .../reladomo/ReladomoConnectionManager.java | 92 ++++++++++++++++ .../main/resources/ReladomoRuntimeConfig.xml | 6 ++ .../main/resources/reladomo/Department.xml | 11 ++ .../src/main/resources/reladomo/Employee.xml | 9 ++ .../resources/reladomo/ReladomoClassList.xml | 4 + .../com/baeldung/reladomo/ReladomoTest.java | 38 +++++++ .../resources/reladomo/ReladomoTestConfig.xml | 7 ++ .../src/test/resources/reladomo/test-data.txt | 7 ++ 16 files changed, 415 insertions(+), 2 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/reladomo/Department.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/Employee.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java create mode 100644 libraries/src/main/resources/ReladomoRuntimeConfig.xml create mode 100644 libraries/src/main/resources/reladomo/Department.xml create mode 100644 libraries/src/main/resources/reladomo/Employee.xml create mode 100644 libraries/src/main/resources/reladomo/ReladomoClassList.xml create mode 100644 libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java create mode 100644 libraries/src/test/resources/reladomo/ReladomoTestConfig.xml create mode 100644 libraries/src/test/resources/reladomo/test-data.txt diff --git a/libraries/pom.xml b/libraries/pom.xml index cf77d197a2..e9603b1453 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -105,6 +105,92 @@ + + + + maven-antrun-plugin + 1.8 + + + generateMithra + generate-sources + + run + + + + + + + + + + + + + + + + + + com.goldmansachs.reladomo + reladomogen + ${reladomo.version} + + + + com.goldmansachs.reladomo + reladomo-gen-util + ${reladomo.version} + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/reladomo + + + + + add-resource + generate-resources + + add-resource + + + + + ${project.build.directory}/generated-db/ + + + + + + + + @@ -497,6 +583,16 @@ gt-swing ${geotools.version}
+ + com.goldmansachs.reladomo + reladomo + ${reladomo.version} + + + com.goldmansachs.reladomo + reladomo-test-util + ${reladomo.version} + @@ -563,6 +659,6 @@ 0.6.5 0.9.0 15.2 + 16.5.1 - - + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/reladomo/Department.java b/libraries/src/main/java/com/baeldung/reladomo/Department.java new file mode 100644 index 0000000000..d26ddafbf4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/Department.java @@ -0,0 +1,15 @@ +package com.baeldung.reladomo; + +public class Department extends DepartmentAbstract { + public Department() { + super(); + // You must not modify this constructor. Mithra calls this internally. + // You can call this constructor. You can also add new constructors. + } + + public Department(long id, String name) { + super(); + this.setId(id); + this.setName(name); + } +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java b/libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java new file mode 100644 index 0000000000..4cfb5cb055 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java @@ -0,0 +1,4 @@ +package com.baeldung.reladomo; +public class DepartmentDatabaseObject extends DepartmentDatabaseObjectAbstract +{ +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java b/libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java new file mode 100644 index 0000000000..edad6bc1f4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java @@ -0,0 +1,25 @@ +package com.baeldung.reladomo; +import com.gs.fw.finder.Operation; +import java.util.*; +public class DepartmentList extends DepartmentListAbstract +{ + public DepartmentList() + { + super(); + } + + public DepartmentList(int initialSize) + { + super(initialSize); + } + + public DepartmentList(Collection c) + { + super(c); + } + + public DepartmentList(Operation operation) + { + super(operation); + } +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/Employee.java b/libraries/src/main/java/com/baeldung/reladomo/Employee.java new file mode 100644 index 0000000000..519e841282 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/Employee.java @@ -0,0 +1,16 @@ +package com.baeldung.reladomo; +public class Employee extends EmployeeAbstract +{ + public Employee() + { + super(); + // You must not modify this constructor. Mithra calls this internally. + // You can call this constructor. You can also add new constructors. + } + + public Employee(long id, String name){ + super(); + this.setId(id); + this.setName(name); + } +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java b/libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java new file mode 100644 index 0000000000..407049f342 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java @@ -0,0 +1,4 @@ +package com.baeldung.reladomo; +public class EmployeeDatabaseObject extends EmployeeDatabaseObjectAbstract +{ +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java b/libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java new file mode 100644 index 0000000000..4e759898c3 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java @@ -0,0 +1,25 @@ +package com.baeldung.reladomo; +import com.gs.fw.finder.Operation; +import java.util.*; +public class EmployeeList extends EmployeeListAbstract +{ + public EmployeeList() + { + super(); + } + + public EmployeeList(int initialSize) + { + super(initialSize); + } + + public EmployeeList(Collection c) + { + super(c); + } + + public EmployeeList(Operation operation) + { + super(operation); + } +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java b/libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java new file mode 100644 index 0000000000..c6b242d3ae --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java @@ -0,0 +1,54 @@ +package com.baeldung.reladomo; + +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.gs.fw.common.mithra.MithraManager; +import com.gs.fw.common.mithra.MithraManagerProvider; + +public class ReladomoApplication { + + public static void main(String[] args) { + + try { + ReladomoConnectionManager.getInstance().createTables(); + } catch (Exception e1) { + e1.printStackTrace(); + } + + MithraManager mithraManager = MithraManagerProvider.getMithraManager(); + mithraManager.setTransactionTimeout(120); + + try (InputStream is = ReladomoApplication.class.getClassLoader().getResourceAsStream("ReladomoRuntimeConfig.xml")) { + MithraManagerProvider.getMithraManager().readConfiguration(is); + + Department department = new Department(1, "IT"); + Employee employee = new Employee(1, "John"); + department.getEmployees().add(employee); + department.cascadeInsert(); + + Department depFound = DepartmentFinder.findByPrimaryKey(1); + System.out.println("Department Name:" + department.getName()); + + Employee empFound = EmployeeFinder.findOne(EmployeeFinder.name().eq("John")); + System.out.println("Employee Id:" + empFound.getId()); + empFound.setName("Steven"); + empFound.delete(); + Department depDetached = DepartmentFinder.findByPrimaryKey(1).getDetachedCopy(); + + mithraManager.executeTransactionalCommand(tx -> { + Department dep = new Department(2, "HR"); + Employee emp = new Employee(2, "Jim"); + dep.getEmployees().add(emp); + dep.cascadeInsert(); + return null; + }); + + } catch (java.io.IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java b/libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java new file mode 100644 index 0000000000..66a8f9ff99 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java @@ -0,0 +1,92 @@ +package com.baeldung.reladomo; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.TimeZone; +import java.util.stream.Stream; + +import org.h2.tools.RunScript; + +import com.gs.fw.common.mithra.bulkloader.BulkLoader; +import com.gs.fw.common.mithra.bulkloader.BulkLoaderException; +import com.gs.fw.common.mithra.connectionmanager.SourcelessConnectionManager; +import com.gs.fw.common.mithra.connectionmanager.XAConnectionManager; +import com.gs.fw.common.mithra.databasetype.DatabaseType; +import com.gs.fw.common.mithra.databasetype.H2DatabaseType; + +public class ReladomoConnectionManager implements SourcelessConnectionManager { + + private static ReladomoConnectionManager instance; + + private XAConnectionManager xaConnectionManager; + + private final String databaseName = "myDb"; + + public static synchronized ReladomoConnectionManager getInstance() { + if (instance == null) { + instance = new ReladomoConnectionManager(); + } + return instance; + } + + private ReladomoConnectionManager() { + this.createConnectionManager(); + } + + private XAConnectionManager createConnectionManager() { + xaConnectionManager = new XAConnectionManager(); + xaConnectionManager.setDriverClassName("org.h2.Driver"); + xaConnectionManager.setJdbcConnectionString("jdbc:h2:mem:" + databaseName); + xaConnectionManager.setJdbcUser("sa"); + xaConnectionManager.setJdbcPassword(""); + xaConnectionManager.setPoolName("My Connection Pool"); + xaConnectionManager.setInitialSize(1); + xaConnectionManager.setPoolSize(10); + xaConnectionManager.initialisePool(); + return xaConnectionManager; + } + + @Override + public BulkLoader createBulkLoader() throws BulkLoaderException { + return null; + } + + @Override + public Connection getConnection() { + return xaConnectionManager.getConnection(); + } + + @Override + public DatabaseType getDatabaseType() { + return H2DatabaseType.getInstance(); + } + + @Override + public TimeZone getDatabaseTimeZone() { + return TimeZone.getDefault(); + } + + @Override + public String getDatabaseIdentifier() { + return databaseName; + } + + public void createTables() throws Exception { + Path ddlPath = Paths.get(ClassLoader.getSystemResource("sql").toURI()); + + try (Connection conn = xaConnectionManager.getConnection(); Stream list = Files.list(ddlPath);) { + list.forEach(path -> { + try { + RunScript.execute(conn, Files.newBufferedReader(path)); + } catch (SQLException | IOException exc) { + exc.printStackTrace(); + } + }); + } + } + +} diff --git a/libraries/src/main/resources/ReladomoRuntimeConfig.xml b/libraries/src/main/resources/ReladomoRuntimeConfig.xml new file mode 100644 index 0000000000..7181e75406 --- /dev/null +++ b/libraries/src/main/resources/ReladomoRuntimeConfig.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/libraries/src/main/resources/reladomo/Department.xml b/libraries/src/main/resources/reladomo/Department.xml new file mode 100644 index 0000000000..a284965cd6 --- /dev/null +++ b/libraries/src/main/resources/reladomo/Department.xml @@ -0,0 +1,11 @@ + + com.baeldung.reladomo + Department + departments + + + + + Employee.departmentId = this.id + + \ No newline at end of file diff --git a/libraries/src/main/resources/reladomo/Employee.xml b/libraries/src/main/resources/reladomo/Employee.xml new file mode 100644 index 0000000000..00e360bc67 --- /dev/null +++ b/libraries/src/main/resources/reladomo/Employee.xml @@ -0,0 +1,9 @@ + + com.baeldung.reladomo + Employee + employees + + + + + \ No newline at end of file diff --git a/libraries/src/main/resources/reladomo/ReladomoClassList.xml b/libraries/src/main/resources/reladomo/ReladomoClassList.xml new file mode 100644 index 0000000000..99118a745d --- /dev/null +++ b/libraries/src/main/resources/reladomo/ReladomoClassList.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java b/libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java new file mode 100644 index 0000000000..61c29e8aa3 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java @@ -0,0 +1,38 @@ +package com.baeldung.reladomo; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.gs.fw.common.mithra.test.ConnectionManagerForTests; +import com.gs.fw.common.mithra.test.MithraTestResource; + +public class ReladomoTest { + private MithraTestResource mithraTestResource; + + @Before + public void setUp() throws Exception { + this.mithraTestResource = new MithraTestResource("reladomo/ReladomoTestConfig.xml"); + + final ConnectionManagerForTests connectionManager = ConnectionManagerForTests.getInstanceForDbName("testDb"); + this.mithraTestResource.createSingleDatabase(connectionManager); + + mithraTestResource.addTestDataToDatabase("reladomo/test-data.txt", connectionManager); + + this.mithraTestResource.setUp(); + } + + @Test + public void whenGetTestData_thenOk() { + Employee employee = EmployeeFinder.findByPrimaryKey(1); + assertEquals(employee.getName(), "Paul"); + } + + @After + public void tearDown() throws Exception { + this.mithraTestResource.tearDown(); + } + +} diff --git a/libraries/src/test/resources/reladomo/ReladomoTestConfig.xml b/libraries/src/test/resources/reladomo/ReladomoTestConfig.xml new file mode 100644 index 0000000000..a1951f09b7 --- /dev/null +++ b/libraries/src/test/resources/reladomo/ReladomoTestConfig.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/libraries/src/test/resources/reladomo/test-data.txt b/libraries/src/test/resources/reladomo/test-data.txt new file mode 100644 index 0000000000..8e407278ac --- /dev/null +++ b/libraries/src/test/resources/reladomo/test-data.txt @@ -0,0 +1,7 @@ +class com.baeldung.reladomo.Department +id, name +1, "Marketing" + +class com.baeldung.reladomo.Employee +id, name +1, "Paul" \ No newline at end of file From 706b3d6c676e198707d00f0febc51c1180c788d0 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Mon, 21 Aug 2017 20:01:41 +0100 Subject: [PATCH 20/33] Example for a GraphQL Application in Spring Boot (#2477) --- spring-boot/pom.xml | 16 +++++ .../java/com/baeldung/graphql/Author.java | 31 ++++++++++ .../java/com/baeldung/graphql/AuthorDao.java | 18 ++++++ .../com/baeldung/graphql/AuthorResolver.java | 17 ++++++ .../graphql/GraphqlConfiguration.java | 59 +++++++++++++++++++ .../java/com/baeldung/graphql/Mutation.java | 25 ++++++++ .../main/java/com/baeldung/graphql/Post.java | 49 +++++++++++++++ .../java/com/baeldung/graphql/PostDao.java | 29 +++++++++ .../com/baeldung/graphql/PostResolver.java | 17 ++++++ .../main/java/com/baeldung/graphql/Query.java | 17 ++++++ .../org/baeldung/boot/DemoApplication.java | 3 + .../src/main/resources/graphql/blog.graphqls | 24 ++++++++ 12 files changed, 305 insertions(+) create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/Author.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/Mutation.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/Post.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/PostDao.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/Query.java create mode 100644 spring-boot/src/main/resources/graphql/blog.graphqls diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 0cf7df86cd..9d44de64a3 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -40,6 +40,22 @@ spring-boot-starter-security + + com.graphql-java + graphql-spring-boot-starter + 3.6.0 + + + com.graphql-java + graphiql-spring-boot-starter + 3.6.0 + + + com.graphql-java + graphql-java-tools + 3.2.0 + + org.springframework.boot spring-boot-starter-tomcat diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Author.java b/spring-boot/src/main/java/com/baeldung/graphql/Author.java new file mode 100644 index 0000000000..11e927c564 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Author.java @@ -0,0 +1,31 @@ +package com.baeldung.graphql; + +public class Author { + private String id; + private String name; + private String thumbnail; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getThumbnail() { + return thumbnail; + } + + public void setThumbnail(String thumbnail) { + this.thumbnail = thumbnail; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java b/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java new file mode 100644 index 0000000000..522732faeb --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java @@ -0,0 +1,18 @@ +package com.baeldung.graphql; + +import java.util.List; +import java.util.Optional; + +public class AuthorDao { + private List authors; + + public AuthorDao(List authors) { + this.authors = authors; + } + + public Optional getAuthor(String id) { + return authors.stream() + .filter(author -> id.equals(author.getId())) + .findFirst(); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java b/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java new file mode 100644 index 0000000000..982c6cebc1 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import java.util.List; + +import com.coxautodev.graphql.tools.GraphQLResolver; + +public class AuthorResolver implements GraphQLResolver { + private PostDao postDao; + + public AuthorResolver(PostDao postDao) { + this.postDao = postDao; + } + + public List getPosts(Author author) { + return postDao.getAuthorPosts(author.getId()); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java new file mode 100644 index 0000000000..a7a864cf96 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java @@ -0,0 +1,59 @@ +package com.baeldung.graphql; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class GraphqlConfiguration { + @Bean + public PostDao postDao() { + List posts = new ArrayList<>(); + for (int postId = 0; postId < 10; ++postId) { + for (int authorId = 0; authorId < 10; ++authorId) { + Post post = new Post(); + post.setId("Post" + authorId + postId); + post.setTitle("Post " + authorId + ":" + postId); + post.setText("Post " + postId + " + by author " + authorId); + post.setAuthorId("Author" + authorId); + posts.add(post); + } + } + return new PostDao(posts); + } + + @Bean + public AuthorDao authorDao() { + List authors = new ArrayList<>(); + for (int authorId = 0; authorId < 10; ++authorId) { + Author author = new Author(); + author.setId("Author" + authorId); + author.setName("Author " + authorId); + author.setThumbnail("http://example.com/authors/" + authorId); + authors.add(author); + } + return new AuthorDao(authors); + } + + @Bean + public PostResolver postResolver(AuthorDao authorDao) { + return new PostResolver(authorDao); + } + + @Bean + public AuthorResolver authorResolver(PostDao postDao) { + return new AuthorResolver(postDao); + } + + @Bean + public Query query(PostDao postDao) { + return new Query(postDao); + } + + @Bean + public Mutation mutation(PostDao postDao) { + return new Mutation(postDao); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java new file mode 100644 index 0000000000..0e16e3c8b7 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java @@ -0,0 +1,25 @@ +package com.baeldung.graphql; + +import java.util.UUID; + +import com.coxautodev.graphql.tools.GraphQLMutationResolver; + +public class Mutation implements GraphQLMutationResolver { + private PostDao postDao; + + public Mutation(PostDao postDao) { + this.postDao = postDao; + } + + public Post writePost(String title, String text, String category, String author) { + Post post = new Post(); + post.setId(UUID.randomUUID().toString()); + post.setTitle(title); + post.setText(text); + post.setCategory(category); + post.setAuthorId(author); + postDao.savePost(post); + + return post; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Post.java b/spring-boot/src/main/java/com/baeldung/graphql/Post.java new file mode 100644 index 0000000000..14d3084841 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Post.java @@ -0,0 +1,49 @@ +package com.baeldung.graphql; + +public class Post { + private String id; + private String title; + private String text; + private String category; + private String authorId; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getAuthorId() { + return authorId; + } + + public void setAuthorId(String authorId) { + this.authorId = authorId; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java b/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java new file mode 100644 index 0000000000..f8d243ee3a --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java @@ -0,0 +1,29 @@ +package com.baeldung.graphql; + +import java.util.List; +import java.util.stream.Collectors; + +public class PostDao { + private List posts; + + public PostDao(List posts) { + this.posts = posts; + } + + public List getRecentPosts(int count, int offset) { + return posts.stream() + .skip(offset) + .limit(count) + .collect(Collectors.toList()); + } + + public List getAuthorPosts(String author) { + return posts.stream() + .filter(post -> author.equals(post.getAuthorId())) + .collect(Collectors.toList()); + } + + public void savePost(Post post) { + posts.add(0, post); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java b/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java new file mode 100644 index 0000000000..dbfde330ea --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import java.util.Optional; + +import com.coxautodev.graphql.tools.GraphQLResolver; + +public class PostResolver implements GraphQLResolver { + private AuthorDao authorDao; + + public PostResolver(AuthorDao authorDao) { + this.authorDao = authorDao; + } + + public Optional getAuthor(Post post) { + return authorDao.getAuthor(post.getAuthorId()); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Query.java b/spring-boot/src/main/java/com/baeldung/graphql/Query.java new file mode 100644 index 0000000000..7bb625798c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Query.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import java.util.List; + +import com.coxautodev.graphql.tools.GraphQLQueryResolver; + +public class Query implements GraphQLQueryResolver { + private PostDao postDao; + + public Query(PostDao postDao) { + this.postDao = postDao; + } + + public List recentPosts(int count, int offset) { + return postDao.getRecentPosts(count, offset); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java index 2d83b650ec..5de4134739 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java @@ -1,11 +1,14 @@ package org.baeldung.boot; +import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; +import org.springframework.context.annotation.Import; @SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@Import(GraphqlConfiguration.class) public class DemoApplication { public static void main(String[] args) { diff --git a/spring-boot/src/main/resources/graphql/blog.graphqls b/spring-boot/src/main/resources/graphql/blog.graphqls new file mode 100644 index 0000000000..aa0c8757e9 --- /dev/null +++ b/spring-boot/src/main/resources/graphql/blog.graphqls @@ -0,0 +1,24 @@ +type Post { + id: ID! + title: String! + text: String! + category: String + author: Author +} + +type Author { + id: ID! + name: String! + thumbnail: String + posts: [Post]! +} + +# The Root Query for the application +type Query { + recentPosts(count: Int, offset: Int): [Post]! +} + +# The Root Mutation for the application +type Mutation { + writePost(title: String!, text: String!, category: String, author: String!) : Post! +} From 802c0b09e044c7047b10e349cf8e31c844c1913e Mon Sep 17 00:00:00 2001 From: Tian Baoqiang Date: Mon, 21 Aug 2017 15:58:37 -0500 Subject: [PATCH 21/33] #BAEL-1025 (#2445) --- ratpack/pom.xml | 22 ++++++++ .../hystrix/HystrixAsyncHttpCommand.java | 54 ++++++++++++++++++ .../hystrix/HystrixReactiveHttpCommand.java | 44 +++++++++++++++ .../hystrix/HystrixSyncHttpCommand.java | 55 +++++++++++++++++++ .../baeldung/hystrix/RatpackHystrixApp.java | 30 ++++++++++ .../RatpackHystrixAppFallbackLiveTest.java | 50 +++++++++++++++++ .../hystrix/RatpackHystrixAppLiveTest.java | 50 +++++++++++++++++ 7 files changed, 305 insertions(+) create mode 100644 ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java create mode 100644 ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java create mode 100644 ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java create mode 100644 ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java create mode 100644 ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java create mode 100644 ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java diff --git a/ratpack/pom.xml b/ratpack/pom.xml index 7a75ec50b7..3f953b3ed0 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -40,16 +40,38 @@ ratpack-hikari ${ratpack.version} + + io.ratpack + ratpack-hystrix + ${ratpack.version} + + + io.ratpack + ratpack-rx + ${ratpack.version} + io.ratpack ratpack-test ${ratpack.version} + test com.h2database h2 1.4.193 + + + org.apache.httpcomponents + httpclient + 4.5.3 + + + org.apache.httpcomponents + httpcore + 4.4.6 + diff --git a/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java b/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java new file mode 100644 index 0000000000..a1a19150c3 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java @@ -0,0 +1,54 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; + +import java.net.URI; +import java.util.Collections; + +/** + * @author aiet + */ +public class HystrixAsyncHttpCommand extends HystrixCommand { + + private URI uri; + private RequestConfig requestConfig; + + HystrixAsyncHttpCommand(URI uri, int timeoutMillis) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-async")) + .andCommandPropertiesDefaults(HystrixCommandProperties + .Setter() + .withExecutionTimeoutInMilliseconds(timeoutMillis))); + requestConfig = RequestConfig + .custom() + .setSocketTimeout(timeoutMillis) + .setConnectTimeout(timeoutMillis) + .setConnectionRequestTimeout(timeoutMillis) + .build(); + this.uri = uri; + } + + @Override + protected String run() throws Exception { + return EntityUtils.toString(HttpClientBuilder + .create() + .setDefaultRequestConfig(requestConfig) + .setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient"))) + .build() + .execute(new HttpGet(uri)) + .getEntity()); + } + + @Override + protected String getFallback() { + return "eugenp's async fallback profile"; + } + +} diff --git a/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java b/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java new file mode 100644 index 0000000000..f9f85c705b --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java @@ -0,0 +1,44 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import com.netflix.hystrix.HystrixObservableCommand; +import ratpack.http.client.HttpClient; +import ratpack.rx.RxRatpack; +import rx.Observable; + +import java.net.URI; + +/** + * @author aiet + */ +public class HystrixReactiveHttpCommand extends HystrixObservableCommand { + + private HttpClient httpClient; + private URI uri; + + HystrixReactiveHttpCommand(HttpClient httpClient, URI uri, int timeoutMillis) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-reactive")) + .andCommandPropertiesDefaults(HystrixCommandProperties + .Setter() + .withExecutionTimeoutInMilliseconds(timeoutMillis))); + this.httpClient = httpClient; + this.uri = uri; + } + + @Override + protected Observable construct() { + return RxRatpack.observe(httpClient + .get(uri, requestSpec -> requestSpec.headers(mutableHeaders -> mutableHeaders.add("User-Agent", "Baeldung HttpClient"))) + .map(receivedResponse -> receivedResponse + .getBody() + .getText())); + } + + @Override + protected Observable resumeWithFallback() { + return Observable.just("eugenp's reactive fallback profile"); + } + +} diff --git a/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java b/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java new file mode 100644 index 0000000000..7c848331ca --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java @@ -0,0 +1,55 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; + +import java.net.URI; +import java.util.Collections; + +/** + * @author aiet + */ +public class HystrixSyncHttpCommand extends HystrixCommand { + + private URI uri; + private RequestConfig requestConfig; + + HystrixSyncHttpCommand(URI uri, int timeoutMillis) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-sync")) + .andCommandPropertiesDefaults(HystrixCommandProperties + .Setter() + .withExecutionTimeoutInMilliseconds(timeoutMillis))); + requestConfig = RequestConfig + .custom() + .setSocketTimeout(timeoutMillis) + .setConnectTimeout(timeoutMillis) + .setConnectionRequestTimeout(timeoutMillis) + .build(); + this.uri = uri; + } + + @Override + protected String run() throws Exception { + HttpGet request = new HttpGet(uri); + return EntityUtils.toString(HttpClientBuilder + .create() + .setDefaultRequestConfig(requestConfig) + .setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient"))) + .build() + .execute(request) + .getEntity()); + } + + @Override + protected String getFallback() { + return "eugenp's sync fallback profile"; + } + +} diff --git a/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java b/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java new file mode 100644 index 0000000000..1e4724bd96 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java @@ -0,0 +1,30 @@ +package com.baeldung.hystrix; + +import ratpack.guice.Guice; +import ratpack.http.client.HttpClient; +import ratpack.hystrix.HystrixMetricsEventStreamHandler; +import ratpack.hystrix.HystrixModule; +import ratpack.server.RatpackServer; + +import java.net.URI; + +public class RatpackHystrixApp { + + public static void main(String[] args) throws Exception { + final int timeout = Integer.valueOf(System.getProperty("ratpack.hystrix.timeout")); + final URI eugenGithubProfileUri = new URI("https://api.github.com/users/eugenp"); + + RatpackServer.start(server -> server + .registry(Guice.registry(bindingsSpec -> bindingsSpec.module(new HystrixModule().sse()))) + .handlers(chain -> chain + .get("rx", ctx -> new HystrixReactiveHttpCommand(ctx.get(HttpClient.class), eugenGithubProfileUri, timeout) + .toObservable() + .subscribe(ctx::render)) + .get("async", ctx -> ctx.render(new HystrixAsyncHttpCommand(eugenGithubProfileUri, timeout) + .queue() + .get())) + .get("sync", ctx -> ctx.render(new HystrixSyncHttpCommand(eugenGithubProfileUri, timeout).execute())) + .get("hystrix", new HystrixMetricsEventStreamHandler()))); + + } +} diff --git a/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java new file mode 100644 index 0000000000..25287a5cbd --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.hystrix; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import ratpack.test.MainClassApplicationUnderTest; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +/** + * @author aiet + */ +public class RatpackHystrixAppFallbackLiveTest { + + static MainClassApplicationUnderTest appUnderTest; + + @BeforeClass + public static void setup() { + System.setProperty("ratpack.hystrix.timeout", "10"); + appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class); + } + + @Test + public void whenFetchReactive_thenGotFallbackProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("rx"), containsString("reactive fallback profile")); + } + + @Test + public void whenFetchAsync_thenGotFallbackProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("async"), containsString("async fallback profile")); + } + + @Test + public void whenFetchSync_thenGotFallbackProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("sync"), containsString("sync fallback profile")); + } + + @AfterClass + public static void clean() { + appUnderTest.close(); + } + +} diff --git a/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java new file mode 100644 index 0000000000..843ef68e13 --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.hystrix; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import ratpack.test.MainClassApplicationUnderTest; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +/** + * @author aiet + */ +public class RatpackHystrixAppLiveTest { + + static MainClassApplicationUnderTest appUnderTest; + + @BeforeClass + public static void setup() { + System.setProperty("ratpack.hystrix.timeout", "5000"); + appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class); + } + + @Test + public void whenFetchReactive_thenGotEugenProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("rx"), containsString("www.baeldung.com")); + } + + @Test + public void whenFetchAsync_thenGotEugenProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("async"), containsString("www.baeldung.com")); + } + + @Test + public void whenFetchSync_thenGotEugenProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("sync"), containsString("www.baeldung.com")); + } + + @AfterClass + public static void clean() { + appUnderTest.close(); + } + +} From 822e8682b64a41a1d99a4790719d131f114708df Mon Sep 17 00:00:00 2001 From: lor6 Date: Tue, 22 Aug 2017 00:03:12 +0300 Subject: [PATCH 22/33] lambda example (#2480) --- .../LambdaExpressionsIntegrationTest.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java new file mode 100644 index 0000000000..a1454c16cc --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.logging.log4j2.tests; + +import java.util.Random; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.Test; + +public class LambdaExpressionsIntegrationTest { + + private static final Logger logger = LogManager.getRootLogger(); + + @Test + public void whenCheckLogMessage_thenOk() { + if (logger.isTraceEnabled()) { + logger.trace("Numer is {}", getRandomNumber()); + } + } + + @Test + public void whenUseLambdaExpression_thenOk() { + logger.trace("Number is {}", () -> getRandomNumber()); + logger.trace("Name is {} and age is {}", () -> getName(), () -> getRandomNumber()); + } + + private int getRandomNumber() { + return (new Random()).nextInt(10); + } + + private String getName() { + return "John"; + } +} From 8c0ce48aaee0bfa5b4cf772db424c9e6828eba87 Mon Sep 17 00:00:00 2001 From: Mansi Date: Tue, 22 Aug 2017 02:38:41 +0530 Subject: [PATCH 23/33] BAEL-1045 Lambda Behave (#2456) * 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 * BAEL-1045 Lambda Behave * BAEL-1045 Lambda Behave * BAEL-1045 Lambda Behave --- testing/pom.xml | 5 ++ .../com/baeldung/lambdabehave/Calculator.java | 24 +++++++++ .../baeldung/lambdabehave/CalculatorTest.java | 54 +++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 testing/src/main/java/com/baeldung/lambdabehave/Calculator.java create mode 100644 testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java diff --git a/testing/pom.xml b/testing/pom.xml index bfd47dbc4a..72ec2b2f0c 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -13,6 +13,11 @@ + + com.insightfullogic + lambda-behave + 0.4 + com.google.guava guava diff --git a/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java b/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java new file mode 100644 index 0000000000..b194dce500 --- /dev/null +++ b/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java @@ -0,0 +1,24 @@ +package com.baeldung.lambdabehave; + +public class Calculator { + + private int x; + private int y; + + Calculator(int x, int y) { + this.x = x; + this.y = y; + } + + public int add() { + return this.x + this.y; + } + + public int divide(int a, int b) { + return a / b; + } + + public int add(int a, int b) { + return a + b; + } +} diff --git a/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java b/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java new file mode 100644 index 0000000000..d179c6eb0e --- /dev/null +++ b/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java @@ -0,0 +1,54 @@ +package com.baeldung.lambdabehave; + +import com.insightfullogic.lambdabehave.JunitSuiteRunner; +import com.insightfullogic.lambdabehave.Suite; +import com.insightfullogic.lambdabehave.generators.Generator; +import com.insightfullogic.lambdabehave.generators.SourceGenerator; +import org.junit.runner.RunWith; + +@RunWith(JunitSuiteRunner.class) +public class CalculatorTest { + + private Calculator calculator; + + { + Suite.describe("Lambda behave example tests", it -> { + + it.isSetupWith(() -> { + calculator = new Calculator(1, 2); + }); + it.should("Add the given numbers", expect -> { + expect.that(calculator.add()).is(3); + }); + it.should("Throw an exception if divide by 0", expect -> { + expect.exception(ArithmeticException.class, () -> { + calculator.divide(1, 0); + }); + }); + it.uses(2, 3, 5) + .and(23, 10, 33) + .toShow("%d + %d = %d", (expect, a, b, c) -> { + expect.that(calculator.add(a, b)).is(c); + }); + it.requires(2) + .example(Generator.asciiStrings()) + .toShow("Reversing a String twice returns the original String", (expect, str) -> { + String same = new StringBuilder(str).reverse() + .reverse() + .toString(); + expect.that(same) + .isEqualTo(str); + }); + it.requires(2) + .withSource(SourceGenerator.deterministicNumbers(5626689007407L)) + .example(Generator.asciiStrings()) + .toShow("Reversing a String twice returns the original String", (expect, str) -> { + String same = new StringBuilder(str).reverse() + .reverse() + .toString(); + expect.that(same) + .isEqualTo(str); + }); + }); + } +} From 8a344330950ecd9c728c80148373be24851fd2f2 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 22 Aug 2017 13:13:24 +0200 Subject: [PATCH 24/33] Optimize libraries (#2458) --- .../com/baeldung/chronicle/queue/ChronicleQueue.java | 2 +- ...Test.java => AsyncServiceLongRunningUnitTest.java} | 11 +++++++---- ...ueTest.java => ChronicleQueueIntegrationTest.java} | 2 +- .../{HLLUnitTest.java => HLLLongRunningUnitTest.java} | 2 +- 4 files changed, 10 insertions(+), 7 deletions(-) rename libraries/src/test/java/com/baeldung/awaitility/{AsyncServiceUnitTest.java => AsyncServiceLongRunningUnitTest.java} (86%) rename libraries/src/test/java/com/baeldung/chronicle/queue/{ChronicleQueueTest.java => ChronicleQueueIntegrationTest.java} (96%) rename libraries/src/test/java/com/baeldung/hll/{HLLUnitTest.java => HLLLongRunningUnitTest.java} (98%) diff --git a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java index b7770e0b78..f6bd25c0fe 100644 --- a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java +++ b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java @@ -7,7 +7,7 @@ import net.openhft.chronicle.ExcerptAppender; public class ChronicleQueue { - public static void writeToQueue( + static void writeToQueue( Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) throws IOException { ExcerptAppender appender = chronicle.createAppender(); diff --git a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java similarity index 86% rename from libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java rename to libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java index 43537965f8..d17a7dcf1b 100644 --- a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java @@ -11,10 +11,13 @@ import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; import static org.awaitility.Awaitility.fieldIn; import static org.awaitility.Awaitility.given; +import static org.awaitility.Awaitility.setDefaultPollDelay; +import static org.awaitility.Awaitility.setDefaultPollInterval; +import static org.awaitility.Awaitility.setDefaultTimeout; import static org.awaitility.proxy.AwaitilityClassProxy.to; import static org.hamcrest.Matchers.equalTo; -public class AsyncServiceUnitTest { +public class AsyncServiceLongRunningUnitTest { private AsyncService asyncService; @Before @@ -41,9 +44,9 @@ public class AsyncServiceUnitTest { @Test public void givenAsyncService_whenInitialize_thenInitOccurs_withDefualts() { - Awaitility.setDefaultPollInterval(10, TimeUnit.MILLISECONDS); - Awaitility.setDefaultPollDelay(Duration.ZERO); - Awaitility.setDefaultTimeout(Duration.ONE_MINUTE); + setDefaultPollInterval(10, TimeUnit.MILLISECONDS); + setDefaultPollDelay(Duration.ZERO); + setDefaultTimeout(Duration.ONE_MINUTE); asyncService.initialize(); await().until(asyncService::isInitialized); diff --git a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueTest.java b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java similarity index 96% rename from libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueTest.java rename to libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java index e64aaed544..9c0a0ac910 100644 --- a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueTest.java +++ b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java @@ -13,7 +13,7 @@ import net.openhft.chronicle.ChronicleQueueBuilder; import net.openhft.chronicle.ExcerptTailer; import net.openhft.chronicle.tools.ChronicleTools; -public class ChronicleQueueTest { +public class ChronicleQueueIntegrationTest { @Test public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException { diff --git a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java similarity index 98% rename from libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java rename to libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java index e208add3c8..5ecd4442d8 100644 --- a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java @@ -11,7 +11,7 @@ import java.util.stream.LongStream; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; -public class HLLUnitTest { +public class HLLLongRunningUnitTest { @Test public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() { From dc867672e9441d9d3c4c67b77dd78566c8321b57 Mon Sep 17 00:00:00 2001 From: lor6 Date: Tue, 22 Aug 2017 14:22:49 +0300 Subject: [PATCH 25/33] logback example app (#2354) --- guest/logback-example/pom.xml | 41 +++++ .../stackify/logging/IgnoreLoggerFilter.java | 28 ++++ .../java/com/stackify/models/Employee.java | 43 +++++ .../stackify/services/EmployeeService.java | 11 ++ .../src/main/resources/application.properties | 1 + .../src/main/resources/logback.xml | 151 ++++++++++++++++++ .../services/EmployeeServiceTest.java | 74 +++++++++ 7 files changed, 349 insertions(+) create mode 100644 guest/logback-example/pom.xml create mode 100644 guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java create mode 100644 guest/logback-example/src/main/java/com/stackify/models/Employee.java create mode 100644 guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java create mode 100644 guest/logback-example/src/main/resources/application.properties create mode 100644 guest/logback-example/src/main/resources/logback.xml create mode 100644 guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java diff --git a/guest/logback-example/pom.xml b/guest/logback-example/pom.xml new file mode 100644 index 0000000000..9d88c94197 --- /dev/null +++ b/guest/logback-example/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + com.stackify + logback-example + 0.0.1-SNAPSHOT + + + + ch.qos.logback + logback-classic + 1.2.3 + + + + junit + junit + 4.12 + + + + org.codehaus.janino + janino + 3.0.7 + + + + + + + + maven-compiler-plugin + 3.5 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java b/guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java new file mode 100644 index 0000000000..c0eb414588 --- /dev/null +++ b/guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java @@ -0,0 +1,28 @@ +package com.stackify.logging; + +import org.slf4j.Marker; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.turbo.TurboFilter; +import ch.qos.logback.core.spi.FilterReply; + +public class IgnoreLoggerFilter extends TurboFilter { + + private String loggerName; + + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + if (loggerName == null) { + return FilterReply.NEUTRAL; + } else if (loggerName.equals(logger.getName())) { + return FilterReply.DENY; + } else + return FilterReply.NEUTRAL; + } + + public void setLoggerName(String loggerName) { + this.loggerName = loggerName; + } + +} diff --git a/guest/logback-example/src/main/java/com/stackify/models/Employee.java b/guest/logback-example/src/main/java/com/stackify/models/Employee.java new file mode 100644 index 0000000000..1d040b372b --- /dev/null +++ b/guest/logback-example/src/main/java/com/stackify/models/Employee.java @@ -0,0 +1,43 @@ +package com.stackify.models; + +public class Employee { + + private String email; + private String name; + + private double salary; + + public Employee() { + } + + public Employee(String email, String name, double salary) { + this.email = email; + this.name = name; + this.salary = salary; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java b/guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java new file mode 100644 index 0000000000..1795101f40 --- /dev/null +++ b/guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java @@ -0,0 +1,11 @@ +package com.stackify.services; + +import com.stackify.models.Employee; + +public class EmployeeService { + + public double calculateBonus(Employee user) { + return 0.1 * user.getSalary(); + } + +} diff --git a/guest/logback-example/src/main/resources/application.properties b/guest/logback-example/src/main/resources/application.properties new file mode 100644 index 0000000000..601f964ff3 --- /dev/null +++ b/guest/logback-example/src/main/resources/application.properties @@ -0,0 +1 @@ +env=dev \ No newline at end of file diff --git a/guest/logback-example/src/main/resources/logback.xml b/guest/logback-example/src/main/resources/logback.xml new file mode 100644 index 0000000000..d8ec24c7c3 --- /dev/null +++ b/guest/logback-example/src/main/resources/logback.xml @@ -0,0 +1,151 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + System.out + + + + + + + + + log-%d{yyyy-MM-dd}.log + 30 + 3GB + + + 3MB + + + %d [%thread] %-5level %logger{50} - %msg%n + + + + + + userRole + ANONYMOUS + + + + ${userRole}.log + + %d [%thread] %level %mdc %logger{50} - %msg%n + + + + + + + + + %d %green([%thread]) %highlight(%level) %logger{50} - %msg%n + + + + + + + %thread%level%logger%msg + + + log.html + + + + + + ERROR + ACCEPT + DENY + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + System.err + + + + + WARN + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + return (level > DEBUG && message.toLowerCase().contains("employee")); + + DENY + NEUTRAL + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + 2 + + + + ignoredColorLogger + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java new file mode 100644 index 0000000000..187b27e1df --- /dev/null +++ b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java @@ -0,0 +1,74 @@ +package com.stackify.services; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +import com.stackify.models.Employee; + +import ch.qos.logback.classic.Level; + +public class EmployeeServiceTest { + private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + private EmployeeService employeeService = new EmployeeService(); + + @Test + public void testAppenders() { + Logger rollingFileLogger = LoggerFactory.getLogger("rollingFileLogger"); + rollingFileLogger.info("Testing rolling file logger"); + + MDC.put("userRole", "ADMIN"); + Logger siftingLogger = LoggerFactory.getLogger("roleSiftingLogger"); + siftingLogger.info("Admin Action"); + } + + @Test + public void testLayouts() { + Logger htmlLogger = LoggerFactory.getLogger("htmlLogger"); + htmlLogger.error("Employee Information Update Failed"); + htmlLogger.info("New Account Created"); + + Logger colorLogger = LoggerFactory.getLogger("colorLogger"); + colorLogger.error("Employee Information Update Failed"); + colorLogger.info("New Account Created"); + } + + @Test + public void testLogLevel() { + ch.qos.logback.classic.Logger rollingFileLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("rollingFileLogger"); + rollingFileLogger.setLevel(Level.DEBUG); + rollingFileLogger.debug("Testing Log Level"); + } + + @Test + public void testParameter() { + Employee employee = new Employee("john@gmail.com", "John", 2000); + if (logger.isDebugEnabled()) { + logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee)); + } + logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee)); + } + + @Test + public void testFilters() { + Logger levelFilterLogger = LoggerFactory.getLogger("levelFilterLogger"); + levelFilterLogger.error("Employee Information Update Failed"); + Logger thresholdFilterLogger = LoggerFactory.getLogger("thresholdFilterLogger"); + thresholdFilterLogger.trace("Employee record inserted"); + Logger evaluatorFilterLogger = LoggerFactory.getLogger("evaluatorFilterLogger"); + evaluatorFilterLogger.debug("Employee account deactivated"); + } + + @Test + public void testIgnoredLogger() { + Logger colorLogger = LoggerFactory.getLogger("ignoredColorLogger"); + colorLogger.info("Ignored Log Message"); + } + + @Test + public void testConditionalConfiguration() { + logger.trace("Employee record updated"); + } +} From ccba3de76531e1b01ab10156dd4ba6247e360c74 Mon Sep 17 00:00:00 2001 From: Buddhini Samarakkody Date: Wed, 23 Aug 2017 06:22:06 +0530 Subject: [PATCH 26/33] Delete and add new test for BAEL-698 (#2479) * Delete HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java * Add new test class * Rename test methods --- ...yToManyAnnotationMainIntegrationTest.java} | 57 ++++++++----------- 1 file changed, 25 insertions(+), 32 deletions(-) rename spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/{HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java => HibernateManyToManyAnnotationMainIntegrationTest.java} (50%) diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java similarity index 50% rename from spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java rename to spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java index 5308134fac..2ec1246961 100644 --- a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java @@ -12,17 +12,16 @@ 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 { +public class HibernateManyToManyAnnotationMainIntegrationTest { private static SessionFactory sessionFactory; private Session session; - @BeforeClass public static void beforeTests() { sessionFactory = HibernateUtil.getSessionFactory(); @@ -34,45 +33,39 @@ public class HibernateManyToManyAnnotationXMLConfigMainIntegrationTest { session.beginTransaction(); } - @Test - public void givenSession_checkIfDatabaseIsPopulated() { - Employee employee1 = new Employee("Peter", "Oven"); + public void givenData_whenInsert_thenCreatesMtoMrelationship() { + String[] employeeData = { "Peter Oven", "Allan Norman" }; + String[] projectData = { "IT Project", "Networking Project" }; 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); + for (String proj : projectData) { + projects.add(new Project(proj)); + } + + for (String emp : employeeData) { + Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]); + assertEquals(0, employee.getProjects().size()); + employee.setProjects(projects); + assertNotNull(employee); + session.persist(employee); + } + } + + @Test + public void givenSession_whenRead_thenReturnsMtoMdata() { @SuppressWarnings("unchecked") List employeeList = session.createQuery("FROM Employee").list(); assertNotNull(employeeList); + for(Employee employee : employeeList) { + assertNotNull(employee.getProjects()); + } } - @After public void tearDown() { - session.getTransaction().commit(); + session.getTransaction() + .commit(); session.close(); } From 18b1334ff12d098265fa1af2a497bbd21cd217b9 Mon Sep 17 00:00:00 2001 From: lor6 Date: Wed, 23 Aug 2017 11:53:21 +0300 Subject: [PATCH 27/33] move reladomo ex to librarie-data (#2485) --- libraries-data/pom.xml | 126 ++++++++++++++++++ .../com/baeldung/reladomo/Department.java | 0 .../reladomo/DepartmentDatabaseObject.java | 0 .../com/baeldung/reladomo/DepartmentList.java | 0 .../java/com/baeldung/reladomo/Employee.java | 0 .../reladomo/EmployeeDatabaseObject.java | 0 .../com/baeldung/reladomo/EmployeeList.java | 0 .../reladomo/ReladomoApplication.java | 0 .../reladomo/ReladomoConnectionManager.java | 0 .../main/resources/ReladomoRuntimeConfig.xml | 0 .../main/resources/reladomo/Department.xml | 0 .../src/main/resources/reladomo/Employee.xml | 0 .../resources/reladomo/ReladomoClassList.xml | 0 .../com/baeldung/reladomo/ReladomoTest.java | 0 .../resources/reladomo/ReladomoTestConfig.xml | 0 .../src/test/resources/reladomo/test-data.txt | 0 libraries/pom.xml | 96 ------------- 17 files changed, 126 insertions(+), 96 deletions(-) rename {libraries => libraries-data}/src/main/java/com/baeldung/reladomo/Department.java (100%) rename {libraries => libraries-data}/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java (100%) rename {libraries => libraries-data}/src/main/java/com/baeldung/reladomo/DepartmentList.java (100%) rename {libraries => libraries-data}/src/main/java/com/baeldung/reladomo/Employee.java (100%) rename {libraries => libraries-data}/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java (100%) rename {libraries => libraries-data}/src/main/java/com/baeldung/reladomo/EmployeeList.java (100%) rename {libraries => libraries-data}/src/main/java/com/baeldung/reladomo/ReladomoApplication.java (100%) rename {libraries => libraries-data}/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java (100%) rename {libraries => libraries-data}/src/main/resources/ReladomoRuntimeConfig.xml (100%) rename {libraries => libraries-data}/src/main/resources/reladomo/Department.xml (100%) rename {libraries => libraries-data}/src/main/resources/reladomo/Employee.xml (100%) rename {libraries => libraries-data}/src/main/resources/reladomo/ReladomoClassList.xml (100%) rename {libraries => libraries-data}/src/test/java/com/baeldung/reladomo/ReladomoTest.java (100%) rename {libraries => libraries-data}/src/test/resources/reladomo/ReladomoTestConfig.xml (100%) rename {libraries => libraries-data}/src/test/resources/reladomo/test-data.txt (100%) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 94a9ca43f4..cae8a725a6 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -14,9 +14,135 @@ com.esotericsoftware kryo ${kryo.version} + + + com.h2database + h2 + ${h2.version} + + + junit + junit + ${junit.version} + test + + + com.goldmansachs.reladomo + reladomo + ${reladomo.version} + + + com.goldmansachs.reladomo + reladomo-test-util + ${reladomo.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + maven-antrun-plugin + 1.8 + + + generateMithra + generate-sources + + run + + + + + + + + + + + + + + + + + + com.goldmansachs.reladomo + reladomogen + ${reladomo.version} + + + + com.goldmansachs.reladomo + reladomo-gen-util + ${reladomo.version} + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/reladomo + + + + + add-resource + generate-resources + + add-resource + + + + + ${project.build.directory}/generated-db/ + + + + + + + + + + + 4.0.1 + 1.4.196 + 16.5.1 + 4.12 + 3.6.2 \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/reladomo/Department.java b/libraries-data/src/main/java/com/baeldung/reladomo/Department.java similarity index 100% rename from libraries/src/main/java/com/baeldung/reladomo/Department.java rename to libraries-data/src/main/java/com/baeldung/reladomo/Department.java diff --git a/libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java b/libraries-data/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java similarity index 100% rename from libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java rename to libraries-data/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java diff --git a/libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java b/libraries-data/src/main/java/com/baeldung/reladomo/DepartmentList.java similarity index 100% rename from libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java rename to libraries-data/src/main/java/com/baeldung/reladomo/DepartmentList.java diff --git a/libraries/src/main/java/com/baeldung/reladomo/Employee.java b/libraries-data/src/main/java/com/baeldung/reladomo/Employee.java similarity index 100% rename from libraries/src/main/java/com/baeldung/reladomo/Employee.java rename to libraries-data/src/main/java/com/baeldung/reladomo/Employee.java diff --git a/libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java b/libraries-data/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java similarity index 100% rename from libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java rename to libraries-data/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java diff --git a/libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java b/libraries-data/src/main/java/com/baeldung/reladomo/EmployeeList.java similarity index 100% rename from libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java rename to libraries-data/src/main/java/com/baeldung/reladomo/EmployeeList.java diff --git a/libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java b/libraries-data/src/main/java/com/baeldung/reladomo/ReladomoApplication.java similarity index 100% rename from libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java rename to libraries-data/src/main/java/com/baeldung/reladomo/ReladomoApplication.java diff --git a/libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java b/libraries-data/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java similarity index 100% rename from libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java rename to libraries-data/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java diff --git a/libraries/src/main/resources/ReladomoRuntimeConfig.xml b/libraries-data/src/main/resources/ReladomoRuntimeConfig.xml similarity index 100% rename from libraries/src/main/resources/ReladomoRuntimeConfig.xml rename to libraries-data/src/main/resources/ReladomoRuntimeConfig.xml diff --git a/libraries/src/main/resources/reladomo/Department.xml b/libraries-data/src/main/resources/reladomo/Department.xml similarity index 100% rename from libraries/src/main/resources/reladomo/Department.xml rename to libraries-data/src/main/resources/reladomo/Department.xml diff --git a/libraries/src/main/resources/reladomo/Employee.xml b/libraries-data/src/main/resources/reladomo/Employee.xml similarity index 100% rename from libraries/src/main/resources/reladomo/Employee.xml rename to libraries-data/src/main/resources/reladomo/Employee.xml diff --git a/libraries/src/main/resources/reladomo/ReladomoClassList.xml b/libraries-data/src/main/resources/reladomo/ReladomoClassList.xml similarity index 100% rename from libraries/src/main/resources/reladomo/ReladomoClassList.xml rename to libraries-data/src/main/resources/reladomo/ReladomoClassList.xml diff --git a/libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java b/libraries-data/src/test/java/com/baeldung/reladomo/ReladomoTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java rename to libraries-data/src/test/java/com/baeldung/reladomo/ReladomoTest.java diff --git a/libraries/src/test/resources/reladomo/ReladomoTestConfig.xml b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml similarity index 100% rename from libraries/src/test/resources/reladomo/ReladomoTestConfig.xml rename to libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml diff --git a/libraries/src/test/resources/reladomo/test-data.txt b/libraries-data/src/test/resources/reladomo/test-data.txt similarity index 100% rename from libraries/src/test/resources/reladomo/test-data.txt rename to libraries-data/src/test/resources/reladomo/test-data.txt diff --git a/libraries/pom.xml b/libraries/pom.xml index e9603b1453..6d1098246e 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -106,91 +106,6 @@ - - - maven-antrun-plugin - 1.8 - - - generateMithra - generate-sources - - run - - - - - - - - - - - - - - - - - - com.goldmansachs.reladomo - reladomogen - ${reladomo.version} - - - - com.goldmansachs.reladomo - reladomo-gen-util - ${reladomo.version} - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 3.0.0 - - - add-source - generate-sources - - add-source - - - - ${project.build.directory}/generated-sources/reladomo - - - - - add-resource - generate-resources - - add-resource - - - - - ${project.build.directory}/generated-db/ - - - - - - - - @@ -583,16 +498,6 @@ gt-swing ${geotools.version} - - com.goldmansachs.reladomo - reladomo - ${reladomo.version} - - - com.goldmansachs.reladomo - reladomo-test-util - ${reladomo.version} - @@ -659,6 +564,5 @@ 0.6.5 0.9.0 15.2 - 16.5.1 \ No newline at end of file From b6674f68dc1ae936ed46cabd251915ccb99c45b7 Mon Sep 17 00:00:00 2001 From: ahmetcetin39 <30636222+ahmetcetin39@users.noreply.github.com> Date: Wed, 23 Aug 2017 16:37:50 +0300 Subject: [PATCH 28/33] BAEL-1070 - CharSequence vs String in Java (#2451) * Different types of bean injection classes are added. * JUnit Tests for Zoo and Forest Class * Necessary dependency is added to pom.xml * Updated pom.xml Carried dependency to into another dependency tag. * dependency added. * dependency is carried. * dependency is added. * A test dependency is added. * dependency is changed. * Dependency is changed. * Test classes are changed and moved. * test correction * correction * String vs CharSequence * unnecesseray files are deleted. * correction * Assert statemenet is changed from java to junit * Assert is changed. * changed the name of the test methods. --- .../string/CharSequenceVsStringUnitTest.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java b/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java new file mode 100644 index 0000000000..1378b5d876 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.string; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class CharSequenceVsStringUnitTest { + + @Test + public void givenUsingString_whenInstantiatingString_thenWrong() { + CharSequence firstString = "bealdung"; + String secondString = "baeldung"; + + assertNotEquals(firstString, secondString); + } + + @Test + public void givenIdenticalCharSequences_whenCastToString_thenEqual() { + CharSequence charSequence1 = "baeldung_1"; + CharSequence charSequence2 = "baeldung_2"; + + assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) > 0); + } + + @Test + public void givenString_whenAppended_thenUnmodified() { + String test = "a"; + int firstAddressOfTest = System.identityHashCode(test); + test += "b"; + int secondAddressOfTest = System.identityHashCode(test); + + assertEquals(firstAddressOfTest, secondAddressOfTest); + } + + @Test + public void givenStringBuilder_whenAppended_thenModified() { + StringBuilder test = new StringBuilder(); + test.append("a"); + int firstAddressOfTest = System.identityHashCode(test); + test.append("b"); + int secondAddressOfTest = System.identityHashCode(test); + + assertEquals(firstAddressOfTest, secondAddressOfTest); + } +} From 621d0d2c621cdc3badca795bfb92928cd708d11c Mon Sep 17 00:00:00 2001 From: Yasin Date: Wed, 23 Aug 2017 23:30:25 +0530 Subject: [PATCH 29/33] BAEL-1073 Converting a List to String in Java (#2489) --- .../org/baeldung/java/lists/ListToSTring.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/lists/ListToSTring.java diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListToSTring.java b/core-java/src/test/java/org/baeldung/java/lists/ListToSTring.java new file mode 100644 index 0000000000..3fc26bcb51 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/lists/ListToSTring.java @@ -0,0 +1,31 @@ +package org.baeldung.java.lists; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +public class ListToSTring { + + @Test + public void whenListToString_thenPrintDefault() { + List intLIst = Arrays.asList(1, 2, 3); + System.out.println(intLIst); + } + + @Test + public void whenCollectorsJoining_thenPrintCustom() { + List intList = Arrays.asList(1, 2, 3); + System.out.println(intList.stream() + .map(n -> String.valueOf(n)) + .collect(Collectors.joining("-", "{", "}"))); + } + + @Test + public void whenStringUtilsJoin_thenPrintCustom() { + List intList = Arrays.asList(1, 2, 3); + System.out.println(StringUtils.join(intList, "|")); + } +} From 15666e8ed4bd33c1a8ea399bd3bbf2f82b74f546 Mon Sep 17 00:00:00 2001 From: Shivang Sarawagi Date: Wed, 23 Aug 2017 23:44:49 +0530 Subject: [PATCH 30/33] Binary Search Algorithm (#2452) * Binary search * deleting previous files * BinarySearch along with the test case --- .../com/baeldung/algorithms/BinarySearch.java | 37 ++++++++++++++++--- .../java/algorithms/BinarySearchTest.java | 33 +++++++++++++++-- 2 files changed, 62 insertions(+), 8 deletions(-) diff --git a/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java index be4a9e578a..86522950ef 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java @@ -1,11 +1,11 @@ +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + public class BinarySearch { - public int runBinarySearch() { - int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; - int key = 6; + public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) { - int low = 0; - int high = sortedArray.length - 1; int index = Integer.MAX_VALUE; while (low <= high) { @@ -23,4 +23,31 @@ public class BinarySearch { } return index; } + + public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) { + + int middle = (low + high) / 2; + if (high < low) { + return -1; + } + + if (key == sortedArray[middle]) { + return middle; + } else if (key < sortedArray[middle]) { + return runBinarySearchRecursively(sortedArray, key, low, middle - 1); + } else { + return runBinarySearchRecursively(sortedArray, key, middle + 1, high); + } + } + + public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) { + int index = Arrays.binarySearch(sortedArray, key); + return index; + } + + public int runBinarySearchUsingJavaCollections(List sortedList, Integer key) { + int index = Collections.binarySearch(sortedList, key); + return index; + } + } diff --git a/algorithms/src/test/java/algorithms/BinarySearchTest.java b/algorithms/src/test/java/algorithms/BinarySearchTest.java index d53b074cc4..3611ec8e49 100644 --- a/algorithms/src/test/java/algorithms/BinarySearchTest.java +++ b/algorithms/src/test/java/algorithms/BinarySearchTest.java @@ -1,14 +1,41 @@ +import java.util.Arrays; +import java.util.List; + import org.junit.Assert; import org.junit.Test; public class BinarySearchTest { + int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; + int key = 6; + int expectedIndexForSearchKey = 7; + int low = 0; + int high = sortedArray.length - 1; + List sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9); + @Test - public void givenASortedArrayOfIntegers_whenBinarySearchRunForANumber_thenGetIndexOfTheNumber() { + public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() { BinarySearch binSearch = new BinarySearch(); - int expectedIndexForSearchKey = 7; - Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearch()); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high)); } + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high)); + } + + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key)); + } + + @Test + public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key)); + } + } From 74e67d6ce9b520ca379a60b592d13a484b31ce07 Mon Sep 17 00:00:00 2001 From: Buddhini Samarakkody Date: Thu, 24 Aug 2017 07:41:01 +0530 Subject: [PATCH 31/33] Fix the test method (#2491) * Remove assertion before persist in test1 * Add back assertion after persist --- .../HibernateManyToManyAnnotationMainIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java index 2ec1246961..9a536a0f80 100644 --- a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java @@ -47,8 +47,8 @@ public class HibernateManyToManyAnnotationMainIntegrationTest { Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]); assertEquals(0, employee.getProjects().size()); employee.setProjects(projects); - assertNotNull(employee); session.persist(employee); + assertNotNull(employee); } } From 1cba1b043cadbd12f499e34d36a94ef902df1cea Mon Sep 17 00:00:00 2001 From: eugenp Date: Thu, 24 Aug 2017 13:11:52 +0300 Subject: [PATCH 32/33] minor formatting cleanup --- .../blockingqueue/NumbersProducer.java | 6 +- .../concurrent/delayqueue/DelayObject.java | 5 +- .../adapter/LuxuryCarsSpeed.java | 4 +- .../adapter/LuxuryCarsSpeedAdapter.java | 2 + .../baeldung/designpatterns/bridge/Blue.java | 2 +- .../decorator/DecoratorPatternDriver.java | 12 +- .../proxy/ExpensiveObjectImpl.java | 6 +- .../forkjoin/CustomRecursiveAction.java | 3 +- .../com/baeldung/java/reflection/Greeter.java | 4 +- .../baeldung/map/iteration/MapIteration.java | 7 +- .../com/baeldung/maths/BigIntegerImpl.java | 2 +- .../cookies/PersistentCookieStore.java | 3 +- .../com/baeldung/printscreen/Screenshot.java | 3 +- .../java/com/baeldung/uuid/UUIDGenerator.java | 38 ++- .../CompletableFutureLongRunningUnitTest.java | 39 +-- .../datetime/UseLocalDateTimeUnitTest.java | 6 +- .../datetime/UseLocalDateUnitTest.java | 15 +- .../FunctionalInterfaceUnitTest.java | 11 +- ...oncurrentMapAggregateStatusManualTest.java | 6 +- ...ncurretMapMemoryConsistencyManualTest.java | 24 +- .../Java8GroupingByCollectorUnitTest.java | 244 +++++++----------- .../baeldung/java8/Java8MapAndFlatMap.java | 20 +- .../java8/JavaFolderSizeUnitTest.java | 15 +- .../comparator/Java8ComparatorUnitTest.java | 74 +++--- .../java8/optional/OptionalUnitTest.java | 54 ++-- .../FlattenNestedListUnitTest.java | 4 +- .../java/com/baeldung/maths/RoundTest.java | 24 +- .../baeldung/socket/EchoIntegrationTest.java | 3 +- .../socket/GreetServerIntegrationTest.java | 3 +- .../org/baeldung/java/JavaIoUnitTest.java | 9 +- .../org/baeldung/java/JavaRandomUnitTest.java | 16 +- .../java/JavaTimerLongRunningUnitTest.java | 4 +- .../org/baeldung/java/sorting/Employee.java | 11 +- .../java/sorting/JavaSortingUnitTest.java | 6 +- .../BookControllerFeignClientBuilder.java | 8 +- .../feign/clients/BookClientLiveTest.java | 14 +- .../deserialization/jacksoninject/Author.java | 3 +- .../deserialization/jacksoninject/Person.java | 2 +- .../deserialization/jsoncreator/Author.java | 5 +- .../deserialization/jsondeserialize/Book.java | 3 +- .../CustomDateDeserializer.java | 6 +- .../deserialization/jsondeserialize/Item.java | 3 +- .../deserialization/jsonsetter/Author.java | 3 +- .../com/baeldung/jackson/domain/Book.java | 2 +- .../com/baeldung/jackson/domain/Course.java | 4 +- .../com/baeldung/jackson/domain/Item.java | 3 +- .../com/baeldung/jackson/domain/Person.java | 3 +- .../jackson/entities/ClassWithAMap.java | 20 +- .../com/baeldung/jackson/entities/MyPair.java | 128 ++++----- .../com/baeldung/jackson/format/User.java | 17 +- .../jackson/inclusion/jsonignore/Person.java | 3 +- .../jsonignoreproperties/Course.java | 6 +- .../inheritance/ItemIdAddedToUser.java | 5 +- .../inheritance/ItemIdRemovedFromUser.java | 5 +- .../jackson/miscellaneous/custom/Course.java | 4 +- .../custom/CustomCourseAnnotation.java | 4 +- .../jackson/miscellaneous/custom/Item.java | 3 +- .../jackson/miscellaneous/disable/Author.java | 2 +- .../baeldung/jackson/polymorphism/Order.java | 8 +- .../serialization/ActorJacksonSerializer.java | 7 +- .../serialization/MyPairDeserializer.java | 9 +- .../serialization/MyPairSerializer.java | 16 +- .../serialization/jsongetter/Author.java | 1 - .../jsonpropertyorder/Author.java | 3 +- .../serialization/jsonserialize/Book.java | 3 +- .../jsonserialize/CustomDateSerializer.java | 6 +- .../serialization/jsonserialize/Item.java | 3 +- .../serialization/jsonvalue/Course.java | 4 +- .../extra/ExtraAnnotationUnitTest.java | 12 +- .../extra/IdentityReferenceBeans.java | 3 +- .../bidirection/CustomListSerializer.java | 1 + .../date/CustomLocalDateTimeSerializer.java | 1 - .../deserialization/ItemDeserializer.java | 6 +- .../ItemDeserializerOnClass.java | 6 +- .../JacksonMapDeserializeUnitTest.java | 65 +++-- .../jacksoninject/JacksonInjectUnitTest.java | 4 +- .../jsonanysetter/JsonAnySetterUnitTest.java | 27 +- .../jsoncreator/JsonCreatorUnitTest.java | 9 +- .../JsonDeserializeUnitTest.java | 3 +- .../jsonsetter/JsonSetterUnitTest.java | 7 +- .../jackson/dynamicIgnore/Address.java | 1 - .../jackson/dynamicIgnore/Hidable.java | 1 - .../jackson/dynamicIgnore/Person.java | 3 +- .../jackson/format/JsonFormatUnitTest.java | 16 +- .../jsonfilter/JsonFilterUnitTest.java | 6 +- .../jackson/general/jsonformat/Book.java | 4 +- .../jsonformat/JsonFormatUnitTest.java | 5 +- .../general/jsonidentityinfo/Author.java | 4 +- .../general/jsonidentityinfo/Course.java | 5 +- .../general/jsonidentityinfo/Item.java | 7 +- .../general/jsonidentityinfo/Person.java | 3 +- .../jackson/general/jsonproperty/Item.java | 3 +- .../jsonproperty/JsonPropertyUnitTest.java | 9 +- .../jsonunwrapped/JsonUnwrappedUnitTest.java | 1 - .../general/jsonview/JsonViewUnitTest.java | 7 +- .../jackson/general/reference/Course.java | 5 +- .../jackson/general/reference/Item.java | 3 +- .../jackson/general/reference/Person.java | 3 +- .../general/reference/ReferenceUnitTest.java | 2 +- .../JsonAutoDetectUnitTest.java | 2 +- .../jsoninclude/JsonIncludeUnitTest.java | 1 - .../ItemIdRemovedFromUserUnitTest.java | 12 +- .../inheritance/SubTypeHandlingUnitTest.java | 6 +- .../TypeInfoInclusionUnitTest.java | 12 +- .../jackson/node/ExampleStructure.java | 3 +- .../jackson/node/NodeOperationUnitTest.java | 36 ++- .../objectmapper/CustomCarDeserializer.java | 2 - .../objectmapper/CustomCarSerializer.java | 6 +- .../JavaReadWriteJsonExampleUnitTest.java | 3 +- ...izationDeserializationFeatureUnitTest.java | 2 +- .../polymorphism/PolymorphismUnitTest.java | 8 +- .../sandbox/JacksonPrettyPrintUnitTest.java | 6 +- .../jackson/sandbox/SandboxUnitTest.java | 5 +- .../JacksonMapSerializeUnitTest.java | 70 +++-- .../JacksonSerializeUnitTest.java | 7 +- .../jsonrawvalue/JsonRawValueUnitTest.java | 1 - .../JacksonStreamingAPIUnitTest.java | 19 +- .../test/JacksonAnnotationUnitTest.java | 31 ++- .../JacksonBidirectionRelationUnitTest.java | 12 +- ...ksonCollectionDeserializationUnitTest.java | 3 +- .../jackson/test/JacksonDateUnitTest.java | 6 +- .../test/JacksonExceptionsUnitTest.java | 56 ++-- .../jackson/test/JacksonJsonViewUnitTest.java | 16 +- .../JacksonSerializationIgnoreUnitTest.java | 15 +- .../try1/RestLoaderRequestDeserializer.java | 6 +- .../xml/XMLSerializeDeserializeUnitTest.java | 3 +- .../SpringBootAnnotatedApp.java | 2 +- .../SpringBootPlainApp.java | 2 +- .../components/AttrListener.java | 5 +- .../components/EchoServlet.java | 5 +- .../components/HelloFilter.java | 5 +- .../components/HelloServlet.java | 10 +- .../MySQLAutoconfiguration.java | 16 +- .../example/MyUserRepository.java | 4 +- .../baeldung/displayallbeans/Application.java | 6 +- .../controller/FooController.java | 6 +- .../displayallbeans/service/FooService.java | 10 +- .../config/PersistenceConfig.java | 5 +- .../FailureAnalyzerApplication.java | 2 +- ...yBeanNotOfRequiredTypeFailureAnalyzer.java | 16 +- .../com/baeldung/git/CommitIdApplication.java | 2 +- .../graphql/GraphqlConfiguration.java | 6 +- .../java/com/baeldung/graphql/Mutation.java | 3 +- .../InternationalizationApp.java | 2 +- .../src/main/java/com/baeldung/intro/App.java | 8 +- .../intro/controller/HomeController.java | 6 +- .../baeldung/servlets/ApplicationMain.java | 2 +- .../configuration/WebMvcConfigure.java | 7 +- .../servlets/props/PropertySourcesLoader.java | 3 +- .../servlets/javaee/AnnotationServlet.java | 7 +- .../baeldung/toggle/EmployeeRepository.java | 2 +- .../java/com/baeldung/toggle/MyFeatures.java | 10 +- .../com/baeldung/utils/UtilsApplication.java | 12 +- .../utils/controller/UtilsController.java | 66 ++--- .../webjar/WebjarsdemoApplication.java | 2 +- .../main/java/org/baeldung/Application.java | 2 +- .../org/baeldung/boot/DemoApplication.java | 2 +- .../baeldung/boot/components/FooService.java | 4 +- .../boot/exceptions/CommonException.java | 4 +- .../boot/exceptions/FooNotFoundException.java | 4 +- .../java/org/baeldung/boot/model/Foo.java | 1 - .../baeldung/boot/service/FooController.java | 2 +- .../controller/GenericEntityController.java | 18 +- .../org/baeldung/endpoints/MyHealthCheck.java | 8 +- .../jsoncomponent/UserCombinedSerializer.java | 6 +- .../jsoncomponent/UserJsonDeserializer.java | 3 +- .../jsoncomponent/UserJsonSerializer.java | 3 +- .../baeldung/main/SpringBootApplication.java | 2 +- .../monitor/jmx/MonitoringConfig.java | 3 +- .../baeldung/service/LoginServiceImpl.java | 3 +- .../session/exception/Application.java | 2 +- .../repository/FooRepositoryImpl.java | 6 +- .../baeldung/websocket/client/Message.java | 3 +- .../client/MyStompSessionHandler.java | 14 +- .../websocket/client/StompClient.java | 4 +- ...otWithServletComponentIntegrationTest.java | 10 +- ...ithoutServletComponentIntegrationTest.java | 4 +- .../AutoconfigurationIntegrationTest.java | 2 +- .../DisplayBeanIntegrationTest.java | 18 +- .../java/com/baeldung/intro/AppLiveTest.java | 16 +- .../toggle/ToggleIntegrationTest.java | 9 +- .../utils/UtilsControllerIntegrationTest.java | 8 +- .../MyStompSessionHandlerIntegrationTest.java | 7 +- .../SpringBootApplicationIntegrationTest.java | 34 ++- .../SpringBootMailIntegrationTest.java | 8 +- .../EmployeeControllerIntegrationTest.java | 16 +- .../EmployeeRepositoryIntegrationTest.java | 4 +- ...EmployeeRestControllerIntegrationTest.java | 16 +- .../EmployeeServiceImplIntegrationTest.java | 25 +- .../DetailsServiceClientIntegrationTest.java | 3 +- .../UserJsonSerializerIntegrationTest.java | 1 - .../security/CustomAccessDeniedHandler.java | 2 +- .../baeldung/spring/SecSecurityConfig.java | 4 +- .../RedirectionSecurityIntegrationTest.java | 57 ++-- 194 files changed, 1147 insertions(+), 1005 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java index 9dcd0a3e47..b301e994d5 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java +++ b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java @@ -19,13 +19,15 @@ public class NumbersProducer implements Runnable { try { generateNumbers(); } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + Thread.currentThread() + .interrupt(); } } private void generateNumbers() throws InterruptedException { for (int i = 0; i < 100; i++) { - numbersQueue.put(ThreadLocalRandom.current().nextInt(100)); + numbersQueue.put(ThreadLocalRandom.current() + .nextInt(100)); } for (int j = 0; j < poisonPillPerProducer; j++) { numbersQueue.put(poisonPill); diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java index 5f72758e71..312eb929ed 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java +++ b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java @@ -27,9 +27,6 @@ public class DelayObject implements Delayed { @Override public String toString() { - return "{" + - "data='" + data + '\'' + - ", startTime=" + startTime + - '}'; + return "{" + "data='" + data + '\'' + ", startTime=" + startTime + '}'; } } \ No newline at end of file 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 index 278329b994..0b97b8228c 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java @@ -4,11 +4,11 @@ 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 index 84f7be2729..d9255f0910 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java @@ -2,6 +2,8 @@ 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/bridge/Blue.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java index 97a4a9508c..ed3f75b4a1 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java @@ -5,7 +5,7 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG; public class Blue implements Color { @Override - public void fillColor() { + public void fillColor() { LOG.info("Color : Blue"); } 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 index f70991da6b..70b4f801cd 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java @@ -5,16 +5,14 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG; public class DecoratorPatternDriver { public static void main(String[] args) { - //christmas tree with just one Garland + // 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())) - ); + + // 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/proxy/ExpensiveObjectImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java index 7014d3811c..de31e22b30 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java @@ -7,14 +7,14 @@ 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/forkjoin/CustomRecursiveAction.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java index ae79787570..ebe59e33b1 100644 --- a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java @@ -43,6 +43,7 @@ public class CustomRecursiveAction extends RecursiveAction { private void processing(String work) { String result = work.toUpperCase(); - logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName()); + logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread() + .getName()); } } diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java index ede269528a..57aefdd169 100644 --- a/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java +++ b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java @@ -5,6 +5,6 @@ import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Greeter { - - public String greet() default ""; + + public String greet() default ""; } diff --git a/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java index 2bc078cdb0..b0c32e1487 100644 --- a/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java +++ b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java @@ -44,7 +44,8 @@ public class MapIteration { } public void iterateUsingIteratorAndEntry(Map map) { - Iterator> iterator = map.entrySet().iterator(); + Iterator> iterator = map.entrySet() + .iterator(); while (iterator.hasNext()) { Map.Entry pair = iterator.next(); System.out.println(pair.getKey() + ":" + pair.getValue()); @@ -58,7 +59,9 @@ public class MapIteration { } public void iterateUsingStreamAPI(Map map) { - map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); + map.entrySet() + .stream() + .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); } public void iterateKeys(Map map) { diff --git a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java index dc509429f9..9f46345e04 100644 --- a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java +++ b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java @@ -8,7 +8,7 @@ public class BigIntegerImpl { BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476"); BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476"); - + BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda); } diff --git a/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java index 5d30491cfe..4f34972b1e 100644 --- a/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java +++ b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java @@ -9,7 +9,8 @@ public class PersistentCookieStore implements CookieStore, Runnable { public PersistentCookieStore() { store = new CookieManager().getCookieStore(); // deserialize cookies into store - Runtime.getRuntime().addShutdownHook(new Thread(this)); + Runtime.getRuntime() + .addShutdownHook(new Thread(this)); } @Override diff --git a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java index 7f87b47476..11716b961d 100644 --- a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java +++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java @@ -14,7 +14,8 @@ public class Screenshot { } public void getScreenshot(int timeToWait) throws Exception { - Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); + Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit() + .getScreenSize()); Robot robot = new Robot(); BufferedImage img = robot.createScreenCapture(rectangle); ImageIO.write(img, "jpg", new File(path)); diff --git a/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java b/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java index 23baf5d5b4..dcf186de93 100644 --- a/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java +++ b/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java @@ -6,16 +6,16 @@ import java.security.NoSuchAlgorithmException; import java.util.UUID; public class UUIDGenerator { - + /** * These are predefined UUID for name spaces */ - private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8"; - private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); + private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); public static void main(String[] args) { try { @@ -35,7 +35,7 @@ public class UUIDGenerator { UUID uuid = UUID.randomUUID(); return uuid; } - + /** * Type 3 UUID Generation * @@ -47,7 +47,7 @@ public class UUIDGenerator { UUID uuid = UUID.nameUUIDFromBytes(bytes); return uuid; } - + /** * Type 5 UUID Generation * @@ -59,8 +59,7 @@ public class UUIDGenerator { UUID uuid = type5UUIDFromBytes(bytes); return uuid; } - - + public static UUID type5UUIDFromBytes(byte[] name) { MessageDigest md; try { @@ -69,27 +68,26 @@ public class UUIDGenerator { throw new InternalError("MD5 not supported", nsae); } byte[] bytes = md.digest(name); - bytes[6] &= 0x0f; /* clear version */ - bytes[6] |= 0x50; /* set to version 5 */ - bytes[8] &= 0x3f; /* clear variant */ - bytes[8] |= 0x80; /* set to IETF variant */ + bytes[6] &= 0x0f; /* clear version */ + bytes[6] |= 0x50; /* set to version 5 */ + bytes[8] &= 0x3f; /* clear variant */ + bytes[8] |= 0x80; /* set to IETF variant */ return constructType5UUID(bytes); } - + private static UUID constructType5UUID(byte[] data) { long msb = 0; long lsb = 0; assert data.length == 16 : "data must be 16 bytes in length"; - - for (int i=0; i<8; i++) + + for (int i = 0; i < 8; i++) msb = (msb << 8) | (data[i] & 0xff); - - for (int i=8; i<16; i++) + + for (int i = 8; i < 16; i++) lsb = (lsb << 8) | (data[i] & 0xff); return new UUID(msb, lsb); } - /** * Unique Keys Generation Using Message Digest and Type 4 UUID * diff --git a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java index 0c3a13d176..0a6d94e126 100644 --- a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java +++ b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java @@ -15,7 +15,6 @@ public class CompletableFutureLongRunningUnitTest { private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class); - @Test public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { Future completableFuture = calculateAsync(); @@ -27,11 +26,12 @@ public class CompletableFutureLongRunningUnitTest { private Future calculateAsync() throws InterruptedException { CompletableFuture completableFuture = new CompletableFuture<>(); - Executors.newCachedThreadPool().submit(() -> { - Thread.sleep(500); - completableFuture.complete("Hello"); - return null; - }); + Executors.newCachedThreadPool() + .submit(() -> { + Thread.sleep(500); + completableFuture.complete("Hello"); + return null; + }); return completableFuture; } @@ -47,11 +47,12 @@ public class CompletableFutureLongRunningUnitTest { private Future calculateAsyncWithCancellation() throws InterruptedException { CompletableFuture completableFuture = new CompletableFuture<>(); - Executors.newCachedThreadPool().submit(() -> { - Thread.sleep(500); - completableFuture.cancel(false); - return null; - }); + Executors.newCachedThreadPool() + .submit(() -> { + Thread.sleep(500); + completableFuture.cancel(false); + return null; + }); return completableFuture; } @@ -98,21 +99,24 @@ public class CompletableFutureLongRunningUnitTest { @Test public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); assertEquals("Hello World", completableFuture.get()); } @Test public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); assertEquals("Hello World", completableFuture.get()); } @Test public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2)); + CompletableFuture.supplyAsync(() -> "Hello") + .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2)); } @Test @@ -131,7 +135,9 @@ public class CompletableFutureLongRunningUnitTest { assertTrue(future2.isDone()); assertTrue(future3.isDone()); - String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" ")); + String combined = Stream.of(future1, future2, future3) + .map(CompletableFuture::join) + .collect(Collectors.joining(" ")); assertEquals("Hello Beautiful World", combined); } @@ -147,7 +153,8 @@ public class CompletableFutureLongRunningUnitTest { throw new RuntimeException("Computation error!"); } return "Hello, " + name; - }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); + }) + .handle((s, t) -> s != null ? s : "Hello, Stranger!"); assertEquals("Hello, Stranger!", completableFuture.get()); } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java index a10ec66f20..e7a76d1ab9 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -15,7 +15,9 @@ public class UseLocalDateTimeUnitTest { @Test public void givenString_whenUsingParse_thenLocalDateTime() { - assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate()); - assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime()); + assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalDate()); + assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalTime()); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java index e158c0fd67..90e858f9ac 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -15,12 +15,14 @@ public class UseLocalDateUnitTest { @Test public void givenValues_whenUsingFactoryOf_thenLocalDate() { - assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString()); + assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10) + .toString()); } @Test public void givenString_whenUsingParse_thenLocalDate() { - assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString()); + assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10") + .toString()); } @Test @@ -30,12 +32,14 @@ public class UseLocalDateUnitTest { @Test public void givenDate_whenUsingPlus_thenNextDay() { - assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now())); + assertEquals(LocalDate.now() + .plusDays(1), useLocalDate.getNextDay(LocalDate.now())); } @Test public void givenDate_whenUsingMinus_thenPreviousDay() { - assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); + assertEquals(LocalDate.now() + .minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); } @Test @@ -45,7 +49,8 @@ public class UseLocalDateUnitTest { @Test public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { - assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth()); + assertEquals(1, useLocalDate.getFirstDayOfMonth() + .getDayOfMonth()); } @Test diff --git a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java index 811088cc0c..e91cbfcb75 100644 --- a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java +++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java @@ -21,7 +21,6 @@ public class FunctionalInterfaceUnitTest { private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class); - @Test public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { Map nameMap = new HashMap<>(); @@ -83,7 +82,8 @@ public class FunctionalInterfaceUnitTest { return result; }); - List fibonacci5 = fibonacci.limit(5).collect(Collectors.toList()); + List fibonacci5 = fibonacci.limit(5) + .collect(Collectors.toList()); assertEquals(new Integer(1), fibonacci5.get(0)); assertEquals(new Integer(1), fibonacci5.get(1)); @@ -112,7 +112,9 @@ public class FunctionalInterfaceUnitTest { public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() { List names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David"); - List namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList()); + List namesWithA = names.stream() + .filter(name -> name.startsWith("A")) + .collect(Collectors.toList()); assertEquals(2, namesWithA.size()); assertTrue(namesWithA.contains("Angela")); @@ -135,7 +137,8 @@ public class FunctionalInterfaceUnitTest { List values = Arrays.asList(3, 5, 8, 9, 12); - int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2); + int sum = values.stream() + .reduce(0, (i1, i2) -> i1 + i2); assertEquals(37, sum); diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java index ec865f71c4..2971f14c41 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java @@ -47,7 +47,8 @@ public class ConcurrentMapAggregateStatusManualTest { executorService.awaitTermination(1, TimeUnit.MINUTES); for (int i = 1; i <= MAX_SIZE; i++) { - assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue()); + assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1) + .intValue()); } assertEquals(MAX_SIZE, concurrentMap.size()); } @@ -69,7 +70,8 @@ public class ConcurrentMapAggregateStatusManualTest { executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); - assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue()); + assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1) + .intValue()); assertEquals(MAX_SIZE, concurrentMap.size()); } diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java index 43cbb2d293..e4fac66fe3 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java @@ -16,8 +16,12 @@ public class ConcurretMapMemoryConsistencyManualTest { public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception { Map map = new ConcurrentHashMap<>(); List sumList = parallelSum100(map, 1000); - assertEquals(1, sumList.stream().distinct().count()); - long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertEquals(1, sumList.stream() + .distinct() + .count()); + long wrongResultCount = sumList.stream() + .filter(num -> num != 100) + .count(); assertEquals(0, wrongResultCount); } @@ -25,8 +29,12 @@ public class ConcurretMapMemoryConsistencyManualTest { public void givenHashtable_whenSumParallel_thenCorrect() throws Exception { Map map = new Hashtable<>(); List sumList = parallelSum100(map, 1000); - assertEquals(1, sumList.stream().distinct().count()); - long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertEquals(1, sumList.stream() + .distinct() + .count()); + long wrongResultCount = sumList.stream() + .filter(num -> num != 100) + .count(); assertEquals(0, wrongResultCount); } @@ -34,8 +42,12 @@ public class ConcurretMapMemoryConsistencyManualTest { public void givenHashMap_whenSumParallel_thenError() throws Exception { Map map = new HashMap<>(); List sumList = parallelSum100(map, 100); - assertNotEquals(1, sumList.stream().distinct().count()); - long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertNotEquals(1, sumList.stream() + .distinct() + .count()); + long wrongResultCount = sumList.stream() + .filter(num -> num != 100) + .count(); assertTrue(wrongResultCount > 0); } diff --git a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java index 4452b4db9a..eea019da2c 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java @@ -13,35 +13,26 @@ import static org.junit.Assert.*; public class Java8GroupingByCollectorUnitTest { - private static final List posts = Arrays.asList( - new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), - new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), - new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), - new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), - new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); + private static final List posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), + new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); @Test public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() { - Map> postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType)); + Map> postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType)); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() { - Map postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); + Map postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS)); assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE)); @@ -50,174 +41,135 @@ public class Java8GroupingByCollectorUnitTest { @Test public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() { - Map likesPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); + Map likesPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); - assertEquals(50, likesPerType - .get(BlogPostType.NEWS) - .intValue()); - assertEquals(20, likesPerType - .get(BlogPostType.REVIEW) - .intValue()); - assertEquals(20, likesPerType - .get(BlogPostType.GUIDE) - .intValue()); + assertEquals(50, likesPerType.get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, likesPerType.get(BlogPostType.REVIEW) + .intValue()); + assertEquals(20, likesPerType.get(BlogPostType.GUIDE) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() { - EnumMap> postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); + EnumMap> postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() { - Map> postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, toSet())); + Map> postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, toSet())); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() { - ConcurrentMap> postsPerType = posts - .parallelStream() - .collect(groupingByConcurrent(BlogPost::getType)); + ConcurrentMap> postsPerType = posts.parallelStream() + .collect(groupingByConcurrent(BlogPost::getType)); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() { - Map averageLikesPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); + Map averageLikesPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); - assertEquals(25, averageLikesPerType - .get(BlogPostType.NEWS) - .intValue()); - assertEquals(20, averageLikesPerType - .get(BlogPostType.GUIDE) - .intValue()); - assertEquals(10, averageLikesPerType - .get(BlogPostType.REVIEW) - .intValue()); + assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE) + .intValue()); + assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() { - Map numberOfPostsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, counting())); + Map numberOfPostsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, counting())); - assertEquals(2, numberOfPostsPerType - .get(BlogPostType.NEWS) - .intValue()); - assertEquals(1, numberOfPostsPerType - .get(BlogPostType.GUIDE) - .intValue()); - assertEquals(2, numberOfPostsPerType - .get(BlogPostType.REVIEW) - .intValue()); + assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS) + .intValue()); + assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE) + .intValue()); + assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() { - Map> maxLikesPerPostType = posts - .stream() - .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); + Map> maxLikesPerPostType = posts.stream() + .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); - assertTrue(maxLikesPerPostType - .get(BlogPostType.NEWS) - .isPresent()); - assertEquals(35, maxLikesPerPostType - .get(BlogPostType.NEWS) - .get() - .getLikes()); + assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS) + .isPresent()); + assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS) + .get() + .getLikes()); - assertTrue(maxLikesPerPostType - .get(BlogPostType.GUIDE) - .isPresent()); - assertEquals(20, maxLikesPerPostType - .get(BlogPostType.GUIDE) - .get() - .getLikes()); + assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE) + .isPresent()); + assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE) + .get() + .getLikes()); - assertTrue(maxLikesPerPostType - .get(BlogPostType.REVIEW) - .isPresent()); - assertEquals(15, maxLikesPerPostType - .get(BlogPostType.REVIEW) - .get() - .getLikes()); + assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW) + .isPresent()); + assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW) + .get() + .getLikes()); } @Test public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() { - Map>> map = posts - .stream() - .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); + Map>> map = posts.stream() + .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); - assertEquals(1, map - .get("Author 1") - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, map - .get("Author 1") - .get(BlogPostType.GUIDE) - .size()); - assertEquals(1, map - .get("Author 1") - .get(BlogPostType.REVIEW) - .size()); + assertEquals(1, map.get("Author 1") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map.get("Author 1") + .get(BlogPostType.GUIDE) + .size()); + assertEquals(1, map.get("Author 1") + .get(BlogPostType.REVIEW) + .size()); - assertEquals(1, map - .get("Author 2") - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, map - .get("Author 2") - .get(BlogPostType.REVIEW) - .size()); - assertNull(map - .get("Author 2") - .get(BlogPostType.GUIDE)); + assertEquals(1, map.get("Author 2") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map.get("Author 2") + .get(BlogPostType.REVIEW) + .size()); + assertNull(map.get("Author 2") + .get(BlogPostType.GUIDE)); } @Test public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() { - Map likeStatisticsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); + Map likeStatisticsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS); diff --git a/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java b/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java index 7098f88f30..a0bd1cf093 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java @@ -17,8 +17,8 @@ public class Java8MapAndFlatMap { @Test public void givenStream_whenCalledMap_thenProduceList() { List myList = Stream.of("a", "b") - .map(String::toUpperCase) - .collect(Collectors.toList()); + .map(String::toUpperCase) + .collect(Collectors.toList()); assertEquals(asList("A", "B"), myList); } @@ -27,9 +27,9 @@ public class Java8MapAndFlatMap { List> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b")); System.out.println(list); - System.out.println(list - .stream().flatMap(Collection::stream) - .collect(Collectors.toList())); + System.out.println(list.stream() + .flatMap(Collection::stream) + .collect(Collectors.toList())); } @Test @@ -40,13 +40,11 @@ public class Java8MapAndFlatMap { @Test public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() { - assertEquals(Optional.of(Optional.of("STRING")), Optional - .of("string") - .map(s -> Optional.of("STRING"))); + assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string") + .map(s -> Optional.of("STRING"))); - assertEquals(Optional.of("STRING"), Optional - .of("string") - .flatMap(s -> Optional.of("STRING"))); + assertEquals(Optional.of("STRING"), Optional.of("string") + .flatMap(s -> Optional.of("STRING"))); } } diff --git a/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java index 1f3b380772..7f83e379cd 100644 --- a/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java @@ -55,7 +55,12 @@ public class JavaFolderSizeUnitTest { @Test public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException { final Path folder = Paths.get(path); - final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum(); + final long size = Files.walk(folder) + .filter(p -> p.toFile() + .isFile()) + .mapToLong(p -> p.toFile() + .length()) + .sum(); assertEquals(EXPECTED_SIZE, size); } @@ -72,8 +77,12 @@ public class JavaFolderSizeUnitTest { public void whenGetFolderSizeUsingGuava_thenCorrect() { final File folder = new File(path); - final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum(); + final Iterable files = com.google.common.io.Files.fileTreeTraverser() + .breadthFirstTraversal(folder); + final long size = StreamSupport.stream(files.spliterator(), false) + .filter(File::isFile) + .mapToLong(File::length) + .sum(); assertEquals(EXPECTED_SIZE, size); } diff --git a/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java index 26536ba705..1cac428285 100644 --- a/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java @@ -1,4 +1,5 @@ package com.baeldung.java8.comparator; + import java.util.Arrays; import java.util.Comparator; @@ -25,44 +26,32 @@ public class Java8ComparatorUnitTest { @Before public void initData() { - employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), - new Employee("Keith", 35, 4000, 3924401) }; - employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), - null, new Employee("Keith", 35, 4000, 3924401) }; + employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) }; + employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), - new Employee("Ace", 22, 2000, 5924001) }; + sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) }; - sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), }; + sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), }; - sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), - new Employee("Keith", 35, 4000, 3924401), }; + sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), }; - sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null }; + sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null }; - someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), - new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) }; + someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), - new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), - new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; } @Test public void whenComparing_thenSortedByName() { Comparator employeeNameComparator = Comparator.comparing(Employee::getName); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByName)); } @@ -72,16 +61,16 @@ public class Java8ComparatorUnitTest { return s2.compareTo(s1); }); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } - + @Test public void whenReversed_thenSortedByNameDesc() { - Comparator employeeNameComparator = Comparator.comparing(Employee::getName); - Comparator employeeNameComparatorReversed = employeeNameComparator.reversed(); + Comparator employeeNameComparator = Comparator.comparing(Employee::getName); + Comparator employeeNameComparatorReversed = employeeNameComparator.reversed(); Arrays.sort(employees, employeeNameComparatorReversed); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } @@ -89,7 +78,7 @@ public class Java8ComparatorUnitTest { public void whenComparingInt_thenSortedByAge() { Comparator employeeAgeComparator = Comparator.comparingInt(Employee::getAge); Arrays.sort(employees, employeeAgeComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByAge)); } @@ -97,7 +86,7 @@ public class Java8ComparatorUnitTest { public void whenComparingLong_thenSortedByMobile() { Comparator employeeMobileComparator = Comparator.comparingLong(Employee::getMobile); Arrays.sort(employees, employeeMobileComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByMobile)); } @@ -105,7 +94,7 @@ public class Java8ComparatorUnitTest { public void whenComparingDouble_thenSortedBySalary() { Comparator employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary); Arrays.sort(employees, employeeSalaryComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesBySalary)); } @@ -113,7 +102,7 @@ public class Java8ComparatorUnitTest { public void whenNaturalOrder_thenSortedByName() { Comparator employeeNameComparator = Comparator. naturalOrder(); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByName)); } @@ -121,7 +110,7 @@ public class Java8ComparatorUnitTest { public void whenReverseOrder_thenSortedByNameDesc() { Comparator employeeNameComparator = Comparator. reverseOrder(); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } @@ -130,7 +119,7 @@ public class Java8ComparatorUnitTest { Comparator employeeNameComparator = Comparator.comparing(Employee::getName); Comparator employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst); -// System.out.println(Arrays.toString(employeesArrayWithNulls)); + // System.out.println(Arrays.toString(employeesArrayWithNulls)); assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst)); } @@ -139,27 +128,28 @@ public class Java8ComparatorUnitTest { Comparator employeeNameComparator = Comparator.comparing(Employee::getName); Comparator employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast); -// System.out.println(Arrays.toString(employeesArrayWithNulls)); + // System.out.println(Arrays.toString(employeesArrayWithNulls)); assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast)); } @Test public void whenThenComparing_thenSortedByAgeName() { - Comparator employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName); + Comparator employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge) + .thenComparing(Employee::getName); Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator); -// System.out.println(Arrays.toString(someMoreEmployees)); + // System.out.println(Arrays.toString(someMoreEmployees)); assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName)); } @Test public void whenThenComparing_thenSortedByNameAge() { - Comparator employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge); + Comparator employee_Name_Age_Comparator = Comparator.comparing(Employee::getName) + .thenComparingInt(Employee::getAge); Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator); -// System.out.println(Arrays.toString(someMoreEmployees)); + // System.out.println(Arrays.toString(someMoreEmployees)); assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge)); } - } diff --git a/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java b/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java index 0085de6327..4cb2551fae 100644 --- a/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java @@ -17,7 +17,6 @@ public class OptionalUnitTest { private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class); - // creating Optional @Test public void whenCreatesEmptyOptional_thenCorrect() { @@ -94,9 +93,11 @@ public class OptionalUnitTest { public void whenOptionalFilterWorks_thenCorrect() { Integer year = 2016; Optional yearOptional = Optional.of(year); - boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent(); + boolean is2016 = yearOptional.filter(y -> y == 2016) + .isPresent(); assertTrue(is2016); - boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent(); + boolean is2017 = yearOptional.filter(y -> y == 2017) + .isPresent(); assertFalse(is2017); } @@ -128,7 +129,11 @@ public class OptionalUnitTest { } public boolean priceIsInRange2(Modem modem2) { - return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent(); + return Optional.ofNullable(modem2) + .map(Modem::getPrice) + .filter(p -> p >= 10) + .filter(p -> p <= 15) + .isPresent(); } // Transforming Value With map() @@ -137,7 +142,8 @@ public class OptionalUnitTest { List companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple"); Optional> listOptional = Optional.of(companyNames); - int size = listOptional.map(List::size).orElse(0); + int size = listOptional.map(List::size) + .orElse(0); assertEquals(6, size); } @@ -146,7 +152,8 @@ public class OptionalUnitTest { String name = "baeldung"; Optional nameOptional = Optional.of(name); - int len = nameOptional.map(String::length).orElse(0); + int len = nameOptional.map(String::length) + .orElse(0); assertEquals(8, len); } @@ -154,10 +161,13 @@ public class OptionalUnitTest { public void givenOptional_whenMapWorksWithFilter_thenCorrect() { String password = " password "; Optional passOpt = Optional.of(password); - boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent(); + boolean correctPassword = passOpt.filter(pass -> pass.equals("password")) + .isPresent(); assertFalse(correctPassword); - correctPassword = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent(); + correctPassword = passOpt.map(String::trim) + .filter(pass -> pass.equals("password")) + .isPresent(); assertTrue(correctPassword); } @@ -172,7 +182,8 @@ public class OptionalUnitTest { String name1 = nameOptional.orElseThrow(IllegalArgumentException::new); assertEquals("john", name1); - String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new); + String name = personOptional.flatMap(Person::getName) + .orElseThrow(IllegalArgumentException::new); assertEquals("john", name); } @@ -182,7 +193,9 @@ public class OptionalUnitTest { person.setPassword("password"); Optional personOptional = Optional.of(person); - String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new); + String password = personOptional.flatMap(Person::getPassword) + .filter(cleanPass -> cleanPass.equals("password")) + .orElseThrow(IllegalArgumentException::new); assertEquals("password", password); } @@ -190,7 +203,8 @@ public class OptionalUnitTest { @Test public void whenOrElseWorks_thenCorrect() { String nullName = null; - String name = Optional.ofNullable(nullName).orElse("john"); + String name = Optional.ofNullable(nullName) + .orElse("john"); assertEquals("john", name); } @@ -198,7 +212,8 @@ public class OptionalUnitTest { @Test public void whenOrElseGetWorks_thenCorrect() { String nullName = null; - String name = Optional.ofNullable(nullName).orElseGet(() -> "john"); + String name = Optional.ofNullable(nullName) + .orElseGet(() -> "john"); assertEquals("john", name); } @@ -207,11 +222,13 @@ public class OptionalUnitTest { public void whenOrElseGetAndOrElseOverlap_thenCorrect() { String text = null; LOG.debug("Using orElseGet:"); - String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); + String defaultText = Optional.ofNullable(text) + .orElseGet(this::getMyDefault); assertEquals("Default Value", defaultText); LOG.debug("Using orElse:"); - defaultText = Optional.ofNullable(text).orElse(getMyDefault()); + defaultText = Optional.ofNullable(text) + .orElse(getMyDefault()); assertEquals("Default Value", defaultText); } @@ -219,11 +236,13 @@ public class OptionalUnitTest { public void whenOrElseGetAndOrElseDiffer_thenCorrect() { String text = "Text present"; LOG.debug("Using orElseGet:"); - String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); + String defaultText = Optional.ofNullable(text) + .orElseGet(this::getMyDefault); assertEquals("Text present", defaultText); LOG.debug("Using orElse:"); - defaultText = Optional.ofNullable(text).orElse(getMyDefault()); + defaultText = Optional.ofNullable(text) + .orElse(getMyDefault()); assertEquals("Text present", defaultText); } @@ -231,7 +250,8 @@ public class OptionalUnitTest { @Test(expected = IllegalArgumentException.class) public void whenOrElseThrowWorks_thenCorrect() { String nullName = null; - String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new); + String name = Optional.ofNullable(nullName) + .orElseThrow(IllegalArgumentException::new); } public String getMyDefault() { diff --git a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java index 3c8f519082..543c680597 100644 --- a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java +++ b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java @@ -43,6 +43,8 @@ public class FlattenNestedListUnitTest { } private List flattenListOfListsStream(List> list) { - return list.stream().flatMap(Collection::stream).collect(Collectors.toList()); + return list.stream() + .flatMap(Collection::stream) + .collect(Collectors.toList()); } } diff --git a/core-java/src/test/java/com/baeldung/maths/RoundTest.java b/core-java/src/test/java/com/baeldung/maths/RoundTest.java index 5ce9523e21..9e3c049c96 100644 --- a/core-java/src/test/java/com/baeldung/maths/RoundTest.java +++ b/core-java/src/test/java/com/baeldung/maths/RoundTest.java @@ -15,56 +15,56 @@ public class RoundTest { private double expected = 2.03d; @Test - public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() { + public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() { Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundAvoid(value, places), delta); Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - + places = 3; expected = 2.035d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundAvoid(value, places), delta); Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - + value = 1000.0d; places = 17; expected = 1000.0d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 ! Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - + value = 256.025d; places = 2; expected = 256.03d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 ! Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 256.02 ! Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 ! - - value = 260.775d; + + value = 260.775d; places = 2; expected = 260.78d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 ! Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 260.77 ! Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 ! - + value = 90080070060.1d; places = 9; expected = 90080070060.1d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 ! diff --git a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java index 2bf6d142bb..70c6e88c49 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java @@ -14,7 +14,8 @@ public class EchoIntegrationTest { @BeforeClass public static void start() throws InterruptedException { - Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT)); + Executors.newSingleThreadExecutor() + .submit(() -> new EchoServer().start(PORT)); Thread.sleep(500); } diff --git a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java index 06b37d8539..4367ed26a2 100644 --- a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java @@ -17,7 +17,8 @@ public class GreetServerIntegrationTest { @BeforeClass public static void start() throws InterruptedException { - Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT)); + Executors.newSingleThreadExecutor() + .submit(() -> new GreetServer().start(PORT)); Thread.sleep(500); } diff --git a/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java index 3ab8e1de91..5da68aa746 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java @@ -96,9 +96,12 @@ public class JavaIoUnitTest { // utils private final void logMemory() { - logger.info("Max Memory: {} Mb", Runtime.getRuntime().maxMemory() / 1048576); - logger.info("Total Memory: {} Mb", Runtime.getRuntime().totalMemory() / 1048576); - logger.info("Free Memory: {} Mb", Runtime.getRuntime().freeMemory() / 1048576); + logger.info("Max Memory: {} Mb", Runtime.getRuntime() + .maxMemory() / 1048576); + logger.info("Total Memory: {} Mb", Runtime.getRuntime() + .totalMemory() / 1048576); + logger.info("Free Memory: {} Mb", Runtime.getRuntime() + .freeMemory() / 1048576); } } diff --git a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java index a11659547e..f17531e744 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java @@ -13,7 +13,6 @@ public class JavaRandomUnitTest { private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class); - // tests - random long @Test @@ -25,7 +24,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() { - final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong(); + final long generatedLong = new RandomDataGenerator().getRandomGenerator() + .nextLong(); LOG.debug("{}", generatedLong); } @@ -68,7 +68,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() { - final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt(); + final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator() + .nextInt(); LOG.debug("{}", generatedInteger); } @@ -93,7 +94,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() { - final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); + final float generatedFloat = new RandomDataGenerator().getRandomGenerator() + .nextFloat(); LOG.debug("{}", generatedFloat); } @@ -111,7 +113,8 @@ public class JavaRandomUnitTest { public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() { final float leftLimit = 1F; final float rightLimit = 10F; - final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); + final float randomFloat = new RandomDataGenerator().getRandomGenerator() + .nextFloat(); final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit); LOG.debug("{}", generatedFloat); @@ -128,7 +131,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { - final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); + final double generatedDouble = new RandomDataGenerator().getRandomGenerator() + .nextDouble(); LOG.debug("{}", generatedDouble); } diff --git a/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java index 7a03070e82..826106a09e 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java @@ -15,7 +15,6 @@ public class JavaTimerLongRunningUnitTest { private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class); - // tests @Test @@ -23,7 +22,8 @@ public class JavaTimerLongRunningUnitTest { final TimerTask timerTask = new TimerTask() { @Override public void run() { - LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread() + .getName()); } }; final Timer timer = new Timer("Timer"); diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java index 477092bfcb..99af49c8d3 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java @@ -38,7 +38,8 @@ public class Employee implements Comparable { @Override public boolean equals(Object obj) { - return ((Employee) obj).getName().equals(getName()); + return ((Employee) obj).getName() + .equals(getName()); } @Override @@ -49,7 +50,13 @@ public class Employee implements Comparable { @Override public String toString() { - return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString(); + return new StringBuffer().append("(") + .append(getName()) + .append(getAge()) + .append(",") + .append(getSalary()) + .append(")") + .toString(); } } diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java b/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java index 277e037615..ca9c9b4b5d 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java @@ -113,7 +113,8 @@ public class JavaSortingUnitTest { sortedMap.put(entry.getKey(), entry.getValue()); } - assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys)); + assertTrue(Arrays.equals(sortedMap.keySet() + .toArray(), sortedKeys)); } @Test @@ -127,7 +128,8 @@ public class JavaSortingUnitTest { sortedMap.put(entry.getKey(), entry.getValue()); } - assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues)); + assertTrue(Arrays.equals(sortedMap.values() + .toArray(), sortedValues)); } @Test diff --git a/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java index 56cf4071b4..31d377622d 100644 --- a/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java +++ b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java @@ -14,6 +14,12 @@ public class BookControllerFeignClientBuilder { private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books"); private static T createClient(Class type, String uri) { - return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri); + return Feign.builder() + .client(new OkHttpClient()) + .encoder(new GsonEncoder()) + .decoder(new GsonDecoder()) + .logger(new Slf4jLogger(type)) + .logLevel(Logger.Level.FULL) + .target(type, uri); } } diff --git a/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java b/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java index a17dbf7a2e..bee440bd9e 100644 --- a/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java +++ b/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java @@ -34,25 +34,31 @@ public class BookClientLiveTest { @Test public void givenBookClient_shouldRunSuccessfully() throws Exception { - List books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList()); + List books = bookClient.findAll() + .stream() + .map(BookResource::getBook) + .collect(Collectors.toList()); assertTrue(books.size() > 2); log.info("{}", books); } @Test public void givenBookClient_shouldFindOneBook() throws Exception { - Book book = bookClient.findByIsbn("0151072558").getBook(); + Book book = bookClient.findByIsbn("0151072558") + .getBook(); assertThat(book.getAuthor(), containsString("Orwell")); log.info("{}", book); } @Test public void givenBookClient_shouldPostBook() throws Exception { - String isbn = UUID.randomUUID().toString(); + String isbn = UUID.randomUUID() + .toString(); Book book = new Book(isbn, "Me", "It's me!", null, null); bookClient.create(book); - book = bookClient.findByIsbn(isbn).getBook(); + book = bookClient.findByIsbn(isbn) + .getBook(); assertThat(book.getAuthor(), is("Me")); log.info("{}", book); } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java index 0330498089..db8b594509 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java @@ -9,7 +9,8 @@ public class Author extends Person { List items = new ArrayList<>(); - public Author(){} + public Author() { + } public Author(String firstName, String lastName) { super(firstName, lastName); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java index 3add362007..9ba91e9170 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java @@ -11,7 +11,7 @@ public class Person { private String firstName; private String lastName; - public Person(){ + public Person() { } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java index 34fbd16c1c..d48c95b255 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.deserialization.jsoncreator; - import com.baeldung.jackson.domain.Person; import com.baeldung.jackson.domain.Item; import com.fasterxml.jackson.annotation.JsonCreator; @@ -14,9 +13,7 @@ public class Author extends Person { List items = new ArrayList<>(); @JsonCreator - public Author( - @JsonProperty("christianName") String firstName, - @JsonProperty("surname") String lastName) { + public Author(@JsonProperty("christianName") String firstName, @JsonProperty("surname") String lastName) { super(firstName, lastName); } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java index 8e93ab5ce7..dc0d0ee623 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java @@ -13,7 +13,8 @@ public class Book extends Item { private Date published; private BigDecimal pages; - public Book() {} + public Book() { + } public Book(String title, Author author) { super(title, author); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java index c9d6ae39fa..93bbfd0069 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java @@ -11,8 +11,7 @@ import java.util.Date; public class CustomDateDeserializer extends StdDeserializer { - private static SimpleDateFormat formatter = - new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); public CustomDateDeserializer() { this(null); @@ -23,8 +22,7 @@ public class CustomDateDeserializer extends StdDeserializer { } @Override - public Date deserialize(JsonParser jsonparser, DeserializationContext context) - throws IOException { + public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException { String date = jsonparser.getText(); try { return formatter.parse(date); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java index ab4689dec8..fc27a586ac 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java @@ -19,7 +19,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java index c63b63f515..3f9ae70a88 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java @@ -18,7 +18,8 @@ public class Author extends Person { private List items = new ArrayList<>(); - public Author(){} + public Author() { + } public Author(String firstName, String lastName) { super(firstName, lastName); diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java b/jackson/src/main/java/com/baeldung/jackson/domain/Book.java index 6e486ffbd3..a5963e33ba 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Book.java @@ -15,7 +15,7 @@ public class Book extends Item { private Date published; private BigDecimal pages; - public Book(){ + public Book() { } public Book(String title, Author author) { diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java b/jackson/src/main/java/com/baeldung/jackson/domain/Course.java index 15049ded09..672b0bc250 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Course.java @@ -10,7 +10,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java b/jackson/src/main/java/com/baeldung/jackson/domain/Item.java index fc861d2f3c..d9d1350a8e 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Item.java @@ -17,7 +17,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java b/jackson/src/main/java/com/baeldung/jackson/domain/Person.java index 2f66a1acfe..785efff755 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Person.java @@ -14,7 +14,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java b/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java index 54ebff8a56..107d75eb0d 100644 --- a/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java +++ b/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java @@ -9,16 +9,16 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; public class ClassWithAMap { - @JsonProperty("map") - @JsonDeserialize(keyUsing = MyPairDeserializer.class) - private final Map map; + @JsonProperty("map") + @JsonDeserialize(keyUsing = MyPairDeserializer.class) + private final Map map; - @JsonCreator - public ClassWithAMap(Map map) { - this.map = map; - } + @JsonCreator + public ClassWithAMap(Map map) { + this.map = map; + } - public Map getMap() { - return map; - } + public Map getMap() { + return map; + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java b/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java index ebe41890fe..ca5960e0cf 100644 --- a/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java +++ b/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java @@ -4,77 +4,77 @@ import com.fasterxml.jackson.annotation.JsonValue; public class MyPair { - private String first; - private String second; + private String first; + private String second; - public MyPair(String first, String second) { - this.first = first; - this.second = second; - } + public MyPair(String first, String second) { + this.first = first; + this.second = second; + } - public MyPair(String both) { - String[] pairs = both.split("and"); - this.first = pairs[0].trim(); - this.second = pairs[1].trim(); - } + public MyPair(String both) { + String[] pairs = both.split("and"); + this.first = pairs[0].trim(); + this.second = pairs[1].trim(); + } - @Override - @JsonValue - public String toString() { - return first + " and " + second; - } + @Override + @JsonValue + public String toString() { + return first + " and " + second; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((first == null) ? 0 : first.hashCode()); - result = prime * result + ((second == null) ? 0 : second.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((first == null) ? 0 : first.hashCode()); + result = prime * result + ((second == null) ? 0 : second.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof MyPair)) { - return false; - } - MyPair other = (MyPair) obj; - if (first == null) { - if (other.first != null) { - return false; - } - } else if (!first.equals(other.first)) { - return false; - } - if (second == null) { - if (other.second != null) { - return false; - } - } else if (!second.equals(other.second)) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof MyPair)) { + return false; + } + MyPair other = (MyPair) obj; + if (first == null) { + if (other.first != null) { + return false; + } + } else if (!first.equals(other.first)) { + return false; + } + if (second == null) { + if (other.second != null) { + return false; + } + } else if (!second.equals(other.second)) { + return false; + } + return true; + } - public String getFirst() { - return first; - } + public String getFirst() { + return first; + } - public void setFirst(String first) { - this.first = first; - } + public void setFirst(String first) { + this.first = first; + } - public String getSecond() { - return second; - } + public String getSecond() { + return second; + } - public void setSecond(String second) { - this.second = second; - } + public void setSecond(String second) { + this.second = second; + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/format/User.java b/jackson/src/main/java/com/baeldung/jackson/format/User.java index 101ef09a4a..e655deb93b 100755 --- a/jackson/src/main/java/com/baeldung/jackson/format/User.java +++ b/jackson/src/main/java/com/baeldung/jackson/format/User.java @@ -13,28 +13,25 @@ public class User extends Person { private String firstName; private String lastName; - @JsonFormat(shape = JsonFormat.Shape.STRING, - pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") private Date createdDate; - public User(String firstName,String lastName) { - super(firstName, lastName); - this.createdDate = new Date(); + public User(String firstName, String lastName) { + super(firstName, lastName); + this.createdDate = new Date(); } public Date getCreatedDate() { return createdDate; } - @JsonFormat(shape = JsonFormat.Shape.STRING, - pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", - locale = "en_GB") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB") public Date getCurrentDate() { - return new Date(); + return new Date(); } @JsonFormat(shape = JsonFormat.Shape.NUMBER) public Date getDateNum() { - return new Date(); + return new Date(); } } diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java index 8c18522627..0037d83148 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java @@ -17,7 +17,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java index e6d62eee3d..70b4dd9842 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java @@ -12,10 +12,12 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonIgnoreProperties({"medium"}) +@JsonIgnoreProperties({ "medium" }) public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java index 11aa8ddb1a..db0412b09b 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java +++ b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java @@ -12,10 +12,7 @@ public class ItemIdAddedToUser extends Event { private final Long quantity; @JsonCreator - public ItemIdAddedToUser(@JsonProperty("id") String id, - @JsonProperty("timestamp") Long timestamp, - @JsonProperty("itemId") String itemId, - @JsonProperty("quantity") Long quantity) { + public ItemIdAddedToUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) { super(id, timestamp); this.itemId = itemId; this.quantity = quantity; diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java index 682394ddf3..ab3b9bf34f 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java +++ b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java @@ -10,10 +10,7 @@ public class ItemIdRemovedFromUser extends Event { private final Long quantity; @JsonCreator - public ItemIdRemovedFromUser(@JsonProperty("id") String id, - @JsonProperty("timestamp") Long timestamp, - @JsonProperty("itemId") String itemId, - @JsonProperty("quantity") Long quantity) { + public ItemIdRemovedFromUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) { super(id, timestamp); this.itemId = itemId; this.quantity = quantity; diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java index 8825677e86..a44492b9f7 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java @@ -13,7 +13,9 @@ import java.util.List; @CustomCourseAnnotation public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java index 37b0bf357e..d7f72ca6ec 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java @@ -14,7 +14,7 @@ import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotationsInside @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({"title", "price", "id", "duration", "authors", "level"}) -@JsonIgnoreProperties({"prerequisite"}) +@JsonPropertyOrder({ "title", "price", "id", "duration", "authors", "level" }) +@JsonIgnoreProperties({ "prerequisite" }) public @interface CustomCourseAnnotation { } diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java index 930c4afb58..6625283dec 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java @@ -20,7 +20,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java index 8df3aec051..0638e32925 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java @@ -16,7 +16,7 @@ import java.util.List; * @version 1.0 */ @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({"lastName", "items", "firstName", "id"}) +@JsonPropertyOrder({ "lastName", "items", "firstName", "id" }) public class Author extends Person { @JsonIgnore diff --git a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java b/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java index 1eab9f5d02..1813148b2b 100644 --- a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java +++ b/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java @@ -18,12 +18,8 @@ public class Order { private Type type; private int internalAudit; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, - include = JsonTypeInfo.As.PROPERTY, - property = "ordertype") - @JsonSubTypes({ - @JsonSubTypes.Type(value = InternalType.class, name = "internal") - }) + @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ordertype") + @JsonSubTypes({ @JsonSubTypes.Type(value = InternalType.class, name = "internal") }) public static class Type { public long id; public String name; diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java index 32a6358003..2340de5957 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java @@ -24,8 +24,11 @@ public class ActorJacksonSerializer extends StdSerializer { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("imdbId", actor.getImdbId()); jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null); - jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography().size() : null); - jsonGenerator.writeStringField("filmography", actor.getFilmography().stream().collect(Collectors.joining("-"))); + jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography() + .size() : null); + jsonGenerator.writeStringField("filmography", actor.getFilmography() + .stream() + .collect(Collectors.joining("-"))); jsonGenerator.writeEndObject(); } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java index 0aa6db98d0..43bdc1c500 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java @@ -9,10 +9,9 @@ import com.fasterxml.jackson.databind.KeyDeserializer; public class MyPairDeserializer extends KeyDeserializer { - @Override - public MyPair deserializeKey(String key, DeserializationContext ctxt) - throws IOException, JsonProcessingException { + @Override + public MyPair deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException { - return new MyPair(key); - } + return new MyPair(key); + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java index 68afb6c193..fee1cafe16 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java @@ -12,14 +12,12 @@ import com.fasterxml.jackson.databind.SerializerProvider; public class MyPairSerializer extends JsonSerializer { - private final ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); - @Override - public void serialize(MyPair value, JsonGenerator gen, - SerializerProvider serializers) throws IOException, - JsonProcessingException { - StringWriter writer = new StringWriter(); - mapper.writeValue(writer, value); - gen.writeFieldName(writer.toString()); - } + @Override + public void serialize(MyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { + StringWriter writer = new StringWriter(); + mapper.writeValue(writer, value); + gen.writeFieldName(writer.toString()); + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java index 13453edeb2..8d89fefce7 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.serialization.jsongetter; - import com.baeldung.jackson.domain.Item; import com.baeldung.jackson.domain.Person; import com.fasterxml.jackson.annotation.JsonGetter; diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java index c5214f3305..dadf893cf9 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.serialization.jsonpropertyorder; - import com.baeldung.jackson.domain.Item; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -13,7 +12,7 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonPropertyOrder({"items", "firstName", "lastName", "id"}) +@JsonPropertyOrder({ "items", "firstName", "lastName", "id" }) public class Author extends Person { List items = new ArrayList<>(); diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java index e682f7c394..0ecc4e72ce 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java @@ -19,7 +19,8 @@ public class Book extends Item { private Date published; private BigDecimal pages; - public Book(){} + public Book() { + } public Book(String title, Author author) { super(title, author); diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java index 8e6d20cfe0..131f4f3695 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java @@ -17,8 +17,7 @@ import java.util.Date; */ public class CustomDateSerializer extends StdSerializer { - private static SimpleDateFormat formatter = - new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); public CustomDateSerializer() { this(null); @@ -29,8 +28,7 @@ public class CustomDateSerializer extends StdSerializer { } @Override - public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) - throws IOException, JsonProcessingException { + public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException { gen.writeString(formatter.format(value)); } } diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java index ed6ac25184..56cfa85793 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java @@ -19,7 +19,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java index eb7cb097e5..a3fdc2d8eb 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java @@ -14,7 +14,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java index c4e0a2ecdb..647c451659 100644 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java @@ -47,9 +47,10 @@ public class ExtraAnnotationUnitTest { ObjectMapper mapper = new ObjectMapper(); BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation"); - ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0"); + ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class) + .withAttribute("version", "1.0"); String jsonString = writer.writeValueAsString(bean); - + assertThat(jsonString, not(containsString("version"))); assertThat(jsonString, not(containsString("1.0"))); } @@ -59,9 +60,10 @@ public class ExtraAnnotationUnitTest { ObjectMapper mapper = new ObjectMapper(); BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation"); - ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0"); + ObjectWriter writer = mapper.writerFor(BeanWithAppend.class) + .withAttribute("version", "1.0"); String jsonString = writer.writeValueAsString(bean); - + assertThat(jsonString, containsString("version")); assertThat(jsonString, containsString("1.0")); } @@ -71,7 +73,7 @@ public class ExtraAnnotationUnitTest { ObjectMapper mapper = new ObjectMapper(); NamingBean bean = new NamingBean(3, "Naming Bean"); String jsonString = mapper.writeValueAsString(bean); - + assertThat(jsonString, containsString("bean_name")); } diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java index 495bb7de43..0a8736d9a5 100644 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.ObjectIdGenerators; - public class IdentityReferenceBeans { @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public static class BeanWithoutIdentityReference { @@ -32,7 +31,7 @@ public class IdentityReferenceBeans { this.name = name; } } - + @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") @JsonIdentityReference(alwaysAsId = true) public static class BeanWithIdentityReference { diff --git a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java index 75e0a4ecb7..c6babdee01 100644 --- a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java @@ -20,6 +20,7 @@ public class CustomListSerializer extends StdSerializer public CustomListSerializer(final Class> t) { super(t); } + @Override public void serialize(final List items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { final List ids = new ArrayList(); diff --git a/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java b/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java index dbcf42488e..ac7d772f0f 100644 --- a/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java @@ -11,7 +11,6 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class CustomLocalDateTimeSerializer extends StdSerializer { - private static final long serialVersionUID = -7449444168934819290L; private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java index e9c89b8c78..bbc3f31a6c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java @@ -28,9 +28,11 @@ public class ItemDeserializer extends StdDeserializer { */ @Override public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jp.getCodec().readTree(jp); + final JsonNode node = jp.getCodec() + .readTree(jp); final int id = (Integer) ((IntNode) node.get("id")).numberValue(); - final String itemName = node.get("itemName").asText(); + final String itemName = node.get("itemName") + .asText(); final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue(); return new Item(id, itemName, new User(userId, null)); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java index 2036780e99..eaba9a7173 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java @@ -28,9 +28,11 @@ public class ItemDeserializerOnClass extends StdDeserializer */ @Override public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jp.getCodec().readTree(jp); + final JsonNode node = jp.getCodec() + .readTree(jp); final int id = (Integer) ((IntNode) node.get("id")).numberValue(); - final String itemName = node.get("itemName").asText(); + final String itemName = node.get("itemName") + .asText(); final int userId = (Integer) ((IntNode) node.get("owner")).numberValue(); return new ItemWithSerializer(id, itemName, new User(userId, null)); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java index 4d5db699a0..1c3e95241a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java @@ -16,54 +16,49 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonMapDeserializeUnitTest { - private Map map; - private Map cmap; - final ObjectMapper mapper = new ObjectMapper(); + private Map map; + private Map cmap; + final ObjectMapper mapper = new ObjectMapper(); - @Test - public void whenSimpleMapDeserialize_thenCorrect() - throws JsonParseException, JsonMappingException, IOException { + @Test + public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonInput = "{\"key\": \"value\"}"; - TypeReference> typeRef = new TypeReference>() { - }; + final String jsonInput = "{\"key\": \"value\"}"; + TypeReference> typeRef = new TypeReference>() { + }; - final Map map = mapper.readValue(jsonInput, typeRef); + final Map map = mapper.readValue(jsonInput, typeRef); - Assert.assertEquals("value", map.get("key")); - } + Assert.assertEquals("value", map.get("key")); + } - @Test - public void whenObjectStringMapDeserialize_thenCorrect() - throws JsonParseException, JsonMappingException, IOException { + @Test + public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}"; + final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}"; - TypeReference> typeRef = new TypeReference>() { - }; + TypeReference> typeRef = new TypeReference>() { + }; - map = mapper.readValue(jsonInput, typeRef); + map = mapper.readValue(jsonInput, typeRef); - Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello"))); + Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello"))); - ClassWithAMap classWithMap = mapper.readValue(jsonInput, - ClassWithAMap.class); + ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class); - Assert.assertEquals("Comedy", - classWithMap.getMap().get(new MyPair("Abbott", "Costello"))); - } + Assert.assertEquals("Comedy", classWithMap.getMap() + .get(new MyPair("Abbott", "Costello"))); + } - @Test - public void whenObjectObjectMapDeserialize_thenCorrect() - throws JsonParseException, JsonMappingException, IOException { + @Test + public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}"; - TypeReference> typeRef = new TypeReference>() { - }; + final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}"; + TypeReference> typeRef = new TypeReference>() { + }; - cmap = mapper.readValue(jsonInput, typeRef); + cmap = mapper.readValue(jsonInput, typeRef); - Assert.assertEquals(new MyPair("Comedy", "1940s"), - cmap.get(new MyPair("Abbott", "Costello"))); - } + Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello"))); + } } diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java index 81bb14c533..96dbff6f3c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java @@ -27,7 +27,9 @@ public class JacksonInjectUnitTest { // act InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id); - Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson); + Author author = new ObjectMapper().reader(inject) + .forType(Author.class) + .readValue(authorJson); // assert assertThat(author.getId()).isEqualTo(id); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java index 7c338696e7..2e1f94bc3c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java @@ -23,15 +23,28 @@ public class JsonAnySetterUnitTest { String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}"; // act - Inventory inventory = new ObjectMapper().readerFor(Inventory.class).readValue(json); + Inventory inventory = new ObjectMapper().readerFor(Inventory.class) + .readValue(json); // assert - assertThat(from(json).getMap(".").get("USA")).isEqualTo(inventory.getCountryDeliveryCost().get("USA")); - assertThat(from(json).getMap(".").get("UK")).isEqualTo(inventory.getCountryDeliveryCost().get("UK")); - assertThat(from(json).getMap(".").get("China")).isEqualTo(inventory.getCountryDeliveryCost().get("China")); - assertThat(from(json).getMap(".").get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost().get("Brazil")); - assertThat(from(json).getMap(".").get("France")).isEqualTo(inventory.getCountryDeliveryCost().get("France")); - assertThat(from(json).getMap(".").get("Russia")).isEqualTo(inventory.getCountryDeliveryCost().get("Russia")); + assertThat(from(json).getMap(".") + .get("USA")).isEqualTo(inventory.getCountryDeliveryCost() + .get("USA")); + assertThat(from(json).getMap(".") + .get("UK")).isEqualTo(inventory.getCountryDeliveryCost() + .get("UK")); + assertThat(from(json).getMap(".") + .get("China")).isEqualTo(inventory.getCountryDeliveryCost() + .get("China")); + assertThat(from(json).getMap(".") + .get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost() + .get("Brazil")); + assertThat(from(json).getMap(".") + .get("France")).isEqualTo(inventory.getCountryDeliveryCost() + .get("France")); + assertThat(from(json).getMap(".") + .get("Russia")).isEqualTo(inventory.getCountryDeliveryCost() + .get("Russia")); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java index cc6b2a28aa..cc245dab66 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java @@ -20,14 +20,11 @@ public class JsonCreatorUnitTest { public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { // arrange - String authorJson = - "{" + - " \"christianName\": \"Alex\"," + - " \"surname\": \"Theedom\"" + - "}"; + String authorJson = "{" + " \"christianName\": \"Alex\"," + " \"surname\": \"Theedom\"" + "}"; // act - final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson); + final Author author = new ObjectMapper().readerFor(Author.class) + .readValue(authorJson); // assert assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName()); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java index dca2252431..1bcde998d6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java @@ -24,7 +24,8 @@ public class JsonDeserializeUnitTest { String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"authors\":[{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"firstName\":\"Joshua\",\"lastName\":\"Bloch\"}],\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}"; // act - Book book = new ObjectMapper().readerFor(Book.class).readValue(bookJson); + Book book = new ObjectMapper().readerFor(Book.class) + .readValue(bookJson); // assert SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java index 42e105cd52..4379fe376c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java @@ -23,10 +23,13 @@ public class JsonSetterUnitTest { String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}"; // act - Author author = new ObjectMapper().readerFor(Author.class).readValue(json); + Author author = new ObjectMapper().readerFor(Author.class) + .readValue(json); // assert - assertThat(from(json).getList("publications").size()).isEqualTo(author.getItems().size()); + assertThat(from(json).getList("publications") + .size()).isEqualTo(author.getItems() + .size()); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java index c2d2e84d45..daca85f66a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java +++ b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.dynamicIgnore; - public class Address implements Hidable { private String city; private String country; diff --git a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java index edca786432..a32e6844a6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java +++ b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java @@ -2,7 +2,6 @@ package com.baeldung.jackson.dynamicIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - @JsonIgnoreProperties("hidden") public interface Hidable { boolean isHidden(); diff --git a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java index 366f611edf..daa62b4be6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java +++ b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.dynamicIgnore; - public class Person implements Hidable { private String name; private Address address; @@ -13,7 +12,6 @@ public class Person implements Hidable { this.hidden = hidden; } - public String getName() { return name; } @@ -29,6 +27,7 @@ public class Person implements Hidable { public void setAddress(final Address address) { this.address = address; } + @Override public boolean isHidden() { return hidden; diff --git a/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java index 7ce03ff625..cf166fdc36 100755 --- a/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java @@ -22,18 +22,16 @@ public class JsonFormatUnitTest { @Test public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException { - User user = new User("Jay", "Sridhar"); + User user = new User("Jay", "Sridhar"); - String result = new ObjectMapper().writeValueAsString(user); + String result = new ObjectMapper().writeValueAsString(user); - // Expected to match: "2016-12-19@09:34:42.628+0000" - assertThat(from(result).getString("createdDate")) - .matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}"); + // Expected to match: "2016-12-19@09:34:42.628+0000" + assertThat(from(result).getString("createdDate")).matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}"); - // Expected to be close to current time - long now = new Date().getTime(); - assertThat(from(result).getLong("dateNum")) - .isCloseTo(now, withPercentage(10.0)); + // Expected to be close to current time + long now = new Date().getTime(); + assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0)); } } diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java index 3eeec8dcee..6fcc57faa7 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java @@ -23,11 +23,11 @@ public class JsonFilterUnitTest { // arrange Author author = new Author("Alex", "Theedom"); - FilterProvider filters = new SimpleFilterProvider() - .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); + FilterProvider filters = new SimpleFilterProvider().addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); // act - String result = new ObjectMapper().writer(filters).writeValueAsString(author); + String result = new ObjectMapper().writer(filters) + .writeValueAsString(author); // assert assertThat(from(result).getList("items")).isNull(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java index cacd11c804..e2eb4aa48a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java @@ -17,9 +17,7 @@ public class Book extends Item { private String ISBN; - @JsonFormat( - shape = JsonFormat.Shape.STRING, - pattern = "dd-MM-yyyy HH:mm:ss") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss") private Date published; private BigDecimal pages; diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java index 0fcfe94cf8..1fe217cef6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java @@ -31,10 +31,7 @@ public class JsonFormatUnitTest { String toParse = "20-12-2014 14:30:00"; Date date = df.parse(toParse); - Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") - ); + Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); book.setPublished(date); // act diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java index ebe1a69c4e..1f36b95b2a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java @@ -12,9 +12,7 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonIdentityInfo( - generator = ObjectIdGenerators.PropertyGenerator.class, - property = "id") +@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Author extends Person { private List items = new ArrayList<>(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java index 3db6d3dddb..80dd9c275e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.general.jsonidentityinfo; - import java.util.List; /** @@ -11,7 +10,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java index f252da4b1b..bad6562122 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java @@ -13,9 +13,7 @@ import java.util.UUID; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonIdentityInfo( - generator = ObjectIdGenerators.PropertyGenerator.class, - property = "id") +@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Item { private UUID id; @@ -23,7 +21,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java index 8a5b4b75e1..ea80814124 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java @@ -14,7 +14,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java index 1deae26b21..d7ee430d51 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java @@ -19,7 +19,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java index 94046f8a56..0b88e7fc47 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java @@ -21,10 +21,7 @@ public class JsonPropertyUnitTest { public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException { // arrange - Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") - ); + Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); book.configureBinding("Hardback"); // act @@ -62,12 +59,12 @@ public class JsonPropertyUnitTest { String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}"; // act - Book book = new ObjectMapper().readerFor(Book.class).readValue(result); + Book book = new ObjectMapper().readerFor(Book.class) + .readValue(result); // assert assertThat(book.coverBinding()).isEqualTo("Hardback"); } - } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java index 491f706db4..5130e037d5 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.general.jsonunwrapped; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java index 8ac10cac8b..ab609008ce 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java @@ -22,7 +22,8 @@ public class JsonViewUnitTest { Order order = new Order(120); // act - String result = new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(order); + String result = new ObjectMapper().writerWithView(Views.Internal.class) + .writeValueAsString(order); // assert assertThat(from(result).getUUID("id")).isNotNull(); @@ -49,7 +50,8 @@ public class JsonViewUnitTest { Order order = new Order(120); // act - String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(order); + String result = new ObjectMapper().writerWithView(Views.Public.class) + .writeValueAsString(order); // assert assertThat(from(result).getUUID("id")).isNotNull(); @@ -68,5 +70,4 @@ public class JsonViewUnitTest { } - } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java index 9d99d632e7..251d25a517 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.general.reference; - import java.util.List; /** @@ -11,7 +10,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java index 08bada3646..5dd66a8ca3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java @@ -21,7 +21,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java index 5bb20f7aff..95c0b35b8b 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java @@ -14,7 +14,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java index c0aece9636..7a52a69656 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java @@ -36,7 +36,7 @@ public class ReferenceUnitTest { /* Without references defined it throws StackOverflowError. Authors excluded. - + { "id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7", "firstName": "Alex", diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java index ef9d6e0e29..a3e29776a9 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java @@ -37,7 +37,7 @@ public class JsonAutoDetectUnitTest { }, "internalAudit": 1234567890 } - + Without @JsonAutoDetect { "id": "c94774d9-de8f-4244-85d5-624bd3a4567a", diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java index f85dd66764..ca4c4b751a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java @@ -28,7 +28,6 @@ public class JsonIncludeUnitTest { assertThat(from(result).getString("firstName")).isEqualTo("Alex"); assertThat(result).doesNotContain("lastName"); - /* { "id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd", diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java index a0ba23fb71..0f312ec37e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java @@ -12,29 +12,29 @@ import static org.junit.Assert.assertTrue; public class ItemIdRemovedFromUserUnitTest { @Test public void givenRemoveItemJson_whenDeserialize_shouldHaveProperClassType() throws IOException { - //given + // given Event event = new ItemIdRemovedFromUser("1", 12345567L, "item_1", 2L); ObjectMapper objectMapper = new ObjectMapper(); String eventJson = objectMapper.writeValueAsString(event); - //when + // when Event result = new ObjectMapper().readValue(eventJson, Event.class); - //then + // then assertTrue(result instanceof ItemIdRemovedFromUser); assertEquals("item_1", ((ItemIdRemovedFromUser) result).getItemId()); } @Test public void givenAdddItemJson_whenSerialize_shouldIgnoreIdPropertyFromSuperclass() throws IOException { - //given + // given Event event = new ItemIdAddedToUser("1", 12345567L, "item_1", 2L); ObjectMapper objectMapper = new ObjectMapper(); - //when + // when String eventJson = objectMapper.writeValueAsString(event); - //then + // then assertFalse(eventJson.contains("id")); } diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java index a8c1e94e9b..b5b81fa4a3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java @@ -21,12 +21,12 @@ public class SubTypeHandlingUnitTest { assertEquals("Mercedes-Benz", truck.getMake()); assertEquals("S500", truck.getModel()); } - + @Test - public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException{ + public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); - + SubTypeConstructorStructure.Car car = new SubTypeConstructorStructure.Car("Mercedes-Benz", "S500", 5, 250.0); SubTypeConstructorStructure.Truck truck = new SubTypeConstructorStructure.Truck("Isuzu", "NQR", 7500.0); diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java index b436eda6e0..02297b9ee8 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java @@ -30,8 +30,10 @@ public class TypeInfoInclusionUnitTest { String jsonDataString = mapper.writeValueAsString(serializedFleet); TypeInfoStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoStructure.Fleet.class); - assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoStructure.Car.class)); - assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoStructure.Truck.class)); + assertThat(deserializedFleet.getVehicles() + .get(0), instanceOf(TypeInfoStructure.Car.class)); + assertThat(deserializedFleet.getVehicles() + .get(1), instanceOf(TypeInfoStructure.Truck.class)); } @Test @@ -51,7 +53,9 @@ public class TypeInfoInclusionUnitTest { String jsonDataString = mapper.writeValueAsString(serializedFleet); TypeInfoAnnotatedStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoAnnotatedStructure.Fleet.class); - assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class)); - assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class)); + assertThat(deserializedFleet.getVehicles() + .get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class)); + assertThat(deserializedFleet.getVehicles() + .get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class)); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java b/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java index 14f9024d0b..a472c7af15 100644 --- a/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java +++ b/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java @@ -10,7 +10,8 @@ public class ExampleStructure { private static ObjectMapper mapper = new ObjectMapper(); static JsonNode getExampleRoot() throws IOException { - InputStream exampleInput = ExampleStructure.class.getClassLoader().getResourceAsStream("node_example.json"); + InputStream exampleInput = ExampleStructure.class.getClassLoader() + .getResourceAsStream("node_example.json"); JsonNode rootNode = mapper.readTree(exampleInput); return rootNode; } diff --git a/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java index 3539f388f9..73328f465e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java @@ -28,8 +28,10 @@ public class NodeOperationUnitTest { final JsonNode node = mapper.valueToTree(fromValue); - assertEquals(2016, node.get("id").intValue()); - assertEquals("baeldung.com", node.get("name").textValue()); + assertEquals(2016, node.get("id") + .intValue()); + assertEquals("baeldung.com", node.get("name") + .textValue()); } @Test @@ -72,12 +74,21 @@ public class NodeOperationUnitTest { public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException { final JsonNode rootNode = ExampleStructure.getExampleRoot(); final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address"); - addedNode.put("city", "Seattle").put("state", "Washington").put("country", "United States"); + addedNode.put("city", "Seattle") + .put("state", "Washington") + .put("country", "United States"); - assertFalse(rootNode.path("address").isMissingNode()); - assertEquals("Seattle", rootNode.path("address").path("city").textValue()); - assertEquals("Washington", rootNode.path("address").path("state").textValue()); - assertEquals("United States", rootNode.path("address").path("country").textValue()); + assertFalse(rootNode.path("address") + .isMissingNode()); + assertEquals("Seattle", rootNode.path("address") + .path("city") + .textValue()); + assertEquals("Washington", rootNode.path("address") + .path("state") + .textValue()); + assertEquals("United States", rootNode.path("address") + .path("country") + .textValue()); } @Test @@ -88,8 +99,12 @@ public class NodeOperationUnitTest { final JsonNode rootNode = ExampleStructure.getExampleRoot(); ((ObjectNode) rootNode).set("name", newNode); - assertFalse(rootNode.path("name").path("nick").isMissingNode()); - assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue()); + assertFalse(rootNode.path("name") + .path("nick") + .isMissingNode()); + assertEquals("cowtowncoder", rootNode.path("name") + .path("nick") + .textValue()); } @Test @@ -97,7 +112,8 @@ public class NodeOperationUnitTest { final JsonNode rootNode = ExampleStructure.getExampleRoot(); ((ObjectNode) rootNode).remove("company"); - assertTrue(rootNode.path("company").isMissingNode()); + assertTrue(rootNode.path("company") + .isMissingNode()); } } diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java index a3d0b377c6..10b22b8365 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java @@ -25,8 +25,6 @@ public class CustomCarDeserializer extends StdDeserializer { super(vc); } - - @Override public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException { final Car car = new Car(); diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java index 37bae829b7..9db09c5081 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java @@ -8,8 +8,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class CustomCarSerializer extends StdSerializer -{ +public class CustomCarSerializer extends StdSerializer { private static final long serialVersionUID = 1396140685442227917L; @@ -22,8 +21,7 @@ public class CustomCarSerializer extends StdSerializer } @Override - public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException - { + public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("model: ", car.getType()); jsonGenerator.writeEndObject(); diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java index e6da19f440..2745e4f767 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java @@ -40,7 +40,8 @@ public class JavaReadWriteJsonExampleUnitTest { final ObjectMapper objectMapper = new ObjectMapper(); final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON); assertNotNull(jsonNode); - assertThat(jsonNode.get("color").asText(), containsString("Black")); + assertThat(jsonNode.get("color") + .asText(), containsString("Black")); } @Test diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java index 4ffec72a61..fcfee98123 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java @@ -18,7 +18,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; -public class SerializationDeserializationFeatureUnitTest { +public class SerializationDeserializationFeatureUnitTest { final String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; final String JSON_CAR = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }"; final String JSON_ARRAY = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]"; diff --git a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java index 5d2ba69767..e922cf9976 100644 --- a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java @@ -53,12 +53,14 @@ public class PolymorphismUnitTest { String orderJson = "{\"type\":{\"ordertype\":\"internal\",\"id\":100,\"name\":\"directors\"}}"; // act - Order order = new ObjectMapper().readerFor(Order.class).readValue(orderJson); + Order order = new ObjectMapper().readerFor(Order.class) + .readValue(orderJson); - // assert + // assert assertThat(from(orderJson).getString("type.ordertype")).isEqualTo("internal"); assertThat(((Order.InternalType) order.getType()).name).isEqualTo("directors"); assertThat(((Order.InternalType) order.getType()).id).isEqualTo(100); - assertThat(order.getType().getClass()).isEqualTo(Order.InternalType.class); + assertThat(order.getType() + .getClass()).isEqualTo(Order.InternalType.class); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java index a68af20f15..a75e8ef831 100644 --- a/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java @@ -33,7 +33,8 @@ public class JacksonPrettyPrintUnitTest { final ObjectMapper mapper = new ObjectMapper(); try { final Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class); - System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json)); + System.out.println(mapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(json)); } catch (final IOException e) { e.printStackTrace(); } @@ -42,7 +43,8 @@ public class JacksonPrettyPrintUnitTest { static String readFile(final String path, final Charset encoding) throws IOException { final byte[] encoded = Files.readAllBytes(Paths.get(path)); - return encoding.decode(ByteBuffer.wrap(encoded)).toString(); + return encoding.decode(ByteBuffer.wrap(encoded)) + .toString(); } } 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 33aca2a1ed..6f22e2fa01 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,10 @@ public class SandboxUnitTest { testElement.setX(10); testElement.setY("adasd"); final ObjectMapper om = new ObjectMapper(); - om.setVisibility(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/serialization/JacksonMapSerializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java index 4935d35791..e67336f6f3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java @@ -14,57 +14,53 @@ import com.fasterxml.jackson.databind.ser.std.MapSerializer; public class JacksonMapSerializeUnitTest { - @JsonSerialize(keyUsing = MyPairSerializer.class) - private Map map; + @JsonSerialize(keyUsing = MyPairSerializer.class) + private Map map; - @JsonSerialize(keyUsing = MapSerializer.class) - private Map cmap; + @JsonSerialize(keyUsing = MapSerializer.class) + private Map cmap; - @JsonSerialize(keyUsing = MyPairSerializer.class) - private MyPair mapKey; + @JsonSerialize(keyUsing = MyPairSerializer.class) + private MyPair mapKey; - @JsonSerialize(keyUsing = MyPairSerializer.class) - private MyPair mapValue; + @JsonSerialize(keyUsing = MyPairSerializer.class) + private MyPair mapValue; - final ObjectMapper mapper = new ObjectMapper(); + final ObjectMapper mapper = new ObjectMapper(); - @Test - public void whenSimpleMapSerialize_thenCorrect() - throws JsonProcessingException { + @Test + public void whenSimpleMapSerialize_thenCorrect() throws JsonProcessingException { - Map map = new HashMap<>(); - map.put("key", "value"); + Map map = new HashMap<>(); + map.put("key", "value"); - final String jsonResult = mapper.writeValueAsString(map); + final String jsonResult = mapper.writeValueAsString(map); - Assert.assertEquals("{\"key\":\"value\"}", jsonResult); - } + Assert.assertEquals("{\"key\":\"value\"}", jsonResult); + } - @Test - public void whenCustomObjectStringMapSerialize_thenCorrect() - throws JsonProcessingException { + @Test + public void whenCustomObjectStringMapSerialize_thenCorrect() throws JsonProcessingException { - map = new HashMap<>(); - MyPair key = new MyPair("Abbott", "Costello"); - map.put(key, "Comedy"); + map = new HashMap<>(); + MyPair key = new MyPair("Abbott", "Costello"); + map.put(key, "Comedy"); - final String jsonResult = mapper.writeValueAsString(map); + final String jsonResult = mapper.writeValueAsString(map); - Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult); - } + Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult); + } - @Test - public void whenCustomObjectObjectMapSerialize_thenCorrect() - throws JsonProcessingException { + @Test + public void whenCustomObjectObjectMapSerialize_thenCorrect() throws JsonProcessingException { - cmap = new HashMap<>(); - mapKey = new MyPair("Abbott", "Costello"); - mapValue = new MyPair("Comedy", "1940's"); - cmap.put(mapKey, mapValue); + cmap = new HashMap<>(); + mapKey = new MyPair("Abbott", "Costello"); + mapValue = new MyPair("Comedy", "1940's"); + cmap.put(mapKey, mapValue); - final String jsonResult = mapper.writeValueAsString(cmap); + final String jsonResult = mapper.writeValueAsString(cmap); - Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", - jsonResult); - } + Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", jsonResult); + } } diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java index fa6364ff92..a003c5b526 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java @@ -48,10 +48,13 @@ public class JacksonSerializeUnitTest { module.addSerializer(new ActorJacksonSerializer(ActorJackson.class)); final ObjectMapper mapper = new ObjectMapper(); - final String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue); + final String jsonResult = mapper.registerModule(module) + .writer(new DefaultPrettyPrinter()) + .writeValueAsString(movieWithNullValue); final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class); - final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json); + final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT) + .writeValueAsString(json); Assert.assertEquals(jsonResult, expectedOutput); } diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java index 0671441d9a..f0f0913aee 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java @@ -28,7 +28,6 @@ public class JsonRawValueUnitTest { // assert assertThat(result.contains(customerConfig)); - /* { "firstName": "Alex", diff --git a/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java index 2f8cf52afb..ff22682f37 100644 --- a/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.streaming; - import com.fasterxml.jackson.core.*; import org.junit.Test; @@ -18,12 +17,12 @@ public class JacksonStreamingAPIUnitTest { @Test public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException { - //given + // given ByteArrayOutputStream stream = new ByteArrayOutputStream(); JsonFactory jfactory = new JsonFactory(); JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8); - //when + // when jGenerator.writeStartObject(); jGenerator.writeStringField("name", "Tom"); jGenerator.writeNumberField("age", 25); @@ -35,14 +34,14 @@ public class JacksonStreamingAPIUnitTest { jGenerator.writeEndObject(); jGenerator.close(); - //then + // then String json = new String(stream.toByteArray(), "UTF-8"); assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"); } @Test public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException { - //given + // given String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; JsonFactory jfactory = new JsonFactory(); JsonParser jParser = jfactory.createParser(json); @@ -51,7 +50,7 @@ public class JacksonStreamingAPIUnitTest { Integer parsedAge = null; List addresses = new LinkedList<>(); - //when + // when while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); @@ -78,7 +77,7 @@ public class JacksonStreamingAPIUnitTest { } jParser.close(); - //then + // then assertEquals(parsedName, "Tom"); assertEquals(parsedAge, (Integer) 25); assertEquals(addresses, Arrays.asList("Poland", "5th avenue")); @@ -87,7 +86,7 @@ public class JacksonStreamingAPIUnitTest { @Test public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException { - //given + // given String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; JsonFactory jfactory = new JsonFactory(); JsonParser jParser = jfactory.createParser(json); @@ -96,7 +95,7 @@ public class JacksonStreamingAPIUnitTest { Integer parsedAge = null; List addresses = new LinkedList<>(); - //when + // when while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); @@ -110,7 +109,7 @@ public class JacksonStreamingAPIUnitTest { } jParser.close(); - //then + // then assertNull(parsedName); assertEquals(parsedAge, (Integer) 25); assertTrue(addresses.isEmpty()); diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java index e544ab670a..935777bad1 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java @@ -124,7 +124,8 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { final String json = "{\"id\":1,\"theName\":\"My bean\"}"; - final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class).readValue(json); + final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class) + .readValue(json); assertEquals("My bean", bean.name); } @@ -133,7 +134,9 @@ public class JacksonAnnotationUnitTest { final String json = "{\"name\":\"My bean\"}"; final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1); - final BeanWithInject bean = new ObjectMapper().reader(inject).forType(BeanWithInject.class).readValue(json); + final BeanWithInject bean = new ObjectMapper().reader(inject) + .forType(BeanWithInject.class) + .readValue(json); assertEquals("My bean", bean.name); assertEquals(1, bean.id); } @@ -142,16 +145,19 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException { final String json = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}"; - final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class).readValue(json); + final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class) + .readValue(json); assertEquals("My bean", bean.name); - assertEquals("val2", bean.getProperties().get("attr2")); + assertEquals("val2", bean.getProperties() + .get("attr2")); } @Test public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException { final String json = "{\"id\":1,\"name\":\"My bean\"}"; - final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(json); + final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class) + .readValue(json); assertEquals("My bean", bean.getTheName()); } @@ -161,7 +167,8 @@ public class JacksonAnnotationUnitTest { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class).readValue(json); + final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class) + .readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } @@ -232,7 +239,8 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingPolymorphic_thenCorrect() throws IOException { final String json = "{\"animal\":{\"name\":\"lacy\",\"type\":\"cat\"}}"; - final Zoo zoo = new ObjectMapper().readerFor(Zoo.class).readValue(json); + final Zoo zoo = new ObjectMapper().readerFor(Zoo.class) + .readValue(json); assertEquals("lacy", zoo.animal.name); assertEquals(Zoo.Cat.class, zoo.animal.getClass()); @@ -247,7 +255,8 @@ public class JacksonAnnotationUnitTest { assertThat(result, containsString("My bean")); assertThat(result, containsString("1")); - final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(result); + final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class) + .readValue(result); assertEquals("My bean", resultBean.getTheName()); } @@ -278,7 +287,8 @@ public class JacksonAnnotationUnitTest { public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException, JsonProcessingException { final Item item = new Item(2, "book", "John"); - final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item); + final String result = new ObjectMapper().writerWithView(Views.Public.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); @@ -317,7 +327,8 @@ public class JacksonAnnotationUnitTest { final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name")); - final String result = new ObjectMapper().writer(filters).writeValueAsString(bean); + final String result = new ObjectMapper().writer(filters) + .writeValueAsString(bean); assertThat(result, containsString("My bean")); assertThat(result, not(containsString("id"))); diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java index 523b42a96c..e55ca55ac9 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java @@ -93,7 +93,8 @@ public class JacksonBidirectionRelationUnitTest { public void givenBidirectionRelation_whenDeserializingUsingIdentity_thenCorrect() throws JsonProcessingException, IOException { final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}"; - final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class).readValue(json); + final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class) + .readValue(json); assertEquals(2, item.id); assertEquals("book", item.itemName); @@ -104,7 +105,8 @@ public class JacksonBidirectionRelationUnitTest { public void givenBidirectionRelation_whenUsingCustomDeserializer_thenCorrect() throws JsonProcessingException, IOException { final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}"; - final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class).readValue(json); + final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class) + .readValue(json); assertEquals(2, item.id); assertEquals("book", item.itemName); assertEquals("John", item.owner.name); @@ -116,7 +118,8 @@ public class JacksonBidirectionRelationUnitTest { final ItemWithView item = new ItemWithView(2, "book", user); user.addItem(item); - final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item); + final String result = new ObjectMapper().writerWithView(Views.Public.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("John")); @@ -129,7 +132,8 @@ public class JacksonBidirectionRelationUnitTest { final ItemWithView item = new ItemWithView(2, "book", user); user.addItem(item); - new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(item); + new ObjectMapper().writerWithView(Views.Internal.class) + .writeValueAsString(item); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java index cd166386e6..0de3a1de82 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java @@ -66,7 +66,8 @@ public class JacksonCollectionDeserializationUnitTest { final String jsonArray = mapper.writeValueAsString(listOfDtos); // [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}] - final CollectionType javaType = mapper.getTypeFactory().constructCollectionType(List.class, MyDto.class); + final CollectionType javaType = mapper.getTypeFactory() + .constructCollectionType(List.class, MyDto.class); final List asList = mapper.readValue(jsonArray, javaType); assertThat(asList.get(0), instanceOf(MyDto.class)); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java index f713494ac8..390030d0d4 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java @@ -130,7 +130,8 @@ public class JacksonDateUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(df); - final Event event = mapper.readerFor(Event.class).readValue(json); + final Event event = mapper.readerFor(Event.class) + .readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } @@ -141,7 +142,8 @@ public class JacksonDateUnitTest { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); final ObjectMapper mapper = new ObjectMapper(); - final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class).readValue(json); + final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class) + .readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java index 4549a752eb..cd2c2925d6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java @@ -34,7 +34,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"animal\":{\"name\":\"lacy\"}}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(Zoo.class).readValue(json); + mapper.reader() + .forType(Zoo.class) + .readValue(json); } @Test @@ -42,7 +44,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"animal\":{\"name\":\"lacy\"}}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(ZooConfigured.class).readValue(json); + mapper.reader() + .forType(ZooConfigured.class) + .readValue(json); } // JsonMappingException: No serializer found for class @@ -51,7 +55,8 @@ public class JacksonExceptionsUnitTest { final UserWithPrivateFields user = new UserWithPrivateFields(1, "John"); final ObjectMapper mapper = new ObjectMapper(); - mapper.writer().writeValueAsString(user); + mapper.writer() + .writeValueAsString(user); } @Test @@ -61,7 +66,8 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - final String result = mapper.writer().writeValueAsString(user); + final String result = mapper.writer() + .writeValueAsString(user); assertThat(result, containsString("John")); } @@ -71,7 +77,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"id\":1,\"name\":\"John\"}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(User.class).readValue(json); + mapper.reader() + .forType(User.class) + .readValue(json); } @Test @@ -79,7 +87,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"id\":1,\"name\":\"John\"}"; final ObjectMapper mapper = new ObjectMapper(); - final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + final com.baeldung.jackson.dtos.User user = mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); assertEquals("John", user.name); } @@ -91,7 +101,9 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -101,7 +113,9 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); - final UserWithRoot user = mapper.reader().forType(UserWithRoot.class).readValue(json); + final UserWithRoot user = mapper.reader() + .forType(UserWithRoot.class) + .readValue(json); assertEquals("John", user.name); } @@ -111,7 +125,9 @@ public class JacksonExceptionsUnitTest { final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -119,8 +135,10 @@ public class JacksonExceptionsUnitTest { final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]"; final ObjectMapper mapper = new ObjectMapper(); - final List users = mapper.reader().forType(new TypeReference>() { - }).readValue(json); + final List users = mapper.reader() + .forType(new TypeReference>() { + }) + .readValue(json); assertEquals(2, users.size()); } @@ -131,7 +149,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -141,7 +161,9 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + final com.baeldung.jackson.dtos.User user = mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); assertEquals("John", user.name); } @@ -151,7 +173,9 @@ public class JacksonExceptionsUnitTest { final String json = "{'id':1,'name':'John'}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -162,7 +186,9 @@ public class JacksonExceptionsUnitTest { factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); final ObjectMapper mapper = new ObjectMapper(factory); - final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + final com.baeldung.jackson.dtos.User user = mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); assertEquals("John", user.name); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java index dd2690876c..7930195ab0 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java @@ -28,7 +28,8 @@ public class JacksonJsonViewUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); - final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(user); + final String result = mapper.writerWithView(Views.Public.class) + .writeValueAsString(user); assertThat(result, containsString("John")); assertThat(result, not(containsString("1"))); @@ -39,7 +40,8 @@ public class JacksonJsonViewUnitTest { final Item item = new Item(2, "book", "John"); final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(item); + final String result = mapper.writerWithView(Views.Public.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); @@ -52,7 +54,8 @@ public class JacksonJsonViewUnitTest { final Item item = new Item(2, "book", "John"); final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writerWithView(Views.Internal.class).writeValueAsString(item); + final String result = mapper.writerWithView(Views.Internal.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); @@ -66,7 +69,9 @@ public class JacksonJsonViewUnitTest { final ObjectMapper mapper = new ObjectMapper(); - final User user = mapper.readerWithView(Views.Public.class).forType(User.class).readValue(json); + final User user = mapper.readerWithView(Views.Public.class) + .forType(User.class) + .readValue(json); assertEquals(1, user.getId()); assertEquals("John", user.getName()); } @@ -79,7 +84,8 @@ public class JacksonJsonViewUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializerFactory(serializerFactory); - final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(user); + final String result = mapper.writerWithView(Views.Public.class) + .writeValueAsString(user); assertThat(result, containsString("JOHN")); assertThat(result, containsString("1")); } 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 bc0e24cdfa..4230420132 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -109,7 +109,8 @@ public class JacksonSerializationIgnoreUnitTest { final MyDtoWithFilter dtoObject = new MyDtoWithFilter(); dtoObject.setIntValue(12); - final String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject); + final String dtoAsString = mapper.writer(filters) + .writeValueAsString(dtoObject); assertThat(dtoAsString, not(containsString("intValue"))); assertThat(dtoAsString, containsString("booleanValue")); @@ -123,7 +124,8 @@ public class JacksonSerializationIgnoreUnitTest { @Override public final void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider provider, final PropertyWriter writer) throws Exception { if (include(writer)) { - if (!writer.getName().equals("intValue")) { + if (!writer.getName() + .equals("intValue")) { writer.serializeAsField(pojo, jgen, provider); return; } @@ -153,7 +155,8 @@ public class JacksonSerializationIgnoreUnitTest { dtoObject.setIntValue(-1); final ObjectMapper mapper = new ObjectMapper(); - final String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject); + final String dtoAsString = mapper.writer(filters) + .writeValueAsString(dtoObject); assertThat(dtoAsString, not(containsString("intValue"))); assertThat(dtoAsString, containsString("booleanValue")); @@ -229,7 +232,8 @@ public class JacksonSerializationIgnoreUnitTest { @Test public final void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); - mapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer()); + mapper.getSerializerProvider() + .setNullKeySerializer(new MyDtoNullKeySerializer()); final MyDto dtoObject1 = new MyDto(); dtoObject1.setStringValue("dtoObjectString1"); @@ -251,7 +255,8 @@ public class JacksonSerializationIgnoreUnitTest { @Test public final void givenAllowingMapObjectOneNullKey_whenWritingMapObjectWithTwoNullKeys_thenOverride() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); - mapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer()); + mapper.getSerializerProvider() + .setNullKeySerializer(new MyDtoNullKeySerializer()); final MyDto dtoObject1 = new MyDto(); dtoObject1.setStringValue("dtoObject1String"); diff --git a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java index 529c05ddcc..52bb65033f 100644 --- a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java @@ -25,8 +25,10 @@ public class RestLoaderRequestDeserializer extends StdDeserializer clazz = Class.forName(className); diff --git a/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java index b5e3449c68..adb0fe0413 100644 --- a/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java @@ -35,8 +35,7 @@ public class XMLSerializeDeserializeUnitTest { @Test public void whenJavaGotFromXmlStr_thenCorrect() throws IOException { XmlMapper xmlMapper = new XmlMapper(); - SimpleBean value = xmlMapper.readValue( - "12", SimpleBean.class); + SimpleBean value = xmlMapper.readValue("12", SimpleBean.class); assertTrue(value.getX() == 1 && value.getY() == 2); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java index d54fa5a7c1..774eb69889 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java @@ -16,7 +16,7 @@ import com.baeldung.autoconfiguration.MySQLAutoconfiguration; * @ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class}) * */ -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) @ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components") public class SpringBootAnnotatedApp { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java index 44030f440b..580498e831 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java @@ -5,7 +5,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) @ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") public class SpringBootPlainApp { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java index bad39c52c4..95b4a1a191 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java @@ -9,9 +9,8 @@ public class AttrListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { - servletContextEvent - .getServletContext() - .setAttribute("servlet-context-attr", "test"); + servletContextEvent.getServletContext() + .setAttribute("servlet-context-attr", "test"); System.out.println("context init"); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java index 3419cd0eaf..a2995d1532 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java @@ -16,9 +16,8 @@ public class EchoServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try { - Path path = File - .createTempFile("echo", "tmp") - .toPath(); + Path path = File.createTempFile("echo", "tmp") + .toPath(); Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); Files.copy(path, response.getOutputStream()); Files.delete(path); diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java index dc2368c5b2..650dae9806 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java @@ -18,9 +18,8 @@ public class HelloFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { - servletResponse - .getOutputStream() - .print(filterConfig.getInitParameter("msg")); + servletResponse.getOutputStream() + .print(filterConfig.getInitParameter("msg")); filterChain.doFilter(servletRequest, servletResponse); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java index aeae7aecc9..3c27b8416f 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java @@ -8,22 +8,22 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")}) +@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello") }) public class HelloServlet extends HttpServlet { private ServletConfig servletConfig; @Override - public void init(ServletConfig servletConfig){ + public void init(ServletConfig servletConfig) { this.servletConfig = servletConfig; } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { try { - response - .getOutputStream() - .write(servletConfig.getInitParameter("msg").getBytes()); + response.getOutputStream() + .write(servletConfig.getInitParameter("msg") + .getBytes()); } catch (IOException e) { e.printStackTrace(); } diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java index 09f387902d..6dd127a8c3 100644 --- a/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java +++ b/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java @@ -92,21 +92,19 @@ public class MySQLAutoconfiguration { static class HibernateCondition extends SpringBootCondition { - private static final String[] CLASS_NAMES = { - "org.hibernate.ejb.HibernateEntityManager", - "org.hibernate.jpa.HibernateEntityManager" }; + private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" }; @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate"); return Arrays.stream(CLASS_NAMES) - .filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) - .map(className -> ConditionOutcome - .match(message.found("class").items(Style.NORMAL, className))) - .findAny() - .orElseGet(() -> ConditionOutcome - .noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); + .filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) + .map(className -> ConditionOutcome.match(message.found("class") + .items(Style.NORMAL, className))) + .findAny() + .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes") + .items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); } } diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java b/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java index fa411bc0b8..3d07e515b1 100644 --- a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java +++ b/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java @@ -2,6 +2,6 @@ package com.baeldung.autoconfiguration.example; import org.springframework.data.jpa.repository.JpaRepository; -public interface MyUserRepository extends JpaRepository{ - +public interface MyUserRepository extends JpaRepository { + } diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java index cd015e6554..6cc3f72cf6 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java @@ -10,13 +10,13 @@ public class Application { public static void main(String[] args) { applicationContext = SpringApplication.run(Application.class, args); - + displayAllBeans(); } - + public static void displayAllBeans() { String[] allBeanNames = applicationContext.getBeanDefinitionNames(); - for(String beanName : allBeanNames) { + for (String beanName : allBeanNames) { System.out.println(beanName); } } diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java index 9f483b18d1..26f0a60bff 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java @@ -12,9 +12,9 @@ import com.baeldung.displayallbeans.service.FooService; public class FooController { @Autowired private FooService fooService; - - @RequestMapping(value="/displayallbeans") - public String getHeaderAndBody (Map model){ + + @RequestMapping(value = "/displayallbeans") + public String getHeaderAndBody(Map model) { model.put("header", fooService.getHeader()); model.put("message", fooService.getBody()); return "displayallbeans"; diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java index e29f18c94a..1f3c15ee0e 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java @@ -4,15 +4,13 @@ import org.springframework.stereotype.Service; @Service public class FooService { - + public String getHeader() { return "Display All Beans"; } - + public String getBody() { - return "This is a sample application that displays all beans " - + "in Spring IoC container using ListableBeanFactory interface " - + "and Spring Boot Actuators."; + return "This is a sample application that displays all beans " + "in Spring IoC container using ListableBeanFactory interface " + "and Spring Boot Actuators."; } - + } diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java index d89dfc5fcd..a2b171c156 100644 --- a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java +++ b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java @@ -18,7 +18,10 @@ public class PersistenceConfig { @Bean public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("schema-expressions.sql").addScript("data-expressions.sql").build(); + EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2) + .addScript("schema-expressions.sql") + .addScript("data-expressions.sql") + .build(); return db; } } diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java index 9d379cbc09..84c96feb92 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java +++ b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java @@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class FailureAnalyzerApplication { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java index 2bbae8944a..04c7fdff9a 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java +++ b/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java @@ -4,8 +4,7 @@ import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; -public class MyBeanNotOfRequiredTypeFailureAnalyzer - extends AbstractFailureAnalyzer { +public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnalyzer { @Override protected FailureAnalysis analyze(Throwable rootFailure, BeanNotOfRequiredTypeException cause) { @@ -13,16 +12,15 @@ public class MyBeanNotOfRequiredTypeFailureAnalyzer } private String getDescription(BeanNotOfRequiredTypeException ex) { - return String.format("The bean %s could not be injected as %s because it is of type %s", - ex.getBeanName(), - ex.getRequiredType().getName(), - ex.getActualType().getName()); + return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType() + .getName(), + ex.getActualType() + .getName()); } private String getAction(BeanNotOfRequiredTypeException ex) { - return String.format("Consider creating a bean with name %s of type %s", - ex.getBeanName(), - ex.getRequiredType().getName()); + return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType() + .getName()); } } diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java index c077692edb..4655e36f83 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java @@ -8,7 +8,7 @@ import org.springframework.core.io.ClassPathResource; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude = MySQLAutoconfiguration.class) public class CommitIdApplication { public static void main(String[] args) { SpringApplication.run(CommitIdApplication.class, args); diff --git a/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java index a7a864cf96..c5ae8bd772 100644 --- a/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java +++ b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java @@ -23,7 +23,7 @@ public class GraphqlConfiguration { } return new PostDao(posts); } - + @Bean public AuthorDao authorDao() { List authors = new ArrayList<>(); @@ -36,12 +36,12 @@ public class GraphqlConfiguration { } return new AuthorDao(authors); } - + @Bean public PostResolver postResolver(AuthorDao authorDao) { return new PostResolver(authorDao); } - + @Bean public AuthorResolver authorResolver(PostDao postDao) { return new AuthorResolver(postDao); diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java index 0e16e3c8b7..5ccc80dad1 100644 --- a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java +++ b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java @@ -13,7 +13,8 @@ public class Mutation implements GraphQLMutationResolver { public Post writePost(String title, String text, String category, String author) { Post post = new Post(); - post.setId(UUID.randomUUID().toString()); + post.setId(UUID.randomUUID() + .toString()); post.setTitle(title); post.setText(text); post.setCategory(category); diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java index b743eb4b61..ca56437392 100644 --- a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java +++ b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java @@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class InternationalizationApp { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/intro/App.java b/spring-boot/src/main/java/com/baeldung/intro/App.java index 9553d814ac..b865deea29 100644 --- a/spring-boot/src/main/java/com/baeldung/intro/App.java +++ b/spring-boot/src/main/java/com/baeldung/intro/App.java @@ -5,11 +5,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) -public class App -{ - public static void main( String[] args ) - { +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +public class App { + public static void main(String[] args) { SpringApplication.run(App.class, args); } } diff --git a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java index 9109b0a292..2a82e58829 100644 --- a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java +++ b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java @@ -7,12 +7,12 @@ import org.springframework.web.bind.annotation.RestController; public class HomeController { @RequestMapping("/") - public String root(){ + public String root() { return "Index Page"; } - + @RequestMapping("/local") - public String local(){ + public String local() { return "/local"; } } diff --git a/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java b/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java index 8965e2f013..c8461e4efc 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java @@ -7,7 +7,7 @@ import org.springframework.boot.web.support.SpringBootServletInitializer; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class ApplicationMain extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java index 3d6a10c2ac..2d8298338c 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java @@ -26,10 +26,13 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter { configurer.enable(); } - @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); + registry.addResourceHandler("/resources/**") + .addResourceLocations("/resources/") + .setCachePeriod(3600) + .resourceChain(true) + .addResolver(new PathResourceResolver()); } @Bean 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 aa70bac777..bbab95c41f 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 @@ -10,7 +10,8 @@ import org.springframework.core.env.ConfigurableEnvironment; @Configuration @ComponentScan(basePackages = { "com.baeldung.servlets.*" }) -@PropertySource("classpath:custom.properties") public class PropertySourcesLoader { +@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/servlets/servlets/javaee/AnnotationServlet.java b/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java index b50a7d5454..358ff5af2d 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java @@ -7,14 +7,13 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -@WebServlet(name = "AnnotationServlet", - description = "Example Servlet Using Annotations", - urlPatterns = { "/annotationservlet" }) +@WebServlet(name = "AnnotationServlet", description = "Example Servlet Using Annotations", urlPatterns = { "/annotationservlet" }) public class AnnotationServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response); + request.getRequestDispatcher("/annotationservlet.jsp") + .forward(request, response); } } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java b/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java index 7ea7c11fde..4e75fc6411 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java @@ -2,6 +2,6 @@ package com.baeldung.toggle; import org.springframework.data.repository.CrudRepository; -public interface EmployeeRepository extends CrudRepository{ +public interface EmployeeRepository extends CrudRepository { } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java index 245415a2a0..b05ec2bf52 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java @@ -10,13 +10,15 @@ import org.togglz.core.context.FeatureContext; public enum MyFeatures implements Feature { - @Label("Employee Management Feature") @EnabledByDefault @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, - parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"), - @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") }) + @Label("Employee Management Feature") + @EnabledByDefault + @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"), + @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") }) EMPLOYEE_MANAGEMENT_FEATURE; public boolean isActive() { - return FeatureContext.getFeatureManager().isActive(this); + return FeatureContext.getFeatureManager() + .isActive(this); } } diff --git a/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java index b63ada9eee..4b00247c4a 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java +++ b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java @@ -8,13 +8,13 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) -@ComponentScan(basePackages="com.baeldung.utils") +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@ComponentScan(basePackages = "com.baeldung.utils") public class UtilsApplication { - @RolesAllowed("*") - public static void main(String[] args) { - SpringApplication.run(UtilsApplication.class, args); - } + @RolesAllowed("*") + public static void main(String[] args) { + SpringApplication.run(UtilsApplication.class, args); + } } diff --git a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java index 7b4827cdf2..7c66391bd2 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java +++ b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java @@ -13,37 +13,37 @@ import org.springframework.web.util.WebUtils; @Controller public class UtilsController { - @GetMapping("/utils") - public String webUtils(Model model) { - return "utils"; - } - - @PostMapping("/setParam") - public String post(HttpServletRequest request, Model model) { - String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); - -// Long param = ServletRequestUtils.getLongParameter(request, "param",1L); -// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); -// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); -// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); -// int param = ServletRequestUtils.getIntParameter(request, "param", 100); - -// try { -// ServletRequestUtils.getRequiredStringParameter(request, "param"); -// } catch (ServletRequestBindingException e) { -// e.printStackTrace(); -// } - - WebUtils.setSessionAttribute(request, "parameter", param); - model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter")); - return "utils"; - } - - @GetMapping("/other") - public String other(HttpServletRequest request, Model model) { - String param = (String) WebUtils.getSessionAttribute(request, "parameter"); - model.addAttribute("parameter", param); - return "other"; - } - + @GetMapping("/utils") + public String webUtils(Model model) { + return "utils"; + } + + @PostMapping("/setParam") + public String post(HttpServletRequest request, Model model) { + String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); + + // Long param = ServletRequestUtils.getLongParameter(request, "param",1L); + // boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); + // double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); + // float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); + // int param = ServletRequestUtils.getIntParameter(request, "param", 100); + + // try { + // ServletRequestUtils.getRequiredStringParameter(request, "param"); + // } catch (ServletRequestBindingException e) { + // e.printStackTrace(); + // } + + WebUtils.setSessionAttribute(request, "parameter", param); + model.addAttribute("parameter", "You set: " + (String) WebUtils.getSessionAttribute(request, "parameter")); + return "utils"; + } + + @GetMapping("/other") + public String other(HttpServletRequest request, Model model) { + String param = (String) WebUtils.getSessionAttribute(request, "parameter"); + model.addAttribute("parameter", param); + return "other"; + } + } diff --git a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java index 44d48f5f8f..8704b42166 100644 --- a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java +++ b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class WebjarsdemoApplication { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/org/baeldung/Application.java b/spring-boot/src/main/java/org/baeldung/Application.java index 8b49f4d6ab..1c1e466afc 100644 --- a/spring-boot/src/main/java/org/baeldung/Application.java +++ b/spring-boot/src/main/java/org/baeldung/Application.java @@ -6,7 +6,7 @@ import org.springframework.context.ApplicationContext; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class Application { private static ApplicationContext applicationContext; diff --git a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java index 5de4134739..cb269f77f1 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java @@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; import org.springframework.context.annotation.Import; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) @Import(GraphqlConfiguration.class) public class DemoApplication { diff --git a/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java b/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java index 235fd43299..4ff8e9fdd4 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java +++ b/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java @@ -10,11 +10,11 @@ public class FooService { @Autowired private FooRepository fooRepository; - + public Foo getFooWithId(Integer id) throws Exception { return fooRepository.findOne(id); } - + public Foo getFooWithName(String name) { return fooRepository.findByName(name); } diff --git a/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java b/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java index 1f008440e6..e03b859eab 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java +++ b/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java @@ -1,13 +1,13 @@ package org.baeldung.boot.exceptions; -public class CommonException extends RuntimeException{ +public class CommonException extends RuntimeException { /** * */ private static final long serialVersionUID = 3080004140659213332L; - public CommonException(String message){ + public CommonException(String message) { super(message); } } diff --git a/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java b/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java index 68ef3fa389..0b04bd2759 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java +++ b/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java @@ -1,13 +1,13 @@ package org.baeldung.boot.exceptions; -public class FooNotFoundException extends RuntimeException{ +public class FooNotFoundException extends RuntimeException { /** * */ private static final long serialVersionUID = 9042200028456133589L; - public FooNotFoundException(String message){ + public FooNotFoundException(String message) { super(message); } } diff --git a/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java b/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java index ac8a8fe429..d373e25b85 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java +++ b/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java @@ -21,7 +21,6 @@ public class Foo implements Serializable { this.name = name; } - public Foo(Integer id, String name) { super(); this.id = id; diff --git a/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java b/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java index 834fa342e2..d400c3bf9e 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java +++ b/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java @@ -18,7 +18,7 @@ public class FooController { public Foo getFooWithId(@PathVariable Integer id) throws Exception { return fooService.getFooWithId(id); } - + @GetMapping("/") public Foo getFooWithName(@RequestParam String name) throws Exception { return fooService.getFooWithName(name); diff --git a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java b/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java index 7d1ad7d899..a9e7dee0b7 100644 --- a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java +++ b/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java @@ -39,21 +39,31 @@ public class GenericEntityController { @RequestMapping("/entity/findby/{id}") public GenericEntity findById(@PathVariable Long id) { - return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get(); + return entityList.stream() + .filter(entity -> entity.getId() + .equals(id)) + .findFirst() + .get(); } @GetMapping("/entity/findbydate/{date}") public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) { - return entityList.stream().findFirst().get(); + return entityList.stream() + .findFirst() + .get(); } @GetMapping("/entity/findbymode/{mode}") public GenericEntity findByEnum(@PathVariable("mode") Modes mode) { - return entityList.stream().findFirst().get(); + return entityList.stream() + .findFirst() + .get(); } @GetMapping("/entity/findbyversion") public ResponseEntity findByVersion(@Version String version) { - return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); + return version != null ? new ResponseEntity(entityList.stream() + .findFirst() + .get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); } } diff --git a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java b/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java index 1a175aed48..68fbffda6e 100644 --- a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java +++ b/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java @@ -10,9 +10,13 @@ public class MyHealthCheck implements HealthIndicator { public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { - return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build(); + return Health.down() + .withDetail("Error Code", errorCode) + .withDetail("Description", "You custom MyHealthCheck endpoint is down") + .build(); } - return Health.up().build(); + return Health.up() + .build(); } public int check() { diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java index 2001340197..cb1b838ca4 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java @@ -21,8 +21,7 @@ public class UserCombinedSerializer { @Override public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); - jsonGenerator.writeStringField("favoriteColor", - getColorAsWebColor(user.getFavoriteColor())); + jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor())); jsonGenerator.writeEndObject(); } @@ -37,7 +36,8 @@ public class UserCombinedSerializer { public static class UserJsonDeserializer extends JsonDeserializer { @Override public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); + TreeNode treeNode = jsonParser.getCodec() + .readTree(jsonParser); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); return new User(Color.web(favoriteColor.asText())); } diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java index d18de7e3f1..a310dcba5a 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java @@ -15,7 +15,8 @@ import java.io.IOException; public class UserJsonDeserializer extends JsonDeserializer { @Override public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); + TreeNode treeNode = jsonParser.getCodec() + .readTree(jsonParser); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); return new User(Color.web(favoriteColor.asText())); } diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java index d90f662a4b..845bc3aac5 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java @@ -15,8 +15,7 @@ public class UserJsonSerializer extends JsonSerializer { @Override public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); - jsonGenerator.writeStringField("favoriteColor", - getColorAsWebColor(user.getFavoriteColor())); + jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor())); jsonGenerator.writeEndObject(); } diff --git a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java index 872426d850..2d118b0eae 100644 --- a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java @@ -20,7 +20,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @RestController -@EnableAutoConfiguration(exclude=MySQLAutoconfiguration.class) +@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class) @ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" }) public class SpringBootApplication { diff --git a/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java b/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java index 8100e61629..40f36ef924 100644 --- a/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java +++ b/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java @@ -14,7 +14,8 @@ public class MonitoringConfig { @Bean public JmxReporter jmxReporter() { - JmxReporter reporter = JmxReporter.forRegistry(registry).build(); + JmxReporter reporter = JmxReporter.forRegistry(registry) + .build(); reporter.start(); return reporter; } diff --git a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java b/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java index ed0090f8e4..6d89f7f695 100644 --- a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java +++ b/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java @@ -16,7 +16,8 @@ public class LoginServiceImpl implements LoginService { public boolean login(String userName, char[] password) { boolean success; - if (userName.equals("admin") && "secret".toCharArray().equals(password)) { + if (userName.equals("admin") && "secret".toCharArray() + .equals(password)) { counterService.increment("counter.login.success"); success = true; } else { diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java index 9f8dadbe55..c0cc669420 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java @@ -10,7 +10,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; @EntityScan(basePackageClasses = Foo.class) -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class Application { public static void main(String[] args) { System.setProperty("spring.config.name", "exception"); diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java index 83de888e5e..36d87e6dad 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -14,12 +14,14 @@ public class FooRepositoryImpl implements FooRepository { @Override public void save(Foo foo) { - sessionFactory.getCurrentSession().saveOrUpdate(foo); + sessionFactory.getCurrentSession() + .saveOrUpdate(foo); } @Override public Foo get(Integer id) { - return sessionFactory.getCurrentSession().get(Foo.class, id); + return sessionFactory.getCurrentSession() + .get(Foo.class, id); } } \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java b/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java index bcab44870b..2744c49f62 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java @@ -20,6 +20,5 @@ public class Message { public void setText(String text) { this.text = text; } - - + } diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java index 35bf1827ea..45fbf2b623 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java @@ -17,12 +17,12 @@ import java.lang.reflect.Type; * */ public class MyStompSessionHandler extends StompSessionHandlerAdapter { - + private Logger logger = Logger.getLogger(MyStompSessionHandler.class); - + @Override public void afterConnected(StompSession session, StompHeaders connectedHeaders) { - logger.info("New session established : "+session.getSessionId()); + logger.info("New session established : " + session.getSessionId()); session.subscribe("/topic/messages", this); logger.info("Subscribed to /topic/messages"); session.send("/app/chat", getSampleMessage()); @@ -41,15 +41,15 @@ public class MyStompSessionHandler extends StompSessionHandlerAdapter { @Override public void handleFrame(StompHeaders headers, Object payload) { - Message msg = (Message)payload; - logger.info("Received : "+ msg.getText()+ " from : "+msg.getFrom()); + Message msg = (Message) payload; + logger.info("Received : " + msg.getText() + " from : " + msg.getFrom()); } - + /** * A sample message instance. * @return instance of Message */ - private Message getSampleMessage(){ + private Message getSampleMessage() { Message msg = new Message(); msg.setFrom("Nicky"); msg.setText("Howdy!!"); diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java b/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java index 71f5471fb1..2bff07186d 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java @@ -19,9 +19,9 @@ public class StompClient { public static void main(String[] args) { WebSocketClient client = new StandardWebSocketClient(); WebSocketStompClient stompClient = new WebSocketStompClient(client); - + stompClient.setMessageConverter(new MappingJackson2MessageConverter()); - + StompSessionHandler sessionHandler = new MyStompSessionHandler(); stompClient.connect(URL, sessionHandler); diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 660b461ab6..b2b14f766e 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -21,7 +21,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = {"security.basic.enabled=false"}) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithServletComponentIntegrationTest { @Autowired @@ -40,9 +40,8 @@ public class SpringBootWithServletComponentIntegrationTest { FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); assertNotNull(filterRegistration); - assertTrue(filterRegistration - .getServletNameMappings() - .contains("echo servlet")); + assertTrue(filterRegistration.getServletNameMappings() + .contains("echo servlet")); } @Autowired @@ -62,7 +61,4 @@ public class SpringBootWithServletComponentIntegrationTest { assertEquals("filtering echo", responseEntity.getBody()); } - } - - diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index 31bb2ab195..a13cd250a2 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNull; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = {"security.basic.enabled=false"}) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithoutServletComponentIntegrationTest { @Autowired @@ -50,5 +50,3 @@ public class SpringBootWithoutServletComponentIntegrationTest { } } - - diff --git a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java index e886042c8d..30ba397b46 100644 --- a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AutoconfigurationApplication.class) -@EnableJpaRepositories(basePackages = {"com.baeldung.autoconfiguration.example"}) +@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) public class AutoconfigurationIntegrationTest { @Autowired diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java index 413f6980ce..8bd9c20c5e 100644 --- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@TestPropertySource(properties = {"management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false"}) +@TestPropertySource(properties = { "management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false" }) public class DisplayBeanIntegrationTest { @LocalServerPort @@ -42,8 +42,7 @@ public class DisplayBeanIntegrationTest { @Test public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception { - ResponseEntity entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.port + "/displayallbeans", String.class); + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class); then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -51,8 +50,7 @@ public class DisplayBeanIntegrationTest { @Test public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.mgt + "/springbeans", List.class); + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -60,11 +58,13 @@ public class DisplayBeanIntegrationTest { @Test public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.mgt + "/springbeans", List.class); + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); - List> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans"); - List beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList()); + List> allBeans = (List) ((Map) entity.getBody() + .get(0)).get("beans"); + List beanNamesList = allBeans.stream() + .map(x -> (String) x.get("bean")) + .collect(Collectors.toList()); assertThat(beanNamesList, hasItem("fooController")); assertThat(beanNamesList, hasItem("fooService")); diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index fa05dbab66..4856c17c7d 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -18,7 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -@TestPropertySource(properties = {"security.basic.enabled=false"}) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class AppLiveTest { @Autowired @@ -26,16 +26,18 @@ public class AppLiveTest { @Test public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("Index Page"))); + mvc.perform(MockMvcRequestBuilders.get("/") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("Index Page"))); } @Test public void getLocal() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("/local"))); + mvc.perform(MockMvcRequestBuilders.get("/local") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("/local"))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index ca6230e8f5..5b70fa3cbe 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -35,7 +35,8 @@ public class ToggleIntegrationTest { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) + .build(); } @Test @@ -45,7 +46,8 @@ public class ToggleIntegrationTest { System.setProperty("employee.feature", "false"); - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) + .andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); @@ -58,7 +60,8 @@ public class ToggleIntegrationTest { System.setProperty("employee.feature", "true"); - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) + .andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); diff --git a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java index edb40e9a1f..5a80e13791 100644 --- a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java @@ -22,18 +22,16 @@ public class UtilsControllerIntegrationTest { public void setup() { MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) - .build(); + .build(); } @Test public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { String param = "testparam"; - this.mockMvc.perform( - post("/setParam") - .param("param", param) + this.mockMvc.perform(post("/setParam").param("param", param) .sessionAttr("parameter", param)) - .andExpect(status().isOk()); + .andExpect(status().isOk()); } } diff --git a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index b52ab5b1d3..4dc4793ce2 100644 --- a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -14,8 +14,9 @@ public class MyStompSessionHandlerIntegrationTest { StompHeaders mockHeader = Mockito.mock(StompHeaders.class); MyStompSessionHandler sessionHandler = new MyStompSessionHandler(); sessionHandler.afterConnected(mockSession, mockHeader); - Mockito.verify(mockSession).subscribe("/topic/messages", sessionHandler); - Mockito.verify(mockSession).send(Mockito.anyString(), Mockito.anyObject()); + Mockito.verify(mockSession) + .subscribe("/topic/messages", sessionHandler); + Mockito.verify(mockSession) + .send(Mockito.anyString(), Mockito.anyObject()); } } - diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index c5cca3c5fb..358ba942d9 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -33,36 +33,56 @@ public class SpringBootApplicationIntegrationTest { @Before public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .build(); } @Test public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$", hasSize(4))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion") + .header("Version", "1.0.0")) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java index 10e3d6d60b..0e8a698f41 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java @@ -62,11 +62,15 @@ public class SpringBootMailIntegrationTest { } private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException { - return wiserMessage.getMimeMessage().getContent().toString().trim(); + return wiserMessage.getMimeMessage() + .getContent() + .toString() + .trim(); } private String getSubject(WiserMessage wiserMessage) throws MessagingException { - return wiserMessage.getMimeMessage().getSubject(); + return wiserMessage.getMimeMessage() + .getSubject(); } private SimpleMailMessage composeEmailMessage() { diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java index 6623a6396f..2146fc09bc 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java @@ -45,9 +45,9 @@ public class EmployeeControllerIntegrationTest { given(service.save(Mockito.anyObject())).willReturn(alex); mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(alex))) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.name", is("alex"))); + .content(JsonUtil.toJson(alex))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name", is("alex"))); verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject()); reset(service); } @@ -63,11 +63,11 @@ public class EmployeeControllerIntegrationTest { given(service.getAllEmployees()).willReturn(allEmployees); mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$", hasSize(3))) - .andExpect(jsonPath("$[0].name", is(alex.getName()))) - .andExpect(jsonPath("$[1].name", is(john.getName()))) - .andExpect(jsonPath("$[2].name", is(bob.getName()))); + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(3))) + .andExpect(jsonPath("$[0].name", is(alex.getName()))) + .andExpect(jsonPath("$[1].name", is(john.getName()))) + .andExpect(jsonPath("$[2].name", is(bob.getName()))); verify(service, VerificationModeFactory.times(1)).getAllEmployees(); reset(service); } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java index 952ff19707..ebde0e243a 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java @@ -65,7 +65,7 @@ public class EmployeeRepositoryIntegrationTest { List allEmployees = employeeRepository.findAll(); assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .containsOnly(alex.getName(), ron.getName(), bob.getName()); + .extracting(Employee::getName) + .containsOnly(alex.getName(), ron.getName(), bob.getName()); } } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java index c1d8c52eb9..9e5613ab10 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java @@ -49,11 +49,11 @@ public class EmployeeRestControllerIntegrationTest { public void whenValidInput_thenCreateEmployee() throws IOException, Exception { Employee bob = new Employee("bob"); mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(bob))); + .content(JsonUtil.toJson(bob))); List found = repository.findAll(); assertThat(found).extracting(Employee::getName) - .containsOnly("bob"); + .containsOnly("bob"); } @Test @@ -63,12 +63,12 @@ public class EmployeeRestControllerIntegrationTest { createTestEmployee("alex"); mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) - .andExpect(jsonPath("$[0].name", is("bob"))) - .andExpect(jsonPath("$[1].name", is("alex"))); + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) + .andExpect(jsonPath("$[0].name", is("bob"))) + .andExpect(jsonPath("$[1].name", is("alex"))); } private void createTestEmployee(String name) { diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java index 5bd6b34c40..9837b02df6 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java @@ -44,17 +44,17 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = Arrays.asList(john, bob, alex); Mockito.when(employeeRepository.findByName(john.getName())) - .thenReturn(john); + .thenReturn(john); Mockito.when(employeeRepository.findByName(alex.getName())) - .thenReturn(alex); + .thenReturn(alex); Mockito.when(employeeRepository.findByName("wrong_name")) - .thenReturn(null); + .thenReturn(null); Mockito.when(employeeRepository.findById(john.getId())) - .thenReturn(john); + .thenReturn(john); Mockito.when(employeeRepository.findAll()) - .thenReturn(allEmployees); + .thenReturn(allEmployees); Mockito.when(employeeRepository.findById(-99L)) - .thenReturn(null); + .thenReturn(null); } @Test @@ -62,8 +62,7 @@ public class EmployeeServiceImplIntegrationTest { String name = "alex"; Employee found = employeeService.getEmployeeByName(name); - assertThat(found.getName()) - .isEqualTo(name); + assertThat(found.getName()).isEqualTo(name); } @Test @@ -114,25 +113,25 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = employeeService.getAllEmployees(); verifyFindAllEmployeesIsCalledOnce(); assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .contains(alex.getName(), john.getName(), bob.getName()); + .extracting(Employee::getName) + .contains(alex.getName(), john.getName(), bob.getName()); } private void verifyFindByNameIsCalledOnce(String name) { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findByName(name); + .findByName(name); Mockito.reset(employeeRepository); } private void verifyFindByIdIsCalledOnce() { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findById(Mockito.anyLong()); + .findById(Mockito.anyLong()); Mockito.reset(employeeRepository); } private void verifyFindAllEmployeesIsCalledOnce() { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findAll(); + .findAll(); Mockito.reset(employeeRepository); } } diff --git a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java index 5627855aa3..0f6c13ae1f 100644 --- a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java @@ -30,7 +30,8 @@ public class DetailsServiceClientIntegrationTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")) + .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java index c1b4c8912c..ac47c5e5d9 100644 --- a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java @@ -1,6 +1,5 @@ package org.baeldung.jsoncomponent; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import javafx.scene.paint.Color; diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java index 843f5f4dcd..64698072bc 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java @@ -25,7 +25,7 @@ public class CustomAccessDeniedHandler implements AccessDeniedHandler { if (auth != null) { LOG.warn("User: " + auth.getName() + " attempted to access the protected URL: " + request.getRequestURI()); } - + response.sendRedirect(request.getContextPath() + "/accessDenied"); } diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 7331d7bb18..d9a43d48d0 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -65,9 +65,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public LogoutSuccessHandler logoutSuccessHandler() { return new CustomLogoutSuccessHandler(); } - + @Bean - public AccessDeniedHandler accessDeniedHandler(){ + public AccessDeniedHandler accessDeniedHandler() { return new CustomAccessDeniedHandler(); } diff --git a/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java b/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java index 1d7fae8b60..2b7a8ce5b9 100644 --- a/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java +++ b/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java @@ -29,65 +29,58 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @WebAppConfiguration public class RedirectionSecurityIntegrationTest { - @Autowired private WebApplicationContext context; + @Autowired + private WebApplicationContext context; - @Autowired private UserDetailsService userDetailsService; + @Autowired + private UserDetailsService userDetailsService; private MockMvc mvc; private UserDetails userDetails; @Before public void setup() { - mvc = MockMvcBuilders - .webAppContextSetup(context) - .apply(springSecurity()) - .build(); + mvc = MockMvcBuilders.webAppContextSetup(context) + .apply(springSecurity()) + .build(); userDetails = userDetailsService.loadUserByUsername("user1"); } @Test public void givenSecuredResource_whenAccessUnauthenticated_thenRequiresAuthentication() throws Exception { - mvc - .perform(get("/secured")) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("**/login")); + mvc.perform(get("/secured")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("**/login")); } @Test public void givenCredentials_whenAccessSecuredResource_thenSuccess() throws Exception { - mvc - .perform(get("/secured").with(user(userDetails))) - .andExpect(status().isOk()); + mvc.perform(get("/secured").with(user(userDetails))) + .andExpect(status().isOk()); } @Test public void givenAccessSecuredResource_whenAuthenticated_thenRedirectedBack() throws Exception { MockHttpServletRequestBuilder securedResourceAccess = get("/secured"); - MvcResult unauthenticatedResult = mvc - .perform(securedResourceAccess) - .andExpect(status().is3xxRedirection()) - .andReturn(); + MvcResult unauthenticatedResult = mvc.perform(securedResourceAccess) + .andExpect(status().is3xxRedirection()) + .andReturn(); - MockHttpSession session = (MockHttpSession) unauthenticatedResult - .getRequest() - .getSession(); - String loginUrl = unauthenticatedResult - .getResponse() - .getRedirectedUrl(); - mvc - .perform(post(loginUrl) - .param("username", userDetails.getUsername()) + MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest() + .getSession(); + String loginUrl = unauthenticatedResult.getResponse() + .getRedirectedUrl(); + mvc.perform(post(loginUrl).param("username", userDetails.getUsername()) .param("password", userDetails.getPassword()) .session(session) .with(csrf())) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("**/secured")) - .andReturn(); + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("**/secured")) + .andReturn(); - mvc - .perform(securedResourceAccess.session(session)) - .andExpect(status().isOk()); + mvc.perform(securedResourceAccess.session(session)) + .andExpect(status().isOk()); } From b00a9e61bc318514a0c13fc7b330c24734aacfc0 Mon Sep 17 00:00:00 2001 From: eugenp Date: Thu, 24 Aug 2017 15:30:33 +0300 Subject: [PATCH 33/33] formatting work --- .../config/JWTCsrfTokenRepository.java | 12 +- .../jjwtfun/config/WebSecurityConfig.java | 30 +-- .../jjwtfun/controller/BaseController.java | 5 +- .../controller/DynamicJWTController.java | 82 +++---- .../jjwtfun/controller/HomeController.java | 22 +- .../controller/StaticJWTController.java | 7 +- .../jjwtfun/model/JwtResponse.java | 3 +- .../jjwtfun/service/SecretService.java | 1 - .../StoredProcedureIntegrationTest.java | 10 +- .../controllers/ELSampleBean.java | 21 +- .../dao/UserManagementDAOImpl.java | 2 - .../OperationIntegrationTest.java | 23 +- .../jsonpath/introduction/ServiceTest.java | 27 ++- .../test/java/fast_json/FastJsonUnitTest.java | 39 ++- json/src/test/java/fast_json/Person.java | 5 +- .../jsoup/JsoupParserIntegrationTest.java | 57 +++-- .../java/com/baeldung/AssertionUnitTest.java | 34 +-- .../java/com/baeldung/AssumptionUnitTest.java | 5 +- .../com/baeldung/DynamicTestsExample.java | 98 ++++---- .../test/java/com/baeldung/EmployeesTest.java | 6 +- .../java/com/baeldung/ExceptionUnitTest.java | 28 +-- .../test/java/com/baeldung/FirstUnitTest.java | 15 +- .../baeldung/JUnit5NewFeaturesUnitTest.java | 52 ++-- .../src/test/java/com/baeldung/LiveTest.java | 39 +-- .../com/baeldung/RepeatedTestExample.java | 12 +- .../test/java/com/baeldung/StringUtils.java | 12 +- .../test/java/com/baeldung/TestLauncher.java | 6 +- .../EmployeeDaoParameterResolver.java | 4 +- .../baeldung/extensions/LoggingExtension.java | 4 +- .../junit5/AssertionsExampleTest.java | 7 +- .../param/InvalidPersonParameterResolver.java | 75 +++--- .../test/java/com/baeldung/param/Person.java | 48 ++-- .../com/baeldung/param/PersonValidator.java | 222 +++++++++--------- .../baeldung/param/PersonValidatorTest.java | 152 ++++++------ .../param/ValidPersonParameterResolver.java | 77 +++--- .../java/com/baeldung/suites/AllTests.java | 2 +- 36 files changed, 628 insertions(+), 616 deletions(-) diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java index bf88b8aff1..4462c012e3 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java @@ -16,7 +16,8 @@ import java.util.UUID; public class JWTCsrfTokenRepository implements CsrfTokenRepository { - private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName().concat(".CSRF_TOKEN"); + private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName() + .concat(".CSRF_TOKEN"); private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class); private byte[] secret; @@ -27,10 +28,12 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository { @Override public CsrfToken generateToken(HttpServletRequest request) { - String id = UUID.randomUUID().toString().replace("-", ""); + String id = UUID.randomUUID() + .toString() + .replace("-", ""); Date now = new Date(); - Date exp = new Date(System.currentTimeMillis() + (1000*30)); // 30 seconds + Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds String token = Jwts.builder() .setId(id) @@ -50,8 +53,7 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository { if (session != null) { session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME); } - } - else { + } else { HttpSession session = request.getSession(); session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token); } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java index 94e2c6ddc5..687a827448 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java @@ -30,23 +30,18 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { SecretService secretService; // ordered so we can use binary search below - private String[] ignoreCsrfAntMatchers = { - "/dynamic-builder-compress", - "/dynamic-builder-general", - "/dynamic-builder-specific", - "/set-secrets" - }; + private String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" }; @Override protected void configure(HttpSecurity http) throws Exception { - http - .addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class) + http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class) .csrf() - .csrfTokenRepository(jwtCsrfTokenRepository) - .ignoringAntMatchers(ignoreCsrfAntMatchers) - .and().authorizeRequests() - .antMatchers("/**") - .permitAll(); + .csrfTokenRepository(jwtCsrfTokenRepository) + .ignoringAntMatchers(ignoreCsrfAntMatchers) + .and() + .authorizeRequests() + .antMatchers("/**") + .permitAll(); } private class JwtCsrfValidatorFilter extends OncePerRequestFilter { @@ -58,13 +53,12 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { CsrfToken token = (CsrfToken) request.getAttribute("_csrf"); if ( - // only care if it's a POST - "POST".equals(request.getMethod()) && - // ignore if the request path is in our list + // only care if it's a POST + "POST".equals(request.getMethod()) && + // ignore if the request path is in our list Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 && // make sure we have a token - token != null - ) { + token != null) { // CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired try { Jwts.parser() diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java index e1e195c6ab..3e2309d43c 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java @@ -11,12 +11,13 @@ import org.springframework.web.bind.annotation.ResponseStatus; public class BaseController { @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler({SignatureException.class, MalformedJwtException.class, JwtException.class}) + @ExceptionHandler({ SignatureException.class, MalformedJwtException.class, JwtException.class }) public JwtResponse exception(Exception e) { JwtResponse response = new JwtResponse(); response.setStatus(JwtResponse.Status.ERROR); response.setMessage(e.getMessage()); - response.setExceptionType(e.getClass().getName()); + response.setExceptionType(e.getClass() + .getName()); return response; } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java index c03c63dd80..3d157827d1 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java @@ -27,25 +27,19 @@ public class DynamicJWTController extends BaseController { @RequestMapping(value = "/dynamic-builder-general", method = POST) public JwtResponse dynamicBuilderGeneric(@RequestBody Map claims) throws UnsupportedEncodingException { - String jws = Jwts.builder() + String jws = Jwts.builder() .setClaims(claims) - .signWith( - SignatureAlgorithm.HS256, - secretService.getHS256SecretBytes() - ) + .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); } @RequestMapping(value = "/dynamic-builder-compress", method = POST) public JwtResponse dynamicBuildercompress(@RequestBody Map claims) throws UnsupportedEncodingException { - String jws = Jwts.builder() + String jws = Jwts.builder() .setClaims(claims) .compressWith(CompressionCodecs.DEFLATE) - .signWith( - SignatureAlgorithm.HS256, - secretService.getHS256SecretBytes() - ) + .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); } @@ -56,36 +50,36 @@ public class DynamicJWTController extends BaseController { claims.forEach((key, value) -> { switch (key) { - case "iss": - ensureType(key, value, String.class); - builder.setIssuer((String) value); - break; - case "sub": - ensureType(key, value, String.class); - builder.setSubject((String) value); - break; - case "aud": - ensureType(key, value, String.class); - builder.setAudience((String) value); - break; - case "exp": - ensureType(key, value, Long.class); - builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); - break; - case "nbf": - ensureType(key, value, Long.class); - builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); - break; - case "iat": - ensureType(key, value, Long.class); - builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); - break; - case "jti": - ensureType(key, value, String.class); - builder.setId((String) value); - break; - default: - builder.claim(key, value); + case "iss": + ensureType(key, value, String.class); + builder.setIssuer((String) value); + break; + case "sub": + ensureType(key, value, String.class); + builder.setSubject((String) value); + break; + case "aud": + ensureType(key, value, String.class); + builder.setAudience((String) value); + break; + case "exp": + ensureType(key, value, Long.class); + builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); + break; + case "nbf": + ensureType(key, value, Long.class); + builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); + break; + case "iat": + ensureType(key, value, Long.class); + builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); + break; + case "jti": + ensureType(key, value, String.class); + builder.setId((String) value); + break; + default: + builder.claim(key, value); } }); @@ -95,13 +89,11 @@ public class DynamicJWTController extends BaseController { } private void ensureType(String registeredClaim, Object value, Class expectedType) { - boolean isCorrectType = - expectedType.isInstance(value) || - expectedType == Long.class && value instanceof Integer; + boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer; if (!isCorrectType) { - String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + - registeredClaim + "', but got value: " + value + " of type: " + value.getClass().getCanonicalName(); + String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass() + .getCanonicalName(); throw new JwtException(msg); } } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java index 57cd14385e..00bc1fb386 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java @@ -11,22 +11,16 @@ public class HomeController { @RequestMapping("/") public String home(HttpServletRequest req) { String requestUrl = getUrl(req); - return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + - " http " + requestUrl + "/\n\tThis usage message\n\n" + - " http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + - " http POST " + requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + - " http POST " + requestUrl + "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + - " http POST " + requestUrl + "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + - " http " + requestUrl + "/parser?jwt=\n\tParse passed in JWT\n\n" + - " http " + requestUrl + "/parser-enforce?jwt=\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" + - " http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" + - " http " + requestUrl + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + - " http POST " + requestUrl + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application."; + return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + " http " + requestUrl + "/\n\tThis usage message\n\n" + " http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + " http POST " + + requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + " http POST " + requestUrl + + "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + " http POST " + requestUrl + + "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + " http " + requestUrl + "/parser?jwt=\n\tParse passed in JWT\n\n" + " http " + requestUrl + + "/parser-enforce?jwt=\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" + " http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" + " http " + requestUrl + + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + " http POST " + requestUrl + + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application."; } private String getUrl(HttpServletRequest req) { - return req.getScheme() + "://" + - req.getServerName() + - ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort()); + return req.getScheme() + "://" + req.getServerName() + ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort()); } } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java index 83f5336978..efafa4b1b7 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java @@ -30,12 +30,9 @@ public class StaticJWTController extends BaseController { .setSubject("msilverman") .claim("name", "Micah Silverman") .claim("scope", "admins") - .setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT) + .setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT) .setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT) - .signWith( - SignatureAlgorithm.HS256, - secretService.getHS256SecretBytes() - ) + .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java index 491f003289..a18cad7e71 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java @@ -16,7 +16,8 @@ public class JwtResponse { SUCCESS, ERROR } - public JwtResponse() {} + public JwtResponse() { + } public JwtResponse(String jwt) { this.jwt = jwt; diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java index 4311afa592..0165d10c83 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java @@ -61,7 +61,6 @@ public class SecretService { return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue())); } - public Map refreshSecrets() { SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256); secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded())); diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java index c93d59fe30..c0fb5485aa 100644 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java +++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java @@ -50,13 +50,17 @@ public class StoredProcedureIntegrationTest { public void findCarsByYearNamedProcedure() { final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure"); final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015); - storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + storedProcedure.getResultList() + .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); } @Test public void findCarsByYearNoNamed() { - final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015); - storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class) + .registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN) + .setParameter(1, 2015); + storedProcedure.getResultList() + .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); } @AfterClass diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java index 16d9f80d89..abc1399f88 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java @@ -27,18 +27,22 @@ public class ELSampleBean { @PostConstruct public void init() { pageCounter = randomIntGen.nextInt(); - FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() { - @Override - public void contextCreated(ELContextEvent evt) { - evt.getELContext().getImportHandler().importClass("com.baeldung.springintegration.controllers.ELSampleBean"); - } - }); + FacesContext.getCurrentInstance() + .getApplication() + .addELContextListener(new ELContextListener() { + @Override + public void contextCreated(ELContextEvent evt) { + evt.getELContext() + .getImportHandler() + .importClass("com.baeldung.springintegration.controllers.ELSampleBean"); + } + }); } public void save() { } - + public static String constantField() { return constantField; } @@ -48,7 +52,8 @@ public class ELSampleBean { } public Long multiplyValue(LambdaExpression expr) { - Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter); + Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance() + .getELContext(), pageCounter); return theResult; } diff --git a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java index 56cbdd7b88..d135fba2b7 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java +++ b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java @@ -1,6 +1,5 @@ package com.baeldung.springintegration.dao; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; @@ -34,5 +33,4 @@ public class UserManagementDAOImpl implements UserManagementDAO { public UserManagementDAOImpl() { } - } diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java index 855f524dbe..7728d2dad6 100644 --- a/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java @@ -18,8 +18,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class OperationIntegrationTest { - private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json"); - private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); + private InputStream jsonInputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("intro_api.json"); + private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z") + .next(); @Test public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() { @@ -38,21 +41,27 @@ public class OperationIntegrationTest { @Test public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() { - Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(20.00)); - List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensiveFilter); + Filter expensiveFilter = Filter.filter(Criteria.where("price") + .gt(20.00)); + List> expensive = JsonPath.parse(jsonDataSourceString) + .read("$['book'][?]", expensiveFilter); predicateUsageAssertionHelper(expensive); } @Test public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() { - Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class).get("price").toString()) > 20.00; - List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate); + Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class) + .get("price") + .toString()) > 20.00; + List> expensive = JsonPath.parse(jsonDataSourceString) + .read("$['book'][?]", expensivePredicate); predicateUsageAssertionHelper(expensive); } @Test public void givenJsonPathWithInlinePredicate_whenReading_thenCorrect() { - List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?(@['price'] > $['price range']['medium'])]"); + List> expensive = JsonPath.parse(jsonDataSourceString) + .read("$['book'][?(@['price'] > $['price range']['medium'])]"); predicateUsageAssertionHelper(expensive); } diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java index d5cfa50e80..067e5cf8ce 100644 --- a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java @@ -18,12 +18,16 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class ServiceTest { - private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json"); - private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); + private InputStream jsonInputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("intro_service.json"); + private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z") + .next(); @Test public void givenId_whenRequestingRecordData_thenSucceed() { - Object dataObject = JsonPath.parse(jsonString).read("$[?(@.id == 2)]"); + Object dataObject = JsonPath.parse(jsonString) + .read("$[?(@.id == 2)]"); String dataString = dataObject.toString(); assertThat(dataString, containsString("2")); @@ -33,8 +37,10 @@ public class ServiceTest { @Test public void givenStarring_whenRequestingMovieTitle_thenSucceed() { - List> dataList = JsonPath.parse(jsonString).read("$[?('Eva Green' in @['starring'])]"); - String title = (String) dataList.get(0).get("title"); + List> dataList = JsonPath.parse(jsonString) + .read("$[?('Eva Green' in @['starring'])]"); + String title = (String) dataList.get(0) + .get("title"); assertEquals("Casino Royale", title); } @@ -59,8 +65,12 @@ public class ServiceTest { Arrays.sort(revenueArray); int highestRevenue = revenueArray[revenueArray.length - 1]; - Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build(); - List pathList = JsonPath.using(pathConfiguration).parse(jsonString).read("$[?(@['box office'] == " + highestRevenue + ")]"); + Configuration pathConfiguration = Configuration.builder() + .options(Option.AS_PATH_LIST) + .build(); + List pathList = JsonPath.using(pathConfiguration) + .parse(jsonString) + .read("$[?(@['box office'] == " + highestRevenue + ")]"); Map dataRecord = context.read(pathList.get(0)); String title = dataRecord.get("title"); @@ -83,7 +93,8 @@ public class ServiceTest { long latestTime = dateArray[dateArray.length - 1]; List> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]"); - String title = (String) finalDataList.get(0).get("title"); + String title = (String) finalDataList.get(0) + .get("title"); assertEquals("Spectre", title); } diff --git a/json/src/test/java/fast_json/FastJsonUnitTest.java b/json/src/test/java/fast_json/FastJsonUnitTest.java index e37f443387..6fcf1e398a 100644 --- a/json/src/test/java/fast_json/FastJsonUnitTest.java +++ b/json/src/test/java/fast_json/FastJsonUnitTest.java @@ -32,11 +32,7 @@ public class FastJsonUnitTest { @Test public void whenJavaList_thanConvertToJsonCorrect() { String personJsonFormat = JSON.toJSONString(listOfPersons); - assertEquals( - personJsonFormat, - "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" - + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" - + "\"24/07/2016\"}]"); + assertEquals(personJsonFormat, "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" + "\"24/07/2016\"}]"); } @Test @@ -44,8 +40,10 @@ public class FastJsonUnitTest { String personJsonFormat = JSON.toJSONString(listOfPersons.get(0)); Person newPerson = JSON.parseObject(personJsonFormat, Person.class); assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute - assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName()); - assertEquals(newPerson.getLastName(), listOfPersons.get(0).getLastName()); + assertEquals(newPerson.getFirstName(), listOfPersons.get(0) + .getFirstName()); + assertEquals(newPerson.getLastName(), listOfPersons.get(0) + .getLastName()); } @Test @@ -58,18 +56,13 @@ public class FastJsonUnitTest { jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12"); jsonArray.add(jsonObject); } - assertEquals( - jsonArray.toString(), - "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" - + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," - + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]"); + assertEquals(jsonArray.toString(), "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]"); } @Test public void givenContextFilter_whenJavaObject_thanJsonCorrect() { ContextValueFilter valueFilter = new ContextValueFilter() { - public Object process(BeanContext context, Object object, - String name, Object value) { + public Object process(BeanContext context, Object object, String name, Object value) { if (name.equals("DATE OF BIRTH")) { return "NOT TO DISCLOSE"; } @@ -87,18 +80,16 @@ public class FastJsonUnitTest { public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() { NameFilter formatName = new NameFilter() { public String process(Object object, String name, Object value) { - return name.toLowerCase().replace(" ", "_"); + return name.toLowerCase() + .replace(" ", "_"); } }; - SerializeConfig.getGlobalInstance().addFilter(Person.class, formatName); - String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, - "yyyy-MM-dd"); - assertEquals( - jsonOutput, - "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," - + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" - + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]"); + SerializeConfig.getGlobalInstance() + .addFilter(Person.class, formatName); + String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd"); + assertEquals(jsonOutput, "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]"); // resetting custom serializer - SerializeConfig.getGlobalInstance().put(Person.class, null); + SerializeConfig.getGlobalInstance() + .put(Person.class, null); } } diff --git a/json/src/test/java/fast_json/Person.java b/json/src/test/java/fast_json/Person.java index 0eac58cdfd..3d772348a4 100644 --- a/json/src/test/java/fast_json/Person.java +++ b/json/src/test/java/fast_json/Person.java @@ -32,10 +32,9 @@ public class Person { @Override public String toString() { - return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" - + firstName + ", dateOfBirth=" + dateOfBirth + "]"; + return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + firstName + ", dateOfBirth=" + dateOfBirth + "]"; } - + public int getAge() { return age; } diff --git a/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java index dadd57b0ed..ee39f2550f 100644 --- a/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java +++ b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java @@ -20,13 +20,15 @@ public class JsoupParserIntegrationTest { @Before public void setUp() throws IOException { - doc = Jsoup.connect("https://spring.io/blog").get(); + doc = Jsoup.connect("https://spring.io/blog") + .get(); } @Test public void loadDocument404() throws IOException { try { - doc = Jsoup.connect("https://spring.io/will-not-be-found").get(); + doc = Jsoup.connect("https://spring.io/will-not-be-found") + .get(); } catch (HttpStatusException ex) { assertEquals(404, ex.getStatusCode()); } @@ -35,13 +37,13 @@ public class JsoupParserIntegrationTest { @Test public void loadDocumentCustomized() throws IOException { doc = Jsoup.connect("https://spring.io/blog") - .userAgent("Mozilla") - .timeout(5000) - .cookie("cookiename", "val234") - .cookie("anothercookie", "ilovejsoup") - .referrer("http://google.com") - .header("headersecurity", "xyz123") - .get(); + .userAgent("Mozilla") + .timeout(5000) + .cookie("cookiename", "val234") + .cookie("anothercookie", "ilovejsoup") + .referrer("http://google.com") + .header("headersecurity", "xyz123") + .get(); } @Test @@ -77,10 +79,13 @@ public class JsoupParserIntegrationTest { @Test public void examplesExtracting() { - Element firstArticle = doc.select("article").first(); - Element timeElement = firstArticle.select("time").first(); + Element firstArticle = doc.select("article") + .first(); + Element timeElement = firstArticle.select("time") + .first(); String dateTimeOfFirstArticle = timeElement.attr("datetime"); - Element sectionDiv = firstArticle.select("section div").first(); + Element sectionDiv = firstArticle.select("section div") + .first(); String sectionDivText = sectionDiv.text(); String articleHtml = firstArticle.html(); String outerHtml = firstArticle.outerHtml(); @@ -88,24 +93,30 @@ public class JsoupParserIntegrationTest { @Test public void examplesModifying() { - Element firstArticle = doc.select("article").first(); - Element timeElement = firstArticle.select("time").first(); - Element sectionDiv = firstArticle.select("section div").first(); + Element firstArticle = doc.select("article") + .first(); + Element timeElement = firstArticle.select("time") + .first(); + Element sectionDiv = firstArticle.select("section div") + .first(); String dateTimeOfFirstArticle = timeElement.attr("datetime"); timeElement.attr("datetime", "2016-12-16 15:19:54.3"); sectionDiv.text("foo bar"); - firstArticle.select("h2").html("
"); + firstArticle.select("h2") + .html("
"); - Element link = new Element(Tag.valueOf("a"), "") - .text("Checkout this amazing website!") - .attr("href", "http://baeldung.com") - .attr("target", "_blank"); + Element link = new Element(Tag.valueOf("a"), "").text("Checkout this amazing website!") + .attr("href", "http://baeldung.com") + .attr("target", "_blank"); firstArticle.appendChild(link); - doc.select("li.navbar-link").remove(); - firstArticle.select("img").remove(); + doc.select("li.navbar-link") + .remove(); + firstArticle.select("img") + .remove(); - assertTrue(doc.html().contains("http://baeldung.com")); + assertTrue(doc.html() + .contains("http://baeldung.com")); } } diff --git a/junit5/src/test/java/com/baeldung/AssertionUnitTest.java b/junit5/src/test/java/com/baeldung/AssertionUnitTest.java index 504931b3d7..6fefd4e06d 100644 --- a/junit5/src/test/java/com/baeldung/AssertionUnitTest.java +++ b/junit5/src/test/java/com/baeldung/AssertionUnitTest.java @@ -6,23 +6,23 @@ import org.junit.jupiter.api.Test; public class AssertionUnitTest { - @Test - public void testConvertToDoubleThrowException() { - String age = "eighteen"; - assertThrows(NumberFormatException.class, () -> { - convertToInt(age); - }); + @Test + public void testConvertToDoubleThrowException() { + String age = "eighteen"; + assertThrows(NumberFormatException.class, () -> { + convertToInt(age); + }); - assertThrows(NumberFormatException.class, () -> { - convertToInt(age); - }); - } - - private static Integer convertToInt(String str) { - if (str == null) { - return null; - } - return Integer.valueOf(str); - } + assertThrows(NumberFormatException.class, () -> { + convertToInt(age); + }); + } + + private static Integer convertToInt(String str) { + if (str == null) { + return null; + } + return Integer.valueOf(str); + } } diff --git a/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java b/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java index afeee642eb..7d67d93486 100644 --- a/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java +++ b/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java @@ -24,9 +24,6 @@ public class AssumptionUnitTest { @Test void assumptionThat() { String someString = "Just a string"; - assumingThat( - someString.equals("Just a string"), - () -> assertEquals(2 + 2, 4) - ); + assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4)); } } diff --git a/junit5/src/test/java/com/baeldung/DynamicTestsExample.java b/junit5/src/test/java/com/baeldung/DynamicTestsExample.java index fd6bb3e0a8..b684f3603f 100644 --- a/junit5/src/test/java/com/baeldung/DynamicTestsExample.java +++ b/junit5/src/test/java/com/baeldung/DynamicTestsExample.java @@ -24,40 +24,33 @@ public class DynamicTestsExample { @TestFactory Collection dynamicTestsWithCollection() { - return Arrays.asList( - DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), - DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); + return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); } - + @TestFactory Iterable dynamicTestsWithIterable() { - return Arrays.asList( - DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), - DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); + return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); } - + @TestFactory Iterator dynamicTestsWithIterator() { - return Arrays.asList( - DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), - DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))) - .iterator(); + return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))) + .iterator(); } - + @TestFactory Stream dynamicTestsFromIntStream() { - return IntStream.iterate(0, n -> n + 2).limit(10).mapToObj( - n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0))); + return IntStream.iterate(0, n -> n + 2) + .limit(10) + .mapToObj(n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0))); } - + @TestFactory Stream dynamicTestsFromStream() { // sample input and output - List inputList = - Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); - List outputList = - Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); + List inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); + List outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); // input generator that generates inputs using inputList Iterator inputGenerator = inputList.iterator(); @@ -75,57 +68,56 @@ public class DynamicTestsExample { // combine everything and return a Stream of DynamicTest return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor); } - + @TestFactory Stream dynamicTestsFromStreamInJava8() { - + DomainNameResolver resolver = new DomainNameResolver(); - - List inputList = - Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); - List outputList = - Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); - - return inputList.stream().map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> { - int id = inputList.indexOf(dom); - assertEquals(outputList.get(id), resolver.resolveDomain(dom)); - })); - + + List inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); + List outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); + + return inputList.stream() + .map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> { + int id = inputList.indexOf(dom); + assertEquals(outputList.get(id), resolver.resolveDomain(dom)); + })); + } @TestFactory Stream dynamicTestsForEmployeeWorkflows() { - List inputList = - Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John")); - + List inputList = Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John")); + EmployeeDao dao = new EmployeeDao(); - Stream saveEmployeeStream = inputList.stream().map(emp -> - DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> { - Employee returned = dao.save(emp.getId()); - assertEquals(returned.getId(), emp.getId()); - })); - - Stream saveEmployeeWithFirstNameStream - = inputList.stream().filter(emp -> !emp.getFirstName().isEmpty()) + Stream saveEmployeeStream = inputList.stream() + .map(emp -> DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> { + Employee returned = dao.save(emp.getId()); + assertEquals(returned.getId(), emp.getId()); + })); + + Stream saveEmployeeWithFirstNameStream = inputList.stream() + .filter(emp -> !emp.getFirstName() + .isEmpty()) .map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> { - Employee returned = dao.save(emp.getId(), emp.getFirstName()); - assertEquals(returned.getId(), emp.getId()); - assertEquals(returned.getFirstName(), emp.getFirstName()); - })); - + Employee returned = dao.save(emp.getId(), emp.getFirstName()); + assertEquals(returned.getId(), emp.getId()); + assertEquals(returned.getFirstName(), emp.getFirstName()); + })); + return Stream.concat(saveEmployeeStream, saveEmployeeWithFirstNameStream); } - + class DomainNameResolver { - + private Map ipByDomainName = new HashMap<>(); - + DomainNameResolver() { this.ipByDomainName.put("www.somedomain.com", "154.174.10.56"); this.ipByDomainName.put("www.anotherdomain.com", "211.152.104.132"); this.ipByDomainName.put("www.yetanotherdomain.com", "178.144.120.156"); } - + public String resolveDomain(String domainName) { return ipByDomainName.get(domainName); } diff --git a/junit5/src/test/java/com/baeldung/EmployeesTest.java b/junit5/src/test/java/com/baeldung/EmployeesTest.java index 1a6da37d72..71bb52284b 100644 --- a/junit5/src/test/java/com/baeldung/EmployeesTest.java +++ b/junit5/src/test/java/com/baeldung/EmployeesTest.java @@ -33,12 +33,14 @@ public class EmployeesTest { public void whenAddEmployee_thenGetEmployee() throws SQLException { Employee emp = new Employee(1, "john"); employeeDao.add(emp); - assertEquals(1, employeeDao.findAll().size()); + assertEquals(1, employeeDao.findAll() + .size()); } @Test public void whenGetEmployees_thenEmptyList() throws SQLException { - assertEquals(0, employeeDao.findAll().size()); + assertEquals(0, employeeDao.findAll() + .size()); } public void setLogger(Logger logger) { diff --git a/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java b/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java index 6ec1a4b7bd..bd57f5b3cb 100644 --- a/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java +++ b/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java @@ -7,19 +7,19 @@ import org.junit.jupiter.api.Test; public class ExceptionUnitTest { - @Test - void shouldThrowException() { - Throwable exception = assertThrows(UnsupportedOperationException.class, () -> { - throw new UnsupportedOperationException("Not supported"); - }); - assertEquals(exception.getMessage(), "Not supported"); - } + @Test + void shouldThrowException() { + Throwable exception = assertThrows(UnsupportedOperationException.class, () -> { + throw new UnsupportedOperationException("Not supported"); + }); + assertEquals(exception.getMessage(), "Not supported"); + } - @Test - void assertThrowsException() { - String str = null; - assertThrows(IllegalArgumentException.class, () -> { - Integer.valueOf(str); - }); - } + @Test + void assertThrowsException() { + String str = null; + assertThrows(IllegalArgumentException.class, () -> { + Integer.valueOf(str); + }); + } } diff --git a/junit5/src/test/java/com/baeldung/FirstUnitTest.java b/junit5/src/test/java/com/baeldung/FirstUnitTest.java index 78c563cf82..c47a70e52f 100644 --- a/junit5/src/test/java/com/baeldung/FirstUnitTest.java +++ b/junit5/src/test/java/com/baeldung/FirstUnitTest.java @@ -13,21 +13,16 @@ class FirstUnitTest { @Test void lambdaExpressions() { List numbers = Arrays.asList(1, 2, 3); - assertTrue(numbers - .stream() - .mapToInt(i -> i) - .sum() > 5, "Sum should be greater than 5"); + assertTrue(numbers.stream() + .mapToInt(i -> i) + .sum() > 5, "Sum should be greater than 5"); } @Disabled("test to show MultipleFailuresError") @Test void groupAssertions() { - int[] numbers = {0, 1, 2, 3, 4}; - assertAll("numbers", - () -> assertEquals(numbers[0], 1), - () -> assertEquals(numbers[3], 3), - () -> assertEquals(numbers[4], 1) - ); + int[] numbers = { 0, 1, 2, 3, 4 }; + assertAll("numbers", () -> assertEquals(numbers[0], 1), () -> assertEquals(numbers[3], 3), () -> assertEquals(numbers[4], 1)); } @Test diff --git a/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java index a4dfd610a1..311c62f425 100644 --- a/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java +++ b/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java @@ -13,38 +13,38 @@ import org.junit.jupiter.api.Test; //@RunWith(JUnitPlatform.class) public class JUnit5NewFeaturesUnitTest { - private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); + private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); - @BeforeAll - static void setup() { - log.info("@BeforeAll - executes once before all test methods in this class"); - } + @BeforeAll + static void setup() { + log.info("@BeforeAll - executes once before all test methods in this class"); + } - @BeforeEach - void init() { - log.info("@BeforeEach - executes before each test method in this class"); - } + @BeforeEach + void init() { + log.info("@BeforeEach - executes before each test method in this class"); + } - @DisplayName("Single test successful") - @Test - void testSingleSuccessTest() { - log.info("Success"); + @DisplayName("Single test successful") + @Test + void testSingleSuccessTest() { + log.info("Success"); - } + } - @Test - @Disabled("Not implemented yet.") - void testShowSomething() { - } + @Test + @Disabled("Not implemented yet.") + void testShowSomething() { + } - @AfterEach - void tearDown() { - log.info("@AfterEach - executed after each test method."); - } + @AfterEach + void tearDown() { + log.info("@AfterEach - executed after each test method."); + } - @AfterAll - static void done() { - log.info("@AfterAll - executed after all test methods."); - } + @AfterAll + static void done() { + log.info("@AfterAll - executed after all test methods."); + } } diff --git a/junit5/src/test/java/com/baeldung/LiveTest.java b/junit5/src/test/java/com/baeldung/LiveTest.java index e0e267da0b..c23eeb5afa 100644 --- a/junit5/src/test/java/com/baeldung/LiveTest.java +++ b/junit5/src/test/java/com/baeldung/LiveTest.java @@ -12,27 +12,28 @@ import org.junit.jupiter.api.TestFactory; public class LiveTest { - private List in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No")); - private List out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie")); + private List in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No")); + private List out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie")); - @TestFactory - public Stream translateDynamicTestsFromStream() { + @TestFactory + public Stream translateDynamicTestsFromStream() { - return in.stream().map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> { - int id = in.indexOf(word); - assertEquals(out.get(id), translate(word)); - })); - } + return in.stream() + .map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> { + int id = in.indexOf(word); + assertEquals(out.get(id), translate(word)); + })); + } - private String translate(String word) { - if ("Hello".equalsIgnoreCase(word)) { - return "Cześć"; - } else if ("Yes".equalsIgnoreCase(word)) { - return "Tak"; - } else if ("No".equalsIgnoreCase(word)) { - return "Nie"; - } - return "Error"; - } + private String translate(String word) { + if ("Hello".equalsIgnoreCase(word)) { + return "Cześć"; + } else if ("Yes".equalsIgnoreCase(word)) { + return "Tak"; + } else if ("No".equalsIgnoreCase(word)) { + return "Nie"; + } + return "Error"; + } } diff --git a/junit5/src/test/java/com/baeldung/RepeatedTestExample.java b/junit5/src/test/java/com/baeldung/RepeatedTestExample.java index 8674e01e5d..749d7064bc 100644 --- a/junit5/src/test/java/com/baeldung/RepeatedTestExample.java +++ b/junit5/src/test/java/com/baeldung/RepeatedTestExample.java @@ -14,36 +14,36 @@ public class RepeatedTestExample { void beforeEachTest() { System.out.println("Before Each Test"); } - + @AfterEach void afterEachTest() { System.out.println("After Each Test"); System.out.println("====================="); } - + @RepeatedTest(3) void repeatedTest(TestInfo testInfo) { System.out.println("Executing repeated test"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME) void repeatedTestWithLongName() { System.out.println("Executing repeated test with long name"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME) void repeatedTestWithShortName() { System.out.println("Executing repeated test with long name"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(value = 3, name = "Custom name {currentRepetition}/{totalRepetitions}") void repeatedTestWithCustomDisplayName() { assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(3) void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) { System.out.println("Repetition #" + repetitionInfo.getCurrentRepetition()); diff --git a/junit5/src/test/java/com/baeldung/StringUtils.java b/junit5/src/test/java/com/baeldung/StringUtils.java index c1852113bc..227f131876 100644 --- a/junit5/src/test/java/com/baeldung/StringUtils.java +++ b/junit5/src/test/java/com/baeldung/StringUtils.java @@ -2,10 +2,10 @@ package com.baeldung; public final class StringUtils { - public static Double convertToDouble(String str) { - if (str == null) { - return null; - } - return Double.valueOf(str); - } + public static Double convertToDouble(String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } } diff --git a/junit5/src/test/java/com/baeldung/TestLauncher.java b/junit5/src/test/java/com/baeldung/TestLauncher.java index d0354e19a9..f9766d2bd9 100644 --- a/junit5/src/test/java/com/baeldung/TestLauncher.java +++ b/junit5/src/test/java/com/baeldung/TestLauncher.java @@ -25,13 +25,15 @@ public class TestLauncher { //@formatter:on - TestPlan plan = LauncherFactory.create().discover(request); + TestPlan plan = LauncherFactory.create() + .discover(request); Launcher launcher = LauncherFactory.create(); SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener(); launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener }); launcher.execute(request); - summaryGeneratingListener.getSummary().printTo(new PrintWriter(System.out)); + summaryGeneratingListener.getSummary() + .printTo(new PrintWriter(System.out)); } } diff --git a/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java b/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java index 2626266454..4e6931a65d 100644 --- a/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java +++ b/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java @@ -12,7 +12,9 @@ public class EmployeeDaoParameterResolver implements ParameterResolver { @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { - return parameterContext.getParameter().getType().equals(EmployeeJdbcDao.class); + return parameterContext.getParameter() + .getType() + .equals(EmployeeJdbcDao.class); } @Override diff --git a/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java b/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java index 437c5c24de..930018d576 100644 --- a/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java +++ b/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java @@ -10,7 +10,9 @@ public class LoggingExtension implements TestInstancePostProcessor { @Override public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception { Logger logger = LogManager.getLogger(testInstance.getClass()); - testInstance.getClass().getMethod("setLogger", Logger.class).invoke(testInstance, logger); + testInstance.getClass() + .getMethod("setLogger", Logger.class) + .invoke(testInstance, logger); } } diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java b/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java index 642b7371de..3cfe4c59f5 100644 --- a/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java +++ b/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java @@ -30,9 +30,10 @@ public class AssertionsExampleTest { List list = Arrays.asList(1, 2, 3); Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0) - .intValue(), 1), - () -> Assertions.assertEquals(list.get(1) - .intValue(), 2), + .intValue(), 1), () -> Assertions.assertEquals( + list.get(1) + .intValue(), + 2), () -> Assertions.assertEquals(list.get(2) .intValue(), 3)); } diff --git a/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java index 67bd47a44a..73ae2e08b7 100644 --- a/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java +++ b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java @@ -9,42 +9,51 @@ 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 - }; + /** + * 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)]; + @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; } - 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; + @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; } - return ret; - } } diff --git a/junit5/src/test/java/com/baeldung/param/Person.java b/junit5/src/test/java/com/baeldung/param/Person.java index 65333b5e56..7095036bd4 100644 --- a/junit5/src/test/java/com/baeldung/param/Person.java +++ b/junit5/src/test/java/com/baeldung/param/Person.java @@ -9,35 +9,35 @@ package com.baeldung.param; */ public class Person { - private Long id; - private String lastName; - private String firstName; + private Long id; + private String lastName; + private String firstName; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Person setId(Long id) { - this.id = id; - return this; - } + public Person setId(Long id) { + this.id = id; + return this; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public Person setLastName(String lastName) { - this.lastName = lastName; - return this; - } + public Person setLastName(String lastName) { + this.lastName = lastName; + return this; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public Person setFirstName(String firstName) { - this.firstName = firstName; - return this; - } + 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 index 0219169aab..fbf596be8a 100644 --- a/junit5/src/test/java/com/baeldung/param/PersonValidator.java +++ b/junit5/src/test/java/com/baeldung/param/PersonValidator.java @@ -11,132 +11,122 @@ import java.util.Arrays; */ 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 { + /** + * 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. */ - private static final long serialVersionUID = -134518049431883102L; - - // Probably should implement some more constructors, but don't want - /// to tarnish the lesson... + 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; + } /** - * The one and only way to create this checked exception. + * 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 message - * The message accompanying the exception. Should be meaningful. + * @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 ValidationException(String message) { - super(message); - + 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; } - } - - 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)!"); + /** + * 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; } - 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 index 09ab03b811..cd6f2b7e4f 100644 --- a/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java +++ b/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java @@ -15,88 +15,88 @@ import org.junit.runner.RunWith; @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. + * Nested class, uses ExtendWith + * {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver} + * to feed Test methods with "good" data. */ - @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()); - } + @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()); + } + } + } /** - * 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. + * Nested class, uses ExtendWith + * {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver} + * to feed Test methods with "bad" data. */ - @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 + @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)); + } + } - } - - /** - * 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 index abb97586eb..10d958b83c 100644 --- a/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java +++ b/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java @@ -9,42 +9,53 @@ 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 - }; + /** + * 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)]; + @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; } - 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; + @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; } - return ret; - } } diff --git a/junit5/src/test/java/com/baeldung/suites/AllTests.java b/junit5/src/test/java/com/baeldung/suites/AllTests.java index 69f28373eb..29452efc3d 100644 --- a/junit5/src/test/java/com/baeldung/suites/AllTests.java +++ b/junit5/src/test/java/com/baeldung/suites/AllTests.java @@ -6,7 +6,7 @@ import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) @SelectPackages("com.baeldung") -//@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) +// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) public class AllTests { }