From db6811406c1c8474d06798b1947729d7b45443e0 Mon Sep 17 00:00:00 2001 From: juan Date: Sun, 8 Oct 2017 23:59:55 -0300 Subject: [PATCH 01/13] Minor format changes. --- .../java/com/baeldung/jsonb/JsonbTest.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java index 4caab86f7d..a65e171e6e 100644 --- a/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java +++ b/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java @@ -24,13 +24,28 @@ public class JsonbTest { public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); String jsonPerson = jsonb.toJson(person); - assertTrue("{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}".equals(jsonPerson)); + //// @formatter:off + String jsonExpected = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); } @Test public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); - String jsonPerson = "{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}"; + // @formatter:off + String jsonPerson = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on assertTrue(jsonb.fromJson(jsonPerson, Person.class) .equals(person)); } From 7b4d644d1ebac4a3a9c5b7091f3f3f09d9a2d372 Mon Sep 17 00:00:00 2001 From: Muhammed Almas Date: Wed, 8 Nov 2017 22:34:59 +0530 Subject: [PATCH 02/13] BAEL-1296 Prime numbers till 'n'. (#2954) --- .../com/baeldung/prime/PrimeGenerator.java | 59 +++++++++++++++++++ .../baeldung/prime/PrimeGeneratorTest.java | 28 +++++++++ 2 files changed, 87 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java create mode 100644 core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java diff --git a/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java b/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java new file mode 100644 index 0000000000..750807ce77 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java @@ -0,0 +1,59 @@ +package com.baeldung.prime; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PrimeGenerator { + public static List sieveOfEratosthenes(int n) { + final boolean prime[] = new boolean[n + 1]; + Arrays.fill(prime, true); + + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * 2; i <= n; i += p) + prime[i] = false; + } + } + + final List primes = new LinkedList<>(); + for (int i = 2; i <= n; i++) { + if (prime[i]) + primes.add(i); + } + return primes; + } + + public static List primeNumbersBruteForce(int max) { + final List primeNumbers = new LinkedList(); + for (int i = 2; i <= max; i++) { + if (isPrimeBruteForce(i)) { + primeNumbers.add(i); + } + } + return primeNumbers; + } + + private static boolean isPrimeBruteForce(int x) { + for (int i = 2; i < x; i++) { + if (x % i == 0) { + return false; + } + } + return true; + } + + public static List primeNumbersTill(int max) { + return IntStream.rangeClosed(2, max) + .filter(x -> isPrime(x)) + .boxed() + .collect(Collectors.toList()); + } + + private static boolean isPrime(int x) { + return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) + .allMatch(n -> x % n != 0); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java new file mode 100644 index 0000000000..e53e1c183e --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java @@ -0,0 +1,28 @@ +package com.baeldung.prime; + +import static com.baeldung.prime.PrimeGenerator.*; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PrimeGeneratorTest { + @Test + public void whenBruteForced_returnsSuccessfully() { + final List primeNumbers = primeNumbersBruteForce(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenOptimized_returnsSuccessfully() { + final List primeNumbers = primeNumbersTill(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenSieveOfEratosthenes_returnsSuccessfully() { + final List primeNumbers = sieveOfEratosthenes(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } +} From f499f86cc89eb9277625183532782cc2a3cfc384 Mon Sep 17 00:00:00 2001 From: fpistritto Date: Thu, 9 Nov 2017 04:13:42 +0100 Subject: [PATCH 03/13] BAEL-1272: Java String Pool (#2952) * Add StringPool unit tests * Refactor tests to use AssertJ instead of JUnit asserts --- .../stringpool/StringPoolUnitTest.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java new file mode 100644 index 0000000000..4bbf63f87e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.stringpool; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class StringPoolUnitTest { + + @Test + public void whenCreatingConstantStrings_thenTheirAddressesAreEqual() { + String constantString1 = "Baeldung"; + String constantString2 = "Baeldung"; + + assertThat(constantString1).isSameAs(constantString2); + } + + @Test + public void whenCreatingStringsWithTheNewOperator_thenTheirAddressesAreDifferent() { + String newString1 = new String("Baeldung"); + String newString2 = new String("Baeldung"); + + assertThat(newString1).isNotSameAs(newString2); + } + + @Test + public void whenComparingConstantAndNewStrings_thenTheirAddressesAreDifferent() { + String constantString = "Baeldung"; + String newString = new String("Baeldung"); + + assertThat(constantString).isNotSameAs(newString); + } + + @Test + public void whenInterningAStringWithIdenticalValueToAnother_thenTheirAddressesAreEqual() { + String constantString = "interned Baeldung"; + String newString = new String("interned Baeldung"); + + assertThat(constantString).isNotSameAs(newString); + + String internedString = newString.intern(); + + assertThat(constantString).isSameAs(internedString); + } +} From 8df4293b6830dccaa3457b54d21351afc345c23a Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Thu, 9 Nov 2017 07:14:05 -0300 Subject: [PATCH 04/13] Implementing the Template Method Pattern in Java - BAEL-1289 (#2976) * Initial Commit * Remove unit test methods * Remove duplicated unit test methods --- .../templatemethodpattern/model/Computer.java | 25 ++-- .../model/HighEndComputer.java | 38 +++--- .../model/StandardComputer.java | 33 ++--- .../TemplateMethodPatternTest.java | 116 ++++++------------ 4 files changed, 74 insertions(+), 138 deletions(-) diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java index c5d1a2cde8..f18485428f 100644 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java @@ -1,33 +1,32 @@ package com.baeldung.templatemethodpattern.model; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; import java.util.HashMap; import java.util.Map; public abstract class Computer { protected Map computerParts = new HashMap<>(); + protected List moterboardSetupStatus = new ArrayList<>(); public final void buildComputer() { - addMotherboard(); + addMotherboard(); + setupMotherboard(); addProcessor(); - addMemory(); - addHardDrive(); - addGraphicCard(); - addSoundCard(); } - public abstract void addProcessor(); - public abstract void addMotherboard(); - public abstract void addMemory(); + public abstract void setupMotherboard(); - public abstract void addHardDrive(); - - public abstract void addGraphicCard(); - - public abstract void addSoundCard(); + public abstract void addProcessor(); + public List getMotherboardSetupStatus() { + return moterboardSetupStatus; + } + public Map getComputerParts() { return computerParts; } diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java index 11baeca6f7..8d80e1e108 100644 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java @@ -3,32 +3,24 @@ package com.baeldung.templatemethodpattern.model; public class HighEndComputer extends Computer { @Override - public void addProcessor() { - computerParts.put("Processor", "High End Processor"); + public void addMotherboard() { + computerParts.put("Motherboard", "High-end Motherboard"); } - + + @Override + public void setupMotherboard() { + moterboardSetupStatus.add("Screwing the high-end motherboard to the case."); + moterboardSetupStatus.add("Pluging in the power supply connectors."); + moterboardSetupStatus.forEach(step -> System.out.println(step)); + } + + @Override + public void addProcessor() { + computerParts.put("Processor", "High-end Processor"); + } + @Override public void addMotherboard() { computerParts.put("Motherboard", "High End Motherboard"); } - - @Override - public void addMemory() { - computerParts.put("Memory", "16GB"); - } - - @Override - public void addHardDrive() { - computerParts.put("Hard Drive", "2TB Hard Drive"); - } - - @Override - public void addGraphicCard() { - computerParts.put("Graphic Card", "High End Graphic Card"); - } - - @Override - public void addSoundCard() { - computerParts.put("Sound Card", "High End Sound Card"); - } } diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java index 22ff370203..8410ad88ee 100644 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java @@ -1,7 +1,18 @@ package com.baeldung.templatemethodpattern.model; public class StandardComputer extends Computer { - + + public void addMotherboard() { + computerParts.put("Motherboard", "Standard Motherboard"); + } + + @Override + public void setupMotherboard() { + moterboardSetupStatus.add("Screwing the standard motherboard to the case."); + moterboardSetupStatus.add("Pluging in the power supply connectors."); + moterboardSetupStatus.forEach(step -> System.out.println(step)); + } + @Override public void addProcessor() { computerParts.put("Processor", "Standard Processor"); @@ -11,24 +22,4 @@ public class StandardComputer extends Computer { public void addMotherboard() { computerParts.put("Motherboard", "Standard Motherboard"); } - - @Override - public void addMemory() { - computerParts.put("Memory", "8GB"); - } - - @Override - public void addHardDrive() { - computerParts.put("Hard Drive", "1TB Hard Drive"); - } - - @Override - public void addGraphicCard() { - computerParts.put("Graphic Card", "Standard Graphic Card"); - } - - @Override - public void addSoundCard() { - computerParts.put("Sound Card", "Standard Sound Card"); - } } diff --git a/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java b/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java index afe66883ac..526873c4f2 100644 --- a/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java +++ b/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java @@ -3,11 +3,12 @@ package com.baeldung.templatemethodpatterntest; import com.baeldung.templatemethodpattern.model.HighEndComputer; import com.baeldung.templatemethodpattern.model.StandardComputer; import org.junit.Assert; +import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; public class TemplateMethodPatternTest { - + private static StandardComputer standardComputer; private static HighEndComputer highEndComputer; @@ -20,101 +21,54 @@ public class TemplateMethodPatternTest { public static void setUpHighEndComputerInstance() { highEndComputer = new HighEndComputer(); } + + @Test + public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + standardComputer.addMotherboard(); + assertEquals("Standard Motherboard", standardComputer.getComputerParts().get("Motherboard")); + } + + @Test + public void givenStandardMotheroboard_whenSetup_thenTwoEqualAssertions() { + standardComputer.setupMotherboard(); + assertEquals("Screwing the standard motherboard to the case.", standardComputer.getMotherboardSetupStatus().get(0)); + assertEquals("Plugin in the power supply connectors.", standardComputer.getMotherboardSetupStatus().get(1)); + } @Test public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() { standardComputer.addProcessor(); - Assert.assertEquals("Standard Processor", standardComputer - .getComputerParts().get("Processor")); + assertEquals("Standard Processor", standardComputer.getComputerParts().get("Processor")); } - + @Test - public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { - standardComputer.addMotherboard(); - Assert.assertEquals("Standard Motherboard", standardComputer - .getComputerParts().get("Motherboard")); - } - - @Test - public void givenStandardMemory_whenAddingMemory_thenEqualAssertion() { - standardComputer.addMemory(); - Assert.assertEquals("8GB", standardComputer - .getComputerParts().get("Memory")); - } - - @Test - public void givenStandardHardDrive_whenAddingHardDrive_thenEqualAssertion() { - standardComputer.addHardDrive(); - Assert.assertEquals("1TB Hard Drive", standardComputer - .getComputerParts().get("Hard Drive")); - } - - @Test - public void givenStandardGraphicaCard_whenAddingGraphicCard_thenEqualAssertion() { - standardComputer.addGraphicCard(); - Assert.assertEquals("Standard Graphic Card", standardComputer - .getComputerParts().get("Graphic Card")); - } - - @Test - public void givenStandardSoundCard_whenAddingSoundCard_thenEqualAssertion() { - standardComputer.addSoundCard(); - Assert.assertEquals("Standard Sound Card", standardComputer - .getComputerParts().get("Sound Card")); - } - - @Test - public void givenAllStandardParts_whenBuildingComputer_thenSixParts() { + public void givenAllStandardParts_whenBuildingComputer_thenTwoParts() { standardComputer.buildComputer(); - Assert.assertEquals(6, standardComputer - .getComputerParts().size()); + assertEquals(2, standardComputer.getComputerParts().size()); + } + + @Test + public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + highEndComputer.addMotherboard(); + Assert.assertEquals("High-end Motherboard", highEndComputer.getComputerParts().get("Motherboard")); + } + + @Test + public void givenHighEnddMotheroboard_whenSetup_thenTwoEqualAssertions() { + highEndComputer.setupMotherboard(); + assertEquals("Screwing the high-end motherboard to the case.", highEndComputer.getMotherboardSetupStatus().get(0)); + assertEquals("Plugin in the power supply connectors.", highEndComputer.getMotherboardSetupStatus().get(1)); } @Test public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() { highEndComputer.addProcessor(); - Assert.assertEquals("High End Processor", highEndComputer - .getComputerParts().get("Processor")); + Assert.assertEquals("High-end Processor", highEndComputer.getComputerParts().get("Processor")); } @Test - public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { - highEndComputer.addMotherboard(); - Assert.assertEquals("High End Motherboard", highEndComputer - .getComputerParts().get("Motherboard")); - } - - @Test - public void givenHighEndMemory_whenAddingMemory_thenEqualAssertion() { - highEndComputer.addMemory(); - Assert.assertEquals("16GB", highEndComputer - .getComputerParts().get("Memory")); - } - - @Test - public void givenHighEndHardDrive_whenAddingHardDrive_thenEqualAssertion() { - highEndComputer.addHardDrive(); - Assert.assertEquals("2TB Hard Drive", highEndComputer - .getComputerParts().get("Hard Drive")); - } - - @Test - public void givenHighEndGraphicCard_whenAddingGraphicCard_thenEqualAssertion() { - highEndComputer.addGraphicCard(); - Assert.assertEquals("High End Graphic Card", highEndComputer - .getComputerParts().get("Graphic Card")); - } - - @Test - public void givenHighEndSoundCard_whenAddingSoundCard_thenEqualAssertion() { - highEndComputer.addSoundCard(); - Assert.assertEquals("High End Sound Card", highEndComputer - .getComputerParts().get("Sound Card")); - } - - @Test - public void givenAllHighEndParts_whenBuildingComputer_thenSixParts() { + public void givenAllHighEnddParts_whenBuildingComputer_thenTwoParts() { highEndComputer.buildComputer(); - Assert.assertEquals(6, highEndComputer.getComputerParts().size()); + assertEquals(2, highEndComputer.getComputerParts().size()); } } From f96548363e17c1566262cef03190a137aee6efb5 Mon Sep 17 00:00:00 2001 From: felipeazv Date: Thu, 9 Nov 2017 12:04:37 +0100 Subject: [PATCH 05/13] BAEL-803: Backward Chaining with Drools - parent module (#2986) * 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 * BAEL-1027: Introduction to GraphQL - initial commit * BAEL-781: Explore the new Spring Cloud Gateway * BAEL-781: Fix UserService.java * BAEL-781: Fix user-service pom.xml * BAEL-781: remove eureka-server from the example * BAEL-781: modifying example * BAEL-803: Backward Chaining wih Drools * BAEL-803: pom.xml * BAEL-803: Backward Chaining with Drools - new example * BAEL-803: Backward Chaining with Drools - parent module * BAEL-803: Backward Chaining with Drools - parent module * BAEL-803: Backward Chaining with Drools - meta-inf/maven-fix * BAEL-803: Backward Chaining with Drools - drools parent module --- drools/backward-chaining/pom.xml | 5 +--- .../com/baeldung/drools/BackwardChaining.java | 4 +-- .../drools/backward_chaining/rules.drl | 27 +++++++++++++++++++ drools/pom.xml | 2 ++ 4 files changed, 31 insertions(+), 7 deletions(-) create mode 100644 drools/backward-chaining/src/main/resources/com/baeldung/drools/backward_chaining/rules.drl diff --git a/drools/backward-chaining/pom.xml b/drools/backward-chaining/pom.xml index bda0cf2abc..1cf8f008af 100644 --- a/drools/backward-chaining/pom.xml +++ b/drools/backward-chaining/pom.xml @@ -1,7 +1,6 @@ - 4.0.0 drools-backward-chaining @@ -17,7 +16,6 @@ 6.4.0.Final - org.kie @@ -26,7 +24,6 @@ org.drools - drools-core ${runtime.version} @@ -35,4 +32,4 @@ ${runtime.version} - + \ No newline at end of file diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java b/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java index 1c1d258b47..bac144c32b 100644 --- a/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java +++ b/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java @@ -21,13 +21,11 @@ public class BackwardChaining { KieSession ksession = kContainer.newKieSession("ksession-backward-chaining"); ksession.setGlobal("result", result); ksession.insert(new Fact("Asia", "Planet Earth")); -// ksession.insert(new Fact("China", "Asia")); + // ksession.insert(new Fact("China", "Asia")); ksession.insert(new Fact("Great Wall of China", "China")); ksession.fireAllRules(); return result; - } - } \ No newline at end of file diff --git a/drools/backward-chaining/src/main/resources/com/baeldung/drools/backward_chaining/rules.drl b/drools/backward-chaining/src/main/resources/com/baeldung/drools/backward_chaining/rules.drl new file mode 100644 index 0000000000..bb5a8299e1 --- /dev/null +++ b/drools/backward-chaining/src/main/resources/com/baeldung/drools/backward_chaining/rules.drl @@ -0,0 +1,27 @@ +package com.baeldung + +import com.baeldung.drools.model.Fact; + +global com.baeldung.drools.model.Result result; + +dialect "mvel" + +query belongsTo(String x, String y) + Fact(x, y;) + or + (Fact(z, y;) and belongsTo(x, z;)) +end + +rule "Great Wall of China BELONGS TO Planet Earth" +when + belongsTo("Great Wall of China", "Planet Earth";) +then + result.setValue("Decision one taken: Great Wall of China BELONGS TO Planet Earth"); +end + +rule "print all facts" +when + belongsTo(element, place;) +then + result.addFact(element + " IS ELEMENT OF " + place); +end diff --git a/drools/pom.xml b/drools/pom.xml index 29231f150c..ab894c6a1a 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -7,6 +7,8 @@ com.baeldung drools 1.0.0-SNAPSHOT + + pom com.baeldung From 182a7525f254cbd401bd3f0a2b9d5c56d2ad4303 Mon Sep 17 00:00:00 2001 From: Sergey Petunin Date: Thu, 9 Nov 2017 12:25:49 +0100 Subject: [PATCH 06/13] BAEL-1222: Hit the Ground Running with the Spring Security Java Configuration (#2988) --- guest/spring-security/README.md | 17 ++++ guest/spring-security/pom.xml | 77 +++++++++++++++++++ .../guest/springsecurity/Application.java | 15 ++++ .../config/WebMvcConfiguration.java | 16 ++++ .../config/WebSecurityConfig.java | 40 ++++++++++ .../src/main/resources/data.sql | 2 + .../src/main/resources/schema.sql | 10 +++ .../src/main/resources/static/css/styles.css | 3 + .../main/resources/templates/customLogin.html | 21 +++++ .../src/main/resources/templates/index.html | 11 +++ 10 files changed, 212 insertions(+) create mode 100644 guest/spring-security/README.md create mode 100644 guest/spring-security/pom.xml create mode 100644 guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java create mode 100644 guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java create mode 100644 guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java create mode 100644 guest/spring-security/src/main/resources/data.sql create mode 100644 guest/spring-security/src/main/resources/schema.sql create mode 100644 guest/spring-security/src/main/resources/static/css/styles.css create mode 100644 guest/spring-security/src/main/resources/templates/customLogin.html create mode 100644 guest/spring-security/src/main/resources/templates/index.html diff --git a/guest/spring-security/README.md b/guest/spring-security/README.md new file mode 100644 index 0000000000..9e5cd64a04 --- /dev/null +++ b/guest/spring-security/README.md @@ -0,0 +1,17 @@ +## Building + +To build the module, use Maven's `package` goal: + +``` +mvn clean package +``` + +## Running + +To run the application, use Spring Boot's `run` goal: + +``` +mvn spring-boot:run +``` + +The application will be accessible at [http://localhost:8080/](http://localhost:8080/) diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml new file mode 100644 index 0000000000..c41637bfc2 --- /dev/null +++ b/guest/spring-security/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + com.stackify.guest + spring-security + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.M6 + + + + spring-security + Spring Security Sample Project + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.thymeleaf + thymeleaf-spring5 + 3.0.8.RELEASE + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.h2database + h2 + runtime + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + UTF-8 + UTF-8 + 1.8 + + + \ No newline at end of file diff --git a/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java new file mode 100644 index 0000000000..fbd0eee044 --- /dev/null +++ b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java @@ -0,0 +1,15 @@ +package com.stackify.guest.springsecurity; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = {"com.stackify.guest.springsecurity"}) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java new file mode 100644 index 0000000000..b8dfe9050d --- /dev/null +++ b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java @@ -0,0 +1,16 @@ +package com.stackify.guest.springsecurity.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebMvcConfiguration implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/customLogin").setViewName("customLogin"); + registry.addViewController("/loginSuccess").setViewName("index"); + } + +} \ No newline at end of file diff --git a/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java new file mode 100644 index 0000000000..164808d5b3 --- /dev/null +++ b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java @@ -0,0 +1,40 @@ +package com.stackify.guest.springsecurity.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +import javax.sql.DataSource; + +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Bean + public UserDetailsService jdbcUserDetailsService(DataSource dataSource) { + JdbcUserDetailsManager manager = new JdbcUserDetailsManager(); + manager.setDataSource(dataSource); + return manager; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/css/**").permitAll() + .anyRequest().authenticated() + .and().formLogin() + .loginPage("/customLogin") + .defaultSuccessUrl("/loginSuccess", true) + .permitAll(); + } + +} \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/data.sql b/guest/spring-security/src/main/resources/data.sql new file mode 100644 index 0000000000..b3f7db9105 --- /dev/null +++ b/guest/spring-security/src/main/resources/data.sql @@ -0,0 +1,2 @@ +INSERT INTO users VALUES ('jill', '$2a$04$qUlqAEEYF1YvrpJMosodoewgL6aO.qgHytl2k5L7kdXEWnJsFdxvq', TRUE); +INSERT INTO authorities VALUES ('jill', 'USERS'); diff --git a/guest/spring-security/src/main/resources/schema.sql b/guest/spring-security/src/main/resources/schema.sql new file mode 100644 index 0000000000..3de1b9a29f --- /dev/null +++ b/guest/spring-security/src/main/resources/schema.sql @@ -0,0 +1,10 @@ +CREATE TABLE users ( + username VARCHAR(256) PRIMARY KEY, + password VARCHAR(256), + enabled BOOLEAN +); + +CREATE TABLE authorities ( + username VARCHAR(256) REFERENCES users (username), + authority VARCHAR(256) +); diff --git a/guest/spring-security/src/main/resources/static/css/styles.css b/guest/spring-security/src/main/resources/static/css/styles.css new file mode 100644 index 0000000000..72bcc4934f --- /dev/null +++ b/guest/spring-security/src/main/resources/static/css/styles.css @@ -0,0 +1,3 @@ +.bad-login { + color: red; +} \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/templates/customLogin.html b/guest/spring-security/src/main/resources/templates/customLogin.html new file mode 100644 index 0000000000..c689c78514 --- /dev/null +++ b/guest/spring-security/src/main/resources/templates/customLogin.html @@ -0,0 +1,21 @@ + + + + + + +
+
+ + + + +
+ + + +
Log out successful.
+
+ + \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/templates/index.html b/guest/spring-security/src/main/resources/templates/index.html new file mode 100644 index 0000000000..0769f9015f --- /dev/null +++ b/guest/spring-security/src/main/resources/templates/index.html @@ -0,0 +1,11 @@ + + +

Hello, !

+
+ + +
+ \ No newline at end of file From 6a8ecab16338ac226874da521426c3c69e4a3738 Mon Sep 17 00:00:00 2001 From: Wosin Date: Thu, 9 Nov 2017 20:52:58 +0100 Subject: [PATCH 07/13] BAEL-1310: Code for Quick Guide to Stack. (#2993) --- .../com/baeldung/stack/StackUnitTest.java | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/stack/StackUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java b/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java new file mode 100644 index 0000000000..2b04617f36 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java @@ -0,0 +1,137 @@ +package com.baeldung.stack; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.List; +import java.util.ListIterator; +import java.util.Stack; + +import org.junit.Test; +public class StackUnitTest { + + @Test + public void whenStackIsCreated_thenItHasSize0() { + Stack intStack = new Stack(); + assertEquals(0, intStack.size()); + } + + @Test + public void givenEmptyStack_whenElementIsPushed_thenStackSizeisIncreased() { + Stack intStack = new Stack(); + intStack.push(1); + assertEquals(1, intStack.size()); + } + + @Test + public void givenEmptyStack_whenMultipleElementsArePushed_thenStackSizeisIncreased() { + Stack intStack = new Stack(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + boolean result = intStack.addAll(intList); + assertTrue(result); + assertEquals(7, intList.size()); + } + + @Test + public void whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.pop(); + assertTrue(intStack.isEmpty()); + } + + @Test + public void whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.peek(); + assertEquals(1, intStack.search(5)); + assertEquals(1, intStack.size()); + } + + @Test + public void whenElementIsOnStack_thenSearchReturnsItsDistanceFromTheTop() { + Stack intStack = new Stack(); + intStack.push(5); + assertEquals(1, intStack.search(5)); + } + + @Test + public void whenElementIsOnStack_thenIndexOfReturnsItsIndex() { + Stack intStack = new Stack(); + intStack.push(5); + int indexOf = intStack.indexOf(5); + assertEquals(0, indexOf); + } + + @Test + public void whenMultipleElementsAreOnStack_thenIndexOfReturnsLastElementIndex() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(5); + intStack.push(5); + int lastIndexOf = intStack.lastIndexOf(5); + assertEquals(2, lastIndexOf); + } + + @Test + public void givenElementOnStack_whenRemoveElementIsInvoked_thenElementIsRemoved() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(5); + intStack.removeElement(5); + assertEquals(1, intStack.size()); + } + + @Test + public void givenElementOnStack_whenRemoveElementAtIsInvoked_thenElementIsRemoved() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(7); + intStack.removeElementAt(1); + assertEquals(-1, intStack.search(7)); + } + + @Test + public void givenElementsOnStack_whenRemoveAllElementsIsInvoked_thenAllElementsAreRemoved() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(7); + intStack.removeAllElements(); + assertTrue(intStack.isEmpty()); + } + + @Test + public void givenElementsOnStack_whenRemoveAllIsInvoked_thenAllElementsFromCollectionAreRemoved() { + Stack intStack = new Stack(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + intStack.addAll(intList); + intStack.add(500); + intStack.removeAll(intList); + assertEquals(1, intStack.size()); + } + + @Test + public void givenElementsOnStack_whenRemoveIfIsInvoked_thenAllElementsSatysfyingConditionAreRemoved() { + Stack intStack = new Stack(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + intStack.addAll(intList); + intStack.removeIf(element -> element < 6); + assertEquals(2, intStack.size()); + } + + @Test + public void whenAnotherStackCreatedWhileTraversingStack_thenStacksAreEqual() { + Stack intStack = new Stack<>(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + intStack.addAll(intList); + ListIterator it = intStack.listIterator(); + Stack result = new Stack(); + while(it.hasNext()) { + result.push(it.next()); + } + + assertThat(result, equalTo(intStack)); + } +} From a38e6e295e6fb82dbb68b1c25df9a9366aaa04ed Mon Sep 17 00:00:00 2001 From: Muhammed Almas Date: Fri, 10 Nov 2017 01:24:36 +0530 Subject: [PATCH 08/13] BAEL-1296 Prime numbers till n. (#2956) * BAEL-1296 Prime numbers till n. * BAEL-1296 Renamed packge --- .../algorithms/prime/PrimeGenerator.java | 59 +++++++++++++++++++ .../algorithms/prime/PrimeGeneratorTest.java | 28 +++++++++ 2 files changed, 87 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java b/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java new file mode 100644 index 0000000000..48d51a8848 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java @@ -0,0 +1,59 @@ +package com.baeldung.algorithms.prime; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PrimeGenerator { + public static List sieveOfEratosthenes(int n) { + final boolean prime[] = new boolean[n + 1]; + Arrays.fill(prime, true); + + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * 2; i <= n; i += p) + prime[i] = false; + } + } + + final List primes = new LinkedList<>(); + for (int i = 2; i <= n; i++) { + if (prime[i]) + primes.add(i); + } + return primes; + } + + public static List primeNumbersBruteForce(int max) { + final List primeNumbers = new LinkedList(); + for (int i = 2; i <= max; i++) { + if (isPrimeBruteForce(i)) { + primeNumbers.add(i); + } + } + return primeNumbers; + } + + private static boolean isPrimeBruteForce(int x) { + for (int i = 2; i < x; i++) { + if (x % i == 0) { + return false; + } + } + return true; + } + + public static List primeNumbersTill(int max) { + return IntStream.rangeClosed(2, max) + .filter(x -> isPrime(x)) + .boxed() + .collect(Collectors.toList()); + } + + private static boolean isPrime(int x) { + return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) + .allMatch(n -> x % n != 0); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java new file mode 100644 index 0000000000..4995e938b7 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java @@ -0,0 +1,28 @@ +package com.baeldung.algorithms.prime; + +import static com.baeldung.algorithms.prime.PrimeGenerator.*; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PrimeGeneratorTest { + @Test + public void whenBruteForced_returnsSuccessfully() { + final List primeNumbers = primeNumbersBruteForce(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenOptimized_returnsSuccessfully() { + final List primeNumbers = primeNumbersTill(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenSieveOfEratosthenes_returnsSuccessfully() { + final List primeNumbers = sieveOfEratosthenes(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } +} From 3bb538a2f7e7664508825b24e3543b9c3f1b9744 Mon Sep 17 00:00:00 2001 From: chrisoberle Date: Thu, 9 Nov 2017 19:15:03 -0500 Subject: [PATCH 09/13] BAEL-1314 Guide to AbstractRoutingDatasource (#2989) * BAEL-1314 initial import. Guide to AbstractRoutingDatasource. * BAEL-1314 Guide to Spring AbstractRoutingDatasource * update test name and rename test classes * move dsrouting example to spring-boot project. rename db create script. --- .../org/baeldung/dsrouting/ClientDao.java | 29 +++++++++ .../dsrouting/ClientDataSourceRouter.java | 14 ++++ .../baeldung/dsrouting/ClientDatabase.java | 7 ++ .../ClientDatabaseContextHolder.java | 26 ++++++++ .../org/baeldung/dsrouting/ClientService.java | 21 ++++++ .../DataSourceRoutingTestConfiguration.java | 64 +++++++++++++++++++ .../dsrouting/DataSourceRoutingTests.java | 62 ++++++++++++++++++ .../src/test/resources/dsrouting-db.sql | 5 ++ 8 files changed, 228 insertions(+) create mode 100644 spring-boot/src/main/java/org/baeldung/dsrouting/ClientDao.java create mode 100644 spring-boot/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java create mode 100644 spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabase.java create mode 100644 spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java create mode 100644 spring-boot/src/main/java/org/baeldung/dsrouting/ClientService.java create mode 100644 spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java create mode 100644 spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTests.java create mode 100644 spring-boot/src/test/resources/dsrouting-db.sql diff --git a/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDao.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDao.java new file mode 100644 index 0000000000..180f54326e --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDao.java @@ -0,0 +1,29 @@ +package org.baeldung.dsrouting; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +/** + * Database access code for datasource routing example. + */ +public class ClientDao { + + private static final String SQL_GET_CLIENT_NAME = "select name from client"; + + private final JdbcTemplate jdbcTemplate; + + public ClientDao(DataSource datasource) { + this.jdbcTemplate = new JdbcTemplate(datasource); + } + + public String getClientName() { + return this.jdbcTemplate.query(SQL_GET_CLIENT_NAME, rowMapper) + .get(0); + } + + private static RowMapper rowMapper = (rs, rowNum) -> { + return rs.getString("name"); + }; +} diff --git a/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java new file mode 100644 index 0000000000..997e461cde --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java @@ -0,0 +1,14 @@ +package org.baeldung.dsrouting; + +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; + +/** + * Returns thread bound client lookup key for current context. + */ +public class ClientDataSourceRouter extends AbstractRoutingDataSource { + + @Override + protected Object determineCurrentLookupKey() { + return ClientDatabaseContextHolder.getClientDatabase(); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabase.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabase.java new file mode 100644 index 0000000000..6c87cb3dde --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabase.java @@ -0,0 +1,7 @@ +package org.baeldung.dsrouting; + +public enum ClientDatabase { + + ACME_WIDGETS, WIDGETS_ARE_US, WIDGET_DEPOT + +} diff --git a/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java new file mode 100644 index 0000000000..c08559e877 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java @@ -0,0 +1,26 @@ +package org.baeldung.dsrouting; + +import org.springframework.util.Assert; + +/** + * Thread shared context to point to the datasource which should be used. This + * enables context switches between different clients. + */ +public class ClientDatabaseContextHolder { + + private static final ThreadLocal CONTEXT = new ThreadLocal<>(); + + public static void set(ClientDatabase clientDatabase) { + Assert.notNull(clientDatabase, "clientDatabase cannot be null"); + CONTEXT.set(clientDatabase); + } + + public static ClientDatabase getClientDatabase() { + return CONTEXT.get(); + } + + public static void clear() { + CONTEXT.remove(); + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/dsrouting/ClientService.java b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientService.java new file mode 100644 index 0000000000..4b63c6333c --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/dsrouting/ClientService.java @@ -0,0 +1,21 @@ +package org.baeldung.dsrouting; + +/** + * Service layer code for datasource routing example. Here, the service methods are responsible + * for setting and clearing the context. + */ +public class ClientService { + + private final ClientDao clientDao; + + public ClientService(ClientDao clientDao) { + this.clientDao = clientDao; + } + + public String getClientName(ClientDatabase clientDb) { + ClientDatabaseContextHolder.set(clientDb); + String clientName = this.clientDao.getClientName(); + ClientDatabaseContextHolder.clear(); + return clientName; + } +} diff --git a/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java b/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java new file mode 100644 index 0000000000..09382c4ca0 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java @@ -0,0 +1,64 @@ +package org.baeldung.dsrouting; + +import java.util.HashMap; +import java.util.Map; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +@Configuration +public class DataSourceRoutingTestConfiguration { + + @Bean + public ClientService clientService() { + return new ClientService(new ClientDao(clientDatasource())); + } + + @Bean + public DataSource clientDatasource() { + Map targetDataSources = new HashMap<>(); + DataSource acmeWidgetsDatasource = acmeWidgetsDatasource(); + DataSource widgetsAreUsDatasource = widgetsAreUsDatasource(); + DataSource widgetsDepotDatasource = widgetsDepotDatasource(); + targetDataSources.put(ClientDatabase.ACME_WIDGETS, acmeWidgetsDatasource); + targetDataSources.put(ClientDatabase.WIDGETS_ARE_US, widgetsAreUsDatasource); + targetDataSources.put(ClientDatabase.WIDGET_DEPOT, widgetsDepotDatasource); + + ClientDataSourceRouter clientRoutingDatasource = new ClientDataSourceRouter(); + clientRoutingDatasource.setTargetDataSources(targetDataSources); + clientRoutingDatasource.setDefaultTargetDataSource(acmeWidgetsDatasource); + return clientRoutingDatasource; + } + + private DataSource acmeWidgetsDatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("ACMEWIDGETS") + .addScript("classpath:dsrouting-db.sql") + .build(); + return embeddedDb; + } + + private DataSource widgetsAreUsDatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("WIDGETSAREUS") + .addScript("classpath:dsrouting-db.sql") + .build(); + return embeddedDb; + } + + private DataSource widgetsDepotDatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("WIDGETDEPOT") + .addScript("classpath:dsrouting-db.sql") + .build(); + return embeddedDb; + } +} diff --git a/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTests.java b/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTests.java new file mode 100644 index 0000000000..f19871702e --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTests.java @@ -0,0 +1,62 @@ +package org.baeldung.dsrouting; + +import static org.junit.Assert.assertEquals; + +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = DataSourceRoutingTestConfiguration.class) +public class DataSourceRoutingTests { + + @Autowired + DataSource routingDatasource; + + @Autowired + ClientService clientService; + + @Before + public void setup() { + final String SQL_ACME_WIDGETS = "insert into client (id, name) values (1, 'ACME WIDGETS')"; + final String SQL_WIDGETS_ARE_US = "insert into client (id, name) values (2, 'WIDGETS ARE US')"; + final String SQL_WIDGET_DEPOT = "insert into client (id, name) values (3, 'WIDGET DEPOT')"; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.setDataSource(routingDatasource); + + ClientDatabaseContextHolder.set(ClientDatabase.ACME_WIDGETS); + jdbcTemplate.execute(SQL_ACME_WIDGETS); + ClientDatabaseContextHolder.clear(); + + ClientDatabaseContextHolder.set(ClientDatabase.WIDGETS_ARE_US); + jdbcTemplate.execute(SQL_WIDGETS_ARE_US); + ClientDatabaseContextHolder.clear(); + + ClientDatabaseContextHolder.set(ClientDatabase.WIDGET_DEPOT); + jdbcTemplate.execute(SQL_WIDGET_DEPOT); + ClientDatabaseContextHolder.clear(); + } + + @Test + public void givenClientDbs_whenContextsSwitch_thenRouteToCorrectDatabase() throws Exception { + + // test ACME WIDGETS + String clientName = clientService.getClientName(ClientDatabase.ACME_WIDGETS); + assertEquals(clientName, "ACME WIDGETS"); + + // test WIDGETS_ARE_US + clientName = clientService.getClientName(ClientDatabase.WIDGETS_ARE_US); + assertEquals(clientName, "WIDGETS ARE US"); + + // test WIDGET_DEPOT + clientName = clientService.getClientName(ClientDatabase.WIDGET_DEPOT); + assertEquals(clientName, "WIDGET DEPOT"); + } +} diff --git a/spring-boot/src/test/resources/dsrouting-db.sql b/spring-boot/src/test/resources/dsrouting-db.sql new file mode 100644 index 0000000000..c9ca52907a --- /dev/null +++ b/spring-boot/src/test/resources/dsrouting-db.sql @@ -0,0 +1,5 @@ +create table client ( + id numeric, + name varchar(50), + constraint pk_client primary key (id) +); \ No newline at end of file From 75630b6c5433b82bb2294afefa6ed562f6790e73 Mon Sep 17 00:00:00 2001 From: juan Date: Fri, 10 Nov 2017 00:53:43 -0300 Subject: [PATCH 10/13] Update for article BAEL-1121 --- jsonb/.gitignore | 12 ++ jsonb/README.md | 1 + jsonb/pom.xml | 90 ++++++++++ .../main/java/com/baeldung/jsonb/Person.java | 127 ++++++++++++++ .../java/com/baeldung/jsonb/JsonbTest.java | 158 ++++++++++++++++++ spring-5/pom.xml | 19 +++ .../java/com/baeldung/jsonb/JsonbTest.java | 53 ------ 7 files changed, 407 insertions(+), 53 deletions(-) create mode 100644 jsonb/.gitignore create mode 100644 jsonb/README.md create mode 100644 jsonb/pom.xml create mode 100644 jsonb/src/main/java/com/baeldung/jsonb/Person.java create mode 100644 jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java delete mode 100644 spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java diff --git a/jsonb/.gitignore b/jsonb/.gitignore new file mode 100644 index 0000000000..dec013dfa4 --- /dev/null +++ b/jsonb/.gitignore @@ -0,0 +1,12 @@ +#folders# +.idea +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/jsonb/README.md b/jsonb/README.md new file mode 100644 index 0000000000..a638f0355c --- /dev/null +++ b/jsonb/README.md @@ -0,0 +1 @@ +## JSON B diff --git a/jsonb/pom.xml b/jsonb/pom.xml new file mode 100644 index 0000000000..af220a015d --- /dev/null +++ b/jsonb/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + + com.baeldung + json-b + 0.0.1-SNAPSHOT + jar + + json-b + json-b sample project + + + + javax.json.bind + javax.json.bind-api + ${jsonb-api.version} + + + + org.eclipse + yasson + 1.0 + + + org.glassfish + javax.json + 1.1.2 + + + + + + + + + + + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test + + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + + UTF-8 + UTF-8 + 1.8 + 1.8 + 1.0.0 + 5.0.0 + 2.20 + 1.1.3 + 1.0 + 1.0 + 4.1 + + + diff --git a/jsonb/src/main/java/com/baeldung/jsonb/Person.java b/jsonb/src/main/java/com/baeldung/jsonb/Person.java new file mode 100644 index 0000000000..7a54b37574 --- /dev/null +++ b/jsonb/src/main/java/com/baeldung/jsonb/Person.java @@ -0,0 +1,127 @@ +package com.baeldung.jsonb; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import javax.json.bind.annotation.JsonbDateFormat; +import javax.json.bind.annotation.JsonbNumberFormat; +import javax.json.bind.annotation.JsonbProperty; +import javax.json.bind.annotation.JsonbTransient; + +public class Person { + + private int id; + @JsonbProperty("person-name") + private String name; + @JsonbProperty(nillable = true) + private String email; + @JsonbTransient + private int age; + @JsonbDateFormat("dd-MM-yyyy") + private LocalDate registeredDate; + private BigDecimal salary; + + public Person() { + } + + public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) { + super(); + this.id = id; + this.name = name; + this.email = email; + this.age = age; + this.registeredDate = registeredDate; + this.salary = salary; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @JsonbNumberFormat(locale = "en_US", value = "#0.0") + public BigDecimal getSalary() { + return salary; + } + + public void setSalary(BigDecimal salary) { + this.salary = salary; + } + + public LocalDate getRegisteredDate() { + return registeredDate; + } + + public void setRegisteredDate(LocalDate registeredDate) { + this.registeredDate = registeredDate; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append(", age="); + builder.append(age); + builder.append(", registeredDate="); + builder.append(registeredDate); + builder.append(", salary="); + builder.append(salary); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Person other = (Person) obj; + if (id != other.id) + return false; + return true; + } + +} diff --git a/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java b/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java new file mode 100644 index 0000000000..92ffe0aa6f --- /dev/null +++ b/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java @@ -0,0 +1,158 @@ +package com.baeldung.jsonb; + +import static org.junit.Assert.assertTrue; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.json.bind.Jsonb; +import javax.json.bind.JsonbBuilder; +import javax.json.bind.JsonbConfig; +import javax.json.bind.config.PropertyNamingStrategy; +import javax.json.bind.config.PropertyOrderStrategy; + +import org.apache.commons.collections4.ListUtils; +import org.junit.Test; + +public class JsonbTest { + + @Test + public void givenPersonList_whenSerializeWithJsonb_thenGetPersonJsonArray() { + Jsonb jsonb = JsonbBuilder.create(); + // @formatter:off + List personList = Arrays.asList( + new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); + // @formatter:on + String jsonArrayPerson = jsonb.toJson(personList); + // @formatter:off + String jsonExpected = "[" + + "{\"email\":\"jhon@test.com\"," + + "\"id\":1,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"jhon1@test.com\"," + + "\"id\":2,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"},{\"email\":null," + + "\"id\":3,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"tom@test.com\"," + + "\"id\":4,\"person-name\":\"Tom\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"}" + + "]"; + // @formatter:on + assertTrue(jsonArrayPerson.equals(jsonExpected)); + } + + @Test + public void givenPersonJsonArray_whenDeserializeWithJsonb_thenGetPersonList() { + Jsonb jsonb = JsonbBuilder.create(); + // @formatter:off + String personJsonArray = + "[" + + "{\"email\":\"jhon@test.com\"," + + "\"id\":1,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"jhon1@test.com\"," + + "\"id\":2,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"},{\"email\":null," + + "\"id\":3,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"tom@test.com\"," + + "\"id\":4,\"person-name\":\"Tom\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"}" + + "]"; + // @formatter:on + @SuppressWarnings("serial") + List personList = jsonb.fromJson(personJsonArray, new ArrayList() { + }.getClass() + .getGenericSuperclass()); + // @formatter:off + List personListExpected = Arrays.asList( + new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); + // @formatter:on + assertTrue(ListUtils.isEqualList(personList, personListExpected)); + } + + @Test + public void givenPersonObject_whenNamingStrategy_thenGetCustomPersonJson() { + JsonbConfig config = new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registered_date\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonObject_whenWithPropertyOrderStrategy_thenGetReversePersonJson() { + JsonbConfig config = new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"salary\":\"1000.0\","+ + "\"registeredDate\":\"07-09-2019\"," + + "\"person-name\":\"Jhon\"," + + "\"id\":1," + + "\"email\":\"jhon@test.com\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { + Jsonb jsonb = JsonbBuilder.create(); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { + Jsonb jsonb = JsonbBuilder.create(); + Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); + // @formatter:off + String jsonPerson = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonb.fromJson(jsonPerson, Person.class) + .equals(person)); + } + +} diff --git a/spring-5/pom.xml b/spring-5/pom.xml index b77d89b532..f45cdb0275 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -49,6 +49,18 @@ javax.json.bind-api ${jsonb-api.version} + + + + + + + + + + + + org.apache.geronimo.specs geronimo-json_1.1_spec @@ -88,6 +100,13 @@ test + + org.apache.commons + commons-collections4 + 4.1 + test + + org.junit.jupiter junit-jupiter-api diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java deleted file mode 100644 index a65e171e6e..0000000000 --- a/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.jsonb; - -import static org.junit.Assert.assertTrue; - -import java.math.BigDecimal; -import java.time.LocalDate; - -import javax.json.bind.Jsonb; -import javax.json.bind.JsonbBuilder; - -import org.junit.Before; -import org.junit.Test; - -public class JsonbTest { - - private Jsonb jsonb; - - @Before - public void setup() { - jsonb = JsonbBuilder.create(); - } - - @Test - public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { - Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); - String jsonPerson = jsonb.toJson(person); - //// @formatter:off - String jsonExpected = - "{\"email\":\"jhon@test.com\"," + - "\"id\":1," + - "\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"07-09-2019\"," + - "\"salary\":\"1000.0\"}"; - // @formatter:on - assertTrue(jsonExpected.equals(jsonPerson)); - } - - @Test - public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { - Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); - // @formatter:off - String jsonPerson = - "{\"email\":\"jhon@test.com\"," + - "\"id\":1," + - "\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"07-09-2019\"," + - "\"salary\":\"1000.0\"}"; - // @formatter:on - assertTrue(jsonb.fromJson(jsonPerson, Person.class) - .equals(person)); - } - -} From a60d922fd66c11969d31a31f37b04509b3600e73 Mon Sep 17 00:00:00 2001 From: juan Date: Fri, 10 Nov 2017 01:28:09 -0300 Subject: [PATCH 11/13] Update pom.xml with profiles --- jsonb/pom.xml | 64 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/jsonb/pom.xml b/jsonb/pom.xml index af220a015d..c61e1ac285 100644 --- a/jsonb/pom.xml +++ b/jsonb/pom.xml @@ -10,35 +10,49 @@ json-b json-b sample project - + + + yasson + + true + + + + + org.eclipse + yasson + ${yasson.version} + + + org.glassfish + javax.json + ${javax.json.version} + + + + + johnzon + + + + org.apache.geronimo.specs + geronimo-json_1.1_spec + ${geronimo-json_1.1_spec.version} + + + org.apache.johnzon + johnzon-jsonb + ${johnzon.version} + + + + javax.json.bind javax.json.bind-api ${jsonb-api.version} - - - org.eclipse - yasson - 1.0 - - - org.glassfish - javax.json - 1.1.2 - - - - - - - - - - - - org.apache.commons @@ -81,9 +95,11 @@ 1.0.0 5.0.0 2.20 - 1.1.3 1.0 + 1.1.3 1.0 + 1.0 + 1.1.2 4.1 From cfd3def0150d9bfa56e1052396b1c8f7266ad16b Mon Sep 17 00:00:00 2001 From: felipeazv Date: Fri, 10 Nov 2017 07:57:09 +0100 Subject: [PATCH 12/13] BAEL-803: Backward Chaining with Drools - removed @RunWith (#3002) * 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 * BAEL-1027: Introduction to GraphQL - initial commit * BAEL-781: Explore the new Spring Cloud Gateway * BAEL-781: Fix UserService.java * BAEL-781: Fix user-service pom.xml * BAEL-781: remove eureka-server from the example * BAEL-781: modifying example * BAEL-803: Backward Chaining wih Drools * BAEL-803: pom.xml * BAEL-803: Backward Chaining with Drools - new example * BAEL-803: Backward Chaining with Drools - parent module * BAEL-803: Backward Chaining with Drools - parent module * BAEL-803: Backward Chaining with Drools - meta-inf/maven-fix * BAEL-803: Backward Chaining with Drools - drools parent module * BAEL-803: Backward Chaining with Drools - removed @RunWith --- .../src/test/java/com/baeldung/test/BackwardChainingTest.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java b/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java index 676e941950..112188f01f 100644 --- a/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java +++ b/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java @@ -2,8 +2,6 @@ package com.baeldung.test; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; @@ -13,7 +11,6 @@ import com.baeldung.drools.model.Result; import static junit.framework.TestCase.assertEquals; -@RunWith(value = JUnit4.class) public class BackwardChainingTest { private Result result; private KieServices ks; From c9aaa0d993cdb70e4e23e966d17e1e46779f2a13 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 10 Nov 2017 13:33:52 +0200 Subject: [PATCH 13/13] hibernate identifiers examples (#2977) * hibernate identifiers examples * fix conflict * change to longstream * change to format --- .../com/baeldung/hibernate/HibernateUtil.java | 17 +++ .../com/baeldung/hibernate/pojo/Course.java | 27 +++++ .../baeldung/hibernate/pojo/Department.java | 25 +++++ .../baeldung/hibernate/pojo/OrderEntry.java | 20 ++++ .../hibernate/pojo/OrderEntryIdClass.java | 31 ++++++ .../baeldung/hibernate/pojo/OrderEntryPK.java | 46 ++++++++ .../com/baeldung/hibernate/pojo/Product.java | 26 +++++ .../com/baeldung/hibernate/pojo/Student.java | 23 ++++ .../com/baeldung/hibernate/pojo/User.java | 24 +++++ .../baeldung/hibernate/pojo/UserProfile.java | 34 ++++++ .../hibernate/pojo/generator/MyGenerator.java | 41 +++++++ .../hibernate/IdentifiersIntegrationTest.java | 100 ++++++++++++++++++ 12 files changed, 414 insertions(+) create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java create mode 100644 hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 0282673218..c44a80cbd9 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -2,8 +2,17 @@ package com.baeldung.hibernate; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Product; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; + import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; @@ -33,6 +42,14 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Phone.class); metadataSources.addAnnotatedClass(EntityDescription.class); metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(User.class); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(Course.class); + metadataSources.addAnnotatedClass(Product.class); + metadataSources.addAnnotatedClass(OrderEntryPK.class); + metadataSources.addAnnotatedClass(OrderEntry.class); + metadataSources.addAnnotatedClass(OrderEntryIdClass.class); + metadataSources.addAnnotatedClass(UserProfile.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder() diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java new file mode 100644 index 0000000000..97760acd3b --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo; + +import java.util.UUID; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Course { + + @Id + @GeneratedValue + private UUID courseId; + + public UUID getCourseId() { + return courseId; + } + + public void setCourseId(UUID courseId) { + this.courseId = courseId; + } + + + + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java new file mode 100644 index 0000000000..6dd106b88e --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.TableGenerator; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.TABLE, generator="table-generator") + @TableGenerator (name="table-generator", table="dep_ids", pkColumnName="seq_id", valueColumnName="seq_value") + private long depId; + + public long getDepId() { + return depId; + } + + public void setDepId(long depId) { + this.depId = depId; + } + + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java new file mode 100644 index 0000000000..a28b7c8dbe --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java @@ -0,0 +1,20 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; + +@Entity +public class OrderEntry { + + @EmbeddedId + private OrderEntryPK entryId; + + public OrderEntryPK getEntryId() { + return entryId; + } + + public void setEntryId(OrderEntryPK entryId) { + this.entryId = entryId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java new file mode 100644 index 0000000000..18926640af --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; + +@Entity +@IdClass(OrderEntryPK.class) +public class OrderEntryIdClass { + @Id + private long orderId; + @Id + private long productId; + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java new file mode 100644 index 0000000000..637d590629 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java @@ -0,0 +1,46 @@ +package com.baeldung.hibernate.pojo; + +import java.io.Serializable; +import java.util.Objects; + +import javax.persistence.Embeddable; + +@Embeddable +public class OrderEntryPK implements Serializable { + + private long orderId; + private long productId; + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderEntryPK pk = (OrderEntryPK) o; + return Objects.equals(orderId, pk.orderId) && Objects.equals(productId, pk.productId); + } + + @Override + public int hashCode() { + return Objects.hash(orderId, productId); + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java new file mode 100644 index 0000000000..efd6b63dc0 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Parameter; + +@Entity +public class Product { + + @Id + @GeneratedValue(generator = "prod-generator") + @GenericGenerator(name = "prod-generator", parameters = @Parameter(name = "prefix", value = "prod"), strategy = "com.baeldung.hibernate.pojo.generator.MyGenerator") + private String prodId; + + public String getProdId() { + return prodId; + } + + public void setProdId(String prodId) { + this.prodId = prodId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..a6dec4a30d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,23 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue (strategy = GenerationType.SEQUENCE) + private long studentId; + + public long getStudentId() { + return studentId; + } + + public void setStudent_id(long studentId) { + this.studentId = studentId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java new file mode 100644 index 0000000000..90203d29ec --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java @@ -0,0 +1,24 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; + +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-generator") + @SequenceGenerator(name = "sequence-generator", sequenceName = "user_sequence", initialValue = 4) + private long userId; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java new file mode 100644 index 0000000000..ac870c2818 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.MapsId; +import javax.persistence.OneToOne; + +@Entity +public class UserProfile { + + @Id + private long profileId; + + @OneToOne + @MapsId + private User user; + + public long getProfileId() { + return profileId; + } + + public void setProfileId(long profileId) { + this.profileId = profileId; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java new file mode 100644 index 0000000000..17ffe9b7e1 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.pojo.generator; + +import java.io.Serializable; +import java.util.Properties; +import java.util.stream.Stream; + +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.id.Configurable; +import org.hibernate.id.IdentifierGenerator; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.type.Type; + +public class MyGenerator implements IdentifierGenerator, Configurable { + + private String prefix; + + @Override + public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException { + + String query = String.format("select %s from %s", + session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(), + obj.getClass().getSimpleName()); + + Stream ids = session.createQuery(query).stream(); + + Long max = ids.map(o -> o.replace(prefix + "-", "")) + .mapToLong(Long::parseLong) + .max() + .orElse(0L); + + return prefix + "-" + (max + 1); + } + + @Override + public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException { + prefix = properties.getProperty("prefix"); + } + +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java new file mode 100644 index 0000000000..6b54dc80a8 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java @@ -0,0 +1,100 @@ +package com.baeldung.hibernate; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.hibernate.Transaction; +import java.io.IOException; +import org.hibernate.Session; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.hibernate.pojo.Product; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; + +public class IdentifiersIntegrationTest { + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void whenSaveSimpleIdEntities_thenOk() { + Student student = new Student(); + session.save(student); + User user = new User(); + session.save(user); + + assertThat(student.getStudentId()).isEqualTo(1L); + assertThat(user.getUserId()).isEqualTo(4L); + + Course course = new Course(); + session.save(course); + + } + + @Test + public void whenSaveCustomGeneratedId_thenOk() { + Product product = new Product(); + session.save(product); + Product product2 = new Product(); + session.save(product2); + + assertThat(product2.getProdId()).isEqualTo("prod-2"); + } + + @Test + public void whenSaveCompositeIdEntity_thenOk() { + OrderEntryPK entryPK = new OrderEntryPK(); + entryPK.setOrderId(1L); + entryPK.setProductId(30L); + + OrderEntry entry = new OrderEntry(); + entry.setEntryId(entryPK); + session.save(entry); + + assertThat(entry.getEntryId() + .getOrderId()).isEqualTo(1L); + } + + @Test + public void whenSaveIdClassEntity_thenOk() { + OrderEntryIdClass entry = new OrderEntryIdClass(); + entry.setOrderId(1L); + entry.setProductId(30L); + session.save(entry); + + assertThat(entry.getOrderId()).isEqualTo(1L); + } + + @Test + public void whenSaveDerivedIdEntity_thenOk() { + User user = new User(); + session.save(user); + + UserProfile profile = new UserProfile(); + profile.setUser(user); + session.save(profile); + + assertThat(profile.getProfileId()).isEqualTo(user.getUserId()); + } + +}