From 4019283c33fe2006125ae07196d0af1301fb0dd5 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Tue, 13 Jun 2017 11:30:05 +0100 Subject: [PATCH 01/17] added updated example codes --- .../baeldung/string/StringToCharStream.java | 47 ++++++++++++------- .../string/StringToCharStreamUnitTest.java | 14 +++++- 2 files changed, 41 insertions(+), 20 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/string/StringToCharStream.java b/core-java/src/main/java/com/baeldung/string/StringToCharStream.java index 4dc04551921d..cbe4deb9a00b 100644 --- a/core-java/src/main/java/com/baeldung/string/StringToCharStream.java +++ b/core-java/src/main/java/com/baeldung/string/StringToCharStream.java @@ -12,29 +12,40 @@ public class StringToCharStream { public StringToCharStream() { - //let's use the Stream API to manipulate a string - //this will count the occurrence of each character in the test string + //let's use the Stream API to manipulate a string + //this will count the occurrence of each character in the test string - System.out.println("Counting Occurrence of Letter"); - String testString = "Noww"; + String testString = "tests"; - //we don't want to use foreach, so . . . + //first get an IntStream + IntStream intStream = testString.chars(); + IntStream intStream1 = testString.codePoints(); - Map map = new HashMap<>(); + //now let's map them + Stream characterStream = intStream.mapToObj(c -> (char) c); + Stream characterStream1 = intStream1.mapToObj(c -> (char) c); - testString.codePoints() - .mapToObj(c -> (char) c) - .filter(c -> Character.isLetter(c)) - .forEach(c -> { - if(map.containsKey(c)) { - map.put(c, map.get(c) + 1); - } else { - map.put(c, 1); - } - }); + System.out.println("Counting Occurrence of Letter"); + testString = "Noww"; + + //we don't want to use foreach, so . . . + + Map map = new HashMap<>(); + + testString.codePoints() + .mapToObj(c -> (char) c) + .filter(c -> Character.isLetter(c)) + .forEach(c -> { + if(map.containsKey(c)) { + map.put(c, map.get(c) + 1); + } else { + map.put(c, 1); + } + }); + + //printing out the result here + System.out.println(map.toString()); - //printing out the result here - System.out.println(map.toString()); } diff --git a/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java b/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java index 0c265d0b1f4d..9332ae814cd2 100644 --- a/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java +++ b/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java @@ -5,7 +5,9 @@ import java.util.stream.IntStream; import java.util.stream.Stream; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** @@ -17,12 +19,13 @@ public class StringToCharStreamUnitTest { @Test public void givenTestString_whenChars_thenReturnIntStream() { - assertTrue(testString.chars() instanceof IntStream); + + assertThat(testString.chars(), instanceOf(IntStream.class)); } @Test public void givenTestString_whenCodePoints_thenReturnIntStream() { - assertTrue(testString.codePoints() instanceof IntStream); + assertThat(testString.codePoints(), instanceOf(IntStream.class)); } @Test @@ -33,4 +36,11 @@ public void givenIntStream_whenMapToObj_thenReturnCharacterStream() { assertNotNull("IntStream returned by codePoints() did not map to Stream", characterStream1); } + @Test + public void givenIntStream_whenMapToObj_thenReturnStringStream(){ + Stream stringStream + = testString.codePoints().mapToObj(c -> String.valueOf((char) c)); + assertNotNull(stringStream); + } + } From 4c0886e3044a78c9062be417f6ff137a039dcc41 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Tue, 13 Jun 2017 17:17:47 +0100 Subject: [PATCH 02/17] updated example code StringToCharStream --- .../com/baeldung/string/StringToCharStream.java | 17 +++++++++++++++++ .../string/StringToCharStreamUnitTest.java | 15 +++++++-------- ...57\200\233[B\357\200\233[B\357\200\233[Bssc" | 0 3 files changed, 24 insertions(+), 8 deletions(-) create mode 100644 "\357\200\233[B\357\200\233[A\357\200\233[B\357\200\233[B\357\200\233[B\357\200\233[Bssc" diff --git a/core-java/src/main/java/com/baeldung/string/StringToCharStream.java b/core-java/src/main/java/com/baeldung/string/StringToCharStream.java index 06a3ca6a6338..6c2e38a54667 100644 --- a/core-java/src/main/java/com/baeldung/string/StringToCharStream.java +++ b/core-java/src/main/java/com/baeldung/string/StringToCharStream.java @@ -28,6 +28,23 @@ private StringToCharStream() { } + public static IntStream getIntStreamFromCodePoints(String test) { + return test.codePoints(); + } + + public static IntStream getIntStreamFromChars(String test) { + return test.chars(); + } + + public static Stream mapIntStreamToCharStream(IntStream intStream) { + return intStream.mapToObj(c -> (char) c); + } + + public static Stream mapIntStreamToStringStream(IntStream intStream) { + return intStream.mapToObj(c -> String.valueOf((char) c)); + } + + public static void main(String[] args) { new StringToCharStream(); diff --git a/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java b/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java index 52e38ff89822..eeb3051fc16b 100644 --- a/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java +++ b/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java @@ -8,27 +8,26 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; public class StringToCharStreamUnitTest { - private String testString = "Tests"; @Test public void givenTestString_whenChars_thenReturnIntStream() { - - assertThat(testString.chars(), instanceOf(IntStream.class)); + assertThat(StringToCharStream.getIntStreamFromChars("test"), instanceOf(IntStream.class)); } @Test public void givenTestString_whenCodePoints_thenReturnIntStream() { - assertThat(testString.codePoints(), instanceOf(IntStream.class)); + assertThat(StringToCharStream.getIntStreamFromCodePoints("test"), instanceOf(IntStream.class)); } @Test public void givenIntStream_whenMapToObj_thenReturnCharacterStream() { - Stream characterStream = testString.chars().mapToObj(c -> (char) c); - Stream characterStream1 = testString.codePoints().mapToObj(c -> (char) c); + Stream characterStream + = StringToCharStream.mapIntStreamToCharStream(StringToCharStream.getIntStreamFromChars("test")); + Stream characterStream1 + = StringToCharStream.mapIntStreamToCharStream(StringToCharStream.getIntStreamFromCodePoints("test")); assertNotNull("IntStream returned by chars() did not map to Stream", characterStream); assertNotNull("IntStream returned by codePoints() did not map to Stream", characterStream1); } @@ -36,7 +35,7 @@ public void givenIntStream_whenMapToObj_thenReturnCharacterStream() { @Test public void givenIntStream_whenMapToObj_thenReturnStringStream() { Stream stringStream - = testString.codePoints().mapToObj(c -> String.valueOf((char) c)); + = StringToCharStream.mapIntStreamToStringStream(StringToCharStream.getIntStreamFromCodePoints("test")); assertNotNull(stringStream); } diff --git "a/\357\200\233[B\357\200\233[A\357\200\233[B\357\200\233[B\357\200\233[B\357\200\233[Bssc" "b/\357\200\233[B\357\200\233[A\357\200\233[B\357\200\233[B\357\200\233[B\357\200\233[Bssc" new file mode 100644 index 000000000000..e69de29bb2d1 From 562d340b82c9886ea0680f3759fe50d8fa6b95e3 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Fri, 16 Jun 2017 11:21:10 +0100 Subject: [PATCH 03/17] deleted StringToCharStream.java locally --- .../baeldung/string/StringToCharStream.java | 53 ------------------- 1 file changed, 53 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/string/StringToCharStream.java diff --git a/core-java/src/main/java/com/baeldung/string/StringToCharStream.java b/core-java/src/main/java/com/baeldung/string/StringToCharStream.java deleted file mode 100644 index 6c2e38a54667..000000000000 --- a/core-java/src/main/java/com/baeldung/string/StringToCharStream.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.string; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -public class StringToCharStream { - - private StringToCharStream() { - String testString = "tests"; - - IntStream intStream = testString.chars(); - IntStream intStream1 = testString.codePoints(); - - Stream characterStream = intStream.mapToObj(c -> (char) c); - Stream characterStream1 = intStream1.mapToObj(c -> (char) c); - - System.out.println("Counting Occurrence of Letter"); - - Map map = "Noww".codePoints() - .mapToObj(c -> (char) c) - .filter(Character::isLetter) - .collect(Collectors.toMap(c -> c, c -> 1, Integer::sum)); - - //printing out the result here - System.out.println(map.toString()); - - } - - public static IntStream getIntStreamFromCodePoints(String test) { - return test.codePoints(); - } - - public static IntStream getIntStreamFromChars(String test) { - return test.chars(); - } - - public static Stream mapIntStreamToCharStream(IntStream intStream) { - return intStream.mapToObj(c -> (char) c); - } - - public static Stream mapIntStreamToStringStream(IntStream intStream) { - return intStream.mapToObj(c -> String.valueOf((char) c)); - } - - - public static void main(String[] args) { - - new StringToCharStream(); - - } -} From 6e3d26062aa46c28786762363fe1d9859d1a4d0a Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Fri, 16 Jun 2017 11:34:04 +0100 Subject: [PATCH 04/17] removed redundant file --- ...[A\357\200\233[B\357\200\233[B\357\200\233[B\357\200\233[Bssc" | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 "\357\200\233[B\357\200\233[A\357\200\233[B\357\200\233[B\357\200\233[B\357\200\233[Bssc" diff --git "a/\357\200\233[B\357\200\233[A\357\200\233[B\357\200\233[B\357\200\233[B\357\200\233[Bssc" "b/\357\200\233[B\357\200\233[A\357\200\233[B\357\200\233[B\357\200\233[B\357\200\233[Bssc" deleted file mode 100644 index e69de29bb2d1..000000000000 From 5397d2c97015013bcc29307e88ba6869f953be99 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Sun, 25 Jun 2017 19:28:02 +0100 Subject: [PATCH 05/17] added code for apache commons collection SetUtils --- libraries/pom.xml | 14 ++- .../commons/collections/SetUtilsUnitTest.java | 115 ++++++++++++++++++ 2 files changed, 128 insertions(+), 1 deletion(-) create mode 100644 libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index da040c9731b1..45b371061eed 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -85,6 +85,11 @@ commons-lang3 ${commons-lang.version} + + org.apache.commons + commons-collections4 + ${commons.collections.version} + org.jasypt jasypt @@ -345,7 +350,12 @@ opennlp-tools 1.8.0 - + + junit + junit + ${junit.version} + test + 0.7.0 @@ -371,6 +381,8 @@ 1.4.0 1.1.0 4.1.10.Final + 4.1 + 4.12 \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java new file mode 100644 index 000000000000..3c2949a9b12f --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java @@ -0,0 +1,115 @@ +package com.baeldung.commons.collections; + +import org.apache.commons.collections4.SetUtils; +import org.apache.commons.collections4.set.TransformedSet; +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Created by smatt on 21/06/2017. + */ +public class SetUtilsUnitTest { + + @Test(expected = IllegalArgumentException.class) + public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() { + Set sourceSet = new HashSet<>(); + sourceSet.add("London"); + sourceSet.add("Lagos"); + sourceSet.add("Error Source1"); + Set validatingSet + = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L")); + validatingSet.add("Error Source2"); + } + + @Test + public void givenTwoSets_whenDifference_thenSetView() { + Set a = new HashSet<>(); + a.add(1); + a.add(2); + a.add(5); + Set b = new HashSet<>(); + b.add(1); + b.add(2); + SetUtils.SetView result = SetUtils.difference(a, b); + assertTrue(result.size() == 1 && result.contains(5)); + } + + @Test + public void givenTwoSets_whenUnion_thenUnionResult() { + Set a = new HashSet<>(); + a.add(1); + a.add(2); + a.add(5); + Set b = new HashSet<>(); + b.add(1); + b.add(2); + Set expected = new HashSet<>(); + expected.addAll(a); + expected.addAll(b); + SetUtils.SetView union = SetUtils.union(a, b); + assertTrue(SetUtils.isEqualSet(expected, union)); + } + + @Test + public void givenTwoSets_whenIntersection_thenIntersectionResult() { + Set a = new HashSet<>(); + a.add(1); + a.add(2); + a.add(5); + Set b = new HashSet<>(); + b.add(1); + b.add(2); + Set expected = new HashSet<>(); + expected.add(1); + expected.add(2); + SetUtils.SetView intersect = SetUtils.intersection(a, b); + assertTrue(SetUtils.isEqualSet(expected, intersect)); + } + + @Test + public void givenSet_whenTransformedSet_thenTransformedResult() { + Set a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2 ); + a.add(2); + assertEquals(a.toArray()[0], 4); + + Set source = new HashSet<>(); + source.add(1); + Set newSet = TransformedSet.transformedSet(source, (e) -> e * 2); + assertEquals(newSet.toArray()[0], 2); + assertEquals(source.toArray()[0], 2); + } + + @Test + public void givenTwoSet_whenDisjunction_thenDisjunctionSet() { + Set a = new HashSet<>(); + a.add(1); + a.add(2); + a.add(5); + Set b = new HashSet<>(); + b.add(1); + b.add(2); + b.add(3); + SetUtils.SetView result = SetUtils.disjunction(a, b); + assertTrue(result.toSet().contains(5) && result.toSet().contains(3)); + } + + @Test + public void givenSet_when_OrderedSet_thenMaintainElementOrder() { + Set set = new HashSet<>(); + set.add(10); + set.add(1); + set.add(5); + System.out.println("unordered set: " + set); + + Set orderedSet = SetUtils.orderedSet(new HashSet<>()); + orderedSet.add(10); + orderedSet.add(1); + orderedSet.add(5); + System.out.println("ordered set = " + orderedSet); + } +} \ No newline at end of file From f75d80cd270e4660d3336596c111075447edfc85 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Mon, 26 Jun 2017 09:42:21 +0100 Subject: [PATCH 06/17] refactored example code --- .../commons/collections/SetUtilsUnitTest.java | 64 +++++-------------- 1 file changed, 16 insertions(+), 48 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java index 3c2949a9b12f..4d264e3aea3d 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java @@ -4,6 +4,7 @@ import org.apache.commons.collections4.set.TransformedSet; import org.junit.Test; +import java.util.Arrays; import java.util.HashSet; import java.util.Set; @@ -18,55 +19,34 @@ public class SetUtilsUnitTest { @Test(expected = IllegalArgumentException.class) public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() { Set sourceSet = new HashSet<>(); - sourceSet.add("London"); - sourceSet.add("Lagos"); - sourceSet.add("Error Source1"); + sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1")); Set validatingSet = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L")); - validatingSet.add("Error Source2"); + validatingSet.add("Err Source2"); } @Test public void givenTwoSets_whenDifference_thenSetView() { - Set a = new HashSet<>(); - a.add(1); - a.add(2); - a.add(5); - Set b = new HashSet<>(); - b.add(1); - b.add(2); + Set a = new HashSet<>(Arrays.asList(1,2,5)); + Set b = new HashSet<>(Arrays.asList(1,2)); SetUtils.SetView result = SetUtils.difference(a, b); assertTrue(result.size() == 1 && result.contains(5)); } @Test public void givenTwoSets_whenUnion_thenUnionResult() { - Set a = new HashSet<>(); - a.add(1); - a.add(2); - a.add(5); - Set b = new HashSet<>(); - b.add(1); - b.add(2); - Set expected = new HashSet<>(); - expected.addAll(a); - expected.addAll(b); + Set a = new HashSet<>(Arrays.asList(1,2,5)); + Set b = new HashSet<>(Arrays.asList(1,2)); + Set expected = new HashSet<>(Arrays.asList(1,2,5)); SetUtils.SetView union = SetUtils.union(a, b); assertTrue(SetUtils.isEqualSet(expected, union)); } @Test public void givenTwoSets_whenIntersection_thenIntersectionResult() { - Set a = new HashSet<>(); - a.add(1); - a.add(2); - a.add(5); - Set b = new HashSet<>(); - b.add(1); - b.add(2); - Set expected = new HashSet<>(); - expected.add(1); - expected.add(2); + Set a = new HashSet<>(Arrays.asList(1,2,5)); + Set b = new HashSet<>(Arrays.asList(1,2)); + Set expected = new HashSet<>(Arrays.asList(1,2)); SetUtils.SetView intersect = SetUtils.intersection(a, b); assertTrue(SetUtils.isEqualSet(expected, intersect)); } @@ -77,8 +57,7 @@ public void givenSet_whenTransformedSet_thenTransformedResult() { a.add(2); assertEquals(a.toArray()[0], 4); - Set source = new HashSet<>(); - source.add(1); + Set source = new HashSet<>(Arrays.asList(1)); Set newSet = TransformedSet.transformedSet(source, (e) -> e * 2); assertEquals(newSet.toArray()[0], 2); assertEquals(source.toArray()[0], 2); @@ -86,30 +65,19 @@ public void givenSet_whenTransformedSet_thenTransformedResult() { @Test public void givenTwoSet_whenDisjunction_thenDisjunctionSet() { - Set a = new HashSet<>(); - a.add(1); - a.add(2); - a.add(5); - Set b = new HashSet<>(); - b.add(1); - b.add(2); - b.add(3); + Set a = new HashSet<>(Arrays.asList(1,2,5)); + Set b = new HashSet<>(Arrays.asList(1,2,3)); SetUtils.SetView result = SetUtils.disjunction(a, b); assertTrue(result.toSet().contains(5) && result.toSet().contains(3)); } @Test public void givenSet_when_OrderedSet_thenMaintainElementOrder() { - Set set = new HashSet<>(); - set.add(10); - set.add(1); - set.add(5); + Set set = new HashSet<>(Arrays.asList(10,1,5)); System.out.println("unordered set: " + set); Set orderedSet = SetUtils.orderedSet(new HashSet<>()); - orderedSet.add(10); - orderedSet.add(1); - orderedSet.add(5); + orderedSet.addAll(Arrays.asList(10,1,5)); System.out.println("ordered set = " + orderedSet); } } \ No newline at end of file From 23959fc2c27fd9ef256d687349b68c49beace88b Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Sun, 16 Jul 2017 01:13:09 +0100 Subject: [PATCH 07/17] added example code for bytebuddy --- libraries/pom.xml | 11 +++ .../main/java/com/baeldung/bytebuddy/Bar.java | 16 ++++ .../main/java/com/baeldung/bytebuddy/Foo.java | 7 ++ .../baeldung/bytebuddy/ByteBuddyUnitTest.java | 89 +++++++++++++++++++ 4 files changed, 123 insertions(+) create mode 100644 libraries/src/main/java/com/baeldung/bytebuddy/Bar.java create mode 100644 libraries/src/main/java/com/baeldung/bytebuddy/Foo.java create mode 100644 libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 9093a2db031c..eebbdf3f0ee5 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -525,6 +525,16 @@ hll ${hll.version} + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + net.bytebuddy + byte-buddy-agent + ${bytebuddy.version} + 0.7.0 @@ -566,6 +576,7 @@ mytheme 1.6.0 + 1.7.1 diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java new file mode 100644 index 000000000000..d0362a6c92b6 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java @@ -0,0 +1,16 @@ +package com.baeldung.bytebuddy; + +import net.bytebuddy.implementation.bind.annotation.BindingPriority; + +public class Bar { + + @BindingPriority(3) + public static String sayHelloBar() { return "Holla in Bar!"; } + + @BindingPriority(2) + public static String sayBar() { return "bar"; } + + public String bar() { return Bar.class.getSimpleName() + " - Bar"; } + + +} diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java new file mode 100644 index 000000000000..4be06785b1c5 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java @@ -0,0 +1,7 @@ +package com.baeldung.bytebuddy; + +public class Foo { + + public String sayHelloFoo() { return "Hello in Foo!"; } + +} diff --git a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java new file mode 100644 index 000000000000..6b7364a0a5b6 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.bytebuddy; + +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.agent.ByteBuddyAgent; +import net.bytebuddy.dynamic.DynamicType; +import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; +import net.bytebuddy.dynamic.loading.ClassReloadingStrategy; +import net.bytebuddy.implementation.FixedValue; +import net.bytebuddy.implementation.MethodDelegation; +import net.bytebuddy.matcher.ElementMatchers; +import org.junit.Test; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import static net.bytebuddy.matcher.ElementMatchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class ByteBuddyUnitTest { + + @Test + public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException { + DynamicType.Unloaded unloadedType = new ByteBuddy() + .subclass(Object.class) + .method(ElementMatchers.isToString()) + .intercept(FixedValue.value("Hello World ByteBuddy!")) + .make(); + + Class dynamicType = unloadedType.load(getClass().getClassLoader()) + .getLoaded(); + + assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!"); + } + + @Test + public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception { + ByteBuddyAgent.install(); + new ByteBuddy() + .redefine(Foo.class) + .method(named("sayHelloFoo")) + .intercept(FixedValue.value("Hello Foo Redefined")) + .make() + .load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()); + Foo f = new Foo(); + assertEquals(f.sayHelloFoo(), "Hello Foo Redefined"); + } + + @Test + public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException { + + String r = new ByteBuddy() + .subclass(Foo.class) + .method( + named("sayHelloFoo") + .and(isDeclaredBy(Foo.class) + .and(returns(String.class))) + ) + .intercept(MethodDelegation.to(Bar.class)) + .make() + .load(getClass().getClassLoader()) + .getLoaded() + .newInstance() + .sayHelloFoo(); + + assertEquals(r, Bar.sayHelloBar()); + } + + @Test + public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception { + Class type = new ByteBuddy() + .subclass(Object.class) + .name("MyClassName") + .defineMethod("custom", String.class, Modifier.PUBLIC) + .intercept(MethodDelegation.to(Bar.class)) + .defineField("x", String.class, Modifier.PUBLIC) + .make() + .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) + .getLoaded(); + + Method m = type.getDeclaredMethod("custom", null); + + assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar()); + assertNotNull(type.getDeclaredField("x")); + + } + + +} From 471c1e45bb9a889fcf063732ad1d42b0655cb8f1 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Thu, 27 Jul 2017 10:42:11 +0100 Subject: [PATCH 08/17] added example code for PCollections --- libraries/pom.xml | 6 ++ .../pcollections/PCollectionsUnitTest.java | 91 +++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 6ab312a535f0..d78d1b28ec7e 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -458,6 +458,11 @@ byte-buddy-agent ${bytebuddy.version} + + org.pcollections + pcollections + ${pcollections.version} + 0.7.0 @@ -497,5 +502,6 @@ 2.0.0.0 1.6.0 1.7.1 + 2.1.2 diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java new file mode 100644 index 000000000000..b2f815074a49 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java @@ -0,0 +1,91 @@ +package com.baeldung.pcollections; + +import org.junit.Test; +import org.pcollections.*; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PCollectionsUnitTest { + + @Test + public void whenEmpty_thenCreateEmptyHashPMap() { + HashPMap pmap = HashTreePMap.empty(); + assertEquals(pmap.size(), 0); + } + + @Test + public void givenKeyValue_whenSingleton_thenCreateNonEmptyHashPMap() { + HashPMap pmap1 = HashTreePMap.singleton("key1", "value1"); + assertEquals(pmap1.size(), 1); + } + + @Test + public void givenExistingHashMap_whenFrom_thenCreateHashPMap() { + Map map = new HashMap(); + map.put("mkey1", "mval1"); + map.put("mkey2", "mval2"); + + HashPMap pmap2 = HashTreePMap.from(map); + assertEquals(pmap2.size(), 2); + } + + @Test + public void whenHashPMapMethods_thenPerformOperations() { + + HashPMap pmap = HashTreePMap.empty(); + pmap = pmap.plus("key1", "value1"); + assertEquals(pmap.size(), 1); + + Map map = new HashMap(); + map.put("key2", "val2"); + map.put("key3", "val3"); + pmap = pmap.plusAll(map); + + assertEquals(pmap.size(), 3); + + pmap = pmap.minus("key1"); + assertFalse(pmap.containsKey("key1")); + + pmap = pmap.minusAll(map.keySet()); + assertEquals(pmap.size(), 0); + + } + + @Test + public void whenTreePVectorMethods_thenPerformOperations() { + TreePVector pVector = TreePVector.empty(); + + pVector = pVector.plus("e1"); + pVector = pVector.plusAll(Arrays.asList("e2", "e3", "e4")); + assertEquals(4, pVector.size()); + + TreePVector pSub = pVector.subList(0, 2); + assertTrue(pSub.contains("e1") && pSub.contains("e2")); + + TreePVector pVW = (TreePVector) pVector.with(0, "e10"); + assertEquals(pVW.get(0), "e10"); + + pVector = pVector.minus("e1"); + TreePVector pV1 = pVector.minusAll(Arrays.asList("e2", "e3")); + assertEquals(pV1.size(), 1); + } + + @Test + public void whenMapPSetMethods_thenPerformOperations() { + + MapPSet pSet = HashTreePSet.empty() + .plusAll(Arrays.asList("e1","e2","e3","e4")); + assertEquals(pSet.size(), 4); + + pSet = pSet.minus("e4"); + assertFalse(pSet.contains("e4")); + + } + +} From 759693781a49cfd2b7a97e8e2b4cbb397988aac8 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Thu, 27 Jul 2017 10:44:54 +0100 Subject: [PATCH 09/17] update pom --- libraries/pom.xml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/libraries/pom.xml b/libraries/pom.xml index d78d1b28ec7e..a655f5267a0a 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -448,16 +448,6 @@ byte-buddy-agent ${bytebuddy.version} - - net.bytebuddy - byte-buddy - ${bytebuddy.version} - - - net.bytebuddy - byte-buddy-agent - ${bytebuddy.version} - org.pcollections pcollections From cb7dc1b9afeeb8b3e9c0e11d504c83af0dbaf3c8 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Sat, 29 Jul 2017 14:55:24 +0100 Subject: [PATCH 10/17] refactored tests for PCollections --- .../pcollections/PCollectionsUnitTest.java | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java index b2f815074a49..1fd110ddd8bc 100644 --- a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java @@ -39,53 +39,52 @@ public void givenExistingHashMap_whenFrom_thenCreateHashPMap() { public void whenHashPMapMethods_thenPerformOperations() { HashPMap pmap = HashTreePMap.empty(); - pmap = pmap.plus("key1", "value1"); - assertEquals(pmap.size(), 1); + HashPMap pmap0 = pmap.plus("key1", "value1"); Map map = new HashMap(); map.put("key2", "val2"); map.put("key3", "val3"); - pmap = pmap.plusAll(map); + HashPMap pmap1 = pmap0.plusAll(map); - assertEquals(pmap.size(), 3); + HashPMap pmap2 = pmap1.minus("key1"); - pmap = pmap.minus("key1"); - assertFalse(pmap.containsKey("key1")); - - pmap = pmap.minusAll(map.keySet()); - assertEquals(pmap.size(), 0); + HashPMap pmap3 = pmap2.minusAll(map.keySet()); + assertEquals(pmap0.size(), 1); + assertEquals(pmap1.size(), 3); + assertFalse(pmap2.containsKey("key1")); + assertEquals(pmap3.size(), 0); } @Test public void whenTreePVectorMethods_thenPerformOperations() { TreePVector pVector = TreePVector.empty(); - pVector = pVector.plus("e1"); - pVector = pVector.plusAll(Arrays.asList("e2", "e3", "e4")); - assertEquals(4, pVector.size()); + TreePVector pV1 = pVector.plus("e1"); + TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4")); + assertEquals(1, pV1.size()); + assertEquals(4, pV2.size()); + + TreePVector pV3 = pV2.minus("e1"); + TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4")); + assertEquals(pV3.size(), 3); + assertEquals(pV4.size(), 0); - TreePVector pSub = pVector.subList(0, 2); + TreePVector pSub = pV2.subList(0, 2); assertTrue(pSub.contains("e1") && pSub.contains("e2")); - TreePVector pVW = (TreePVector) pVector.with(0, "e10"); + TreePVector pVW = (TreePVector) pV2.with(0, "e10"); assertEquals(pVW.get(0), "e10"); - - pVector = pVector.minus("e1"); - TreePVector pV1 = pVector.minusAll(Arrays.asList("e2", "e3")); - assertEquals(pV1.size(), 1); } @Test public void whenMapPSetMethods_thenPerformOperations() { - MapPSet pSet = HashTreePSet.empty() .plusAll(Arrays.asList("e1","e2","e3","e4")); assertEquals(pSet.size(), 4); - pSet = pSet.minus("e4"); - assertFalse(pSet.contains("e4")); - + MapPSet pSet1 = pSet.minus("e4"); + assertFalse(pSet1.contains("e4")); } } From 4c338e63e0c2f4abca4c770aeeb7b402bdc32071 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Thu, 3 Aug 2017 08:43:19 +0100 Subject: [PATCH 11/17] spring security xml config --- jee7/.gitignore | 5 ++++ jee7/pom.xml | 3 +++ .../main/webapp/WEB-INF/spring/security.xml | 23 ++++++++++++++++ jee7/src/main/webapp/WEB-INF/web.xml | 27 +++++++++++++++++++ jee7/src/main/webapp/index.jsp | 18 +++++++++++++ jee7/src/main/webapp/secure.jsp | 24 +++++++++++++++++ 6 files changed, 100 insertions(+) create mode 100644 jee7/.gitignore create mode 100644 jee7/src/main/webapp/WEB-INF/spring/security.xml create mode 100644 jee7/src/main/webapp/index.jsp create mode 100644 jee7/src/main/webapp/secure.jsp diff --git a/jee7/.gitignore b/jee7/.gitignore new file mode 100644 index 000000000000..067348b3f408 --- /dev/null +++ b/jee7/.gitignore @@ -0,0 +1,5 @@ + +/classes/ +/.idea/ +/target/ +/jee7.iml diff --git a/jee7/pom.xml b/jee7/pom.xml index b5e0d80b6cb5..6858a05d17e3 100644 --- a/jee7/pom.xml +++ b/jee7/pom.xml @@ -6,8 +6,10 @@ com.baeldung jee7 1.0-SNAPSHOT + war JavaEE 7 Arquillian Archetype Sample + com.baeldung parent-modules @@ -174,6 +176,7 @@ maven-war-plugin ${maven-war-plugin.version} + webapp false diff --git a/jee7/src/main/webapp/WEB-INF/spring/security.xml b/jee7/src/main/webapp/WEB-INF/spring/security.xml new file mode 100644 index 000000000000..777cd9461fa3 --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/spring/security.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee7/src/main/webapp/WEB-INF/web.xml b/jee7/src/main/webapp/WEB-INF/web.xml index 11bd87cf9926..5be1bf8808e4 100644 --- a/jee7/src/main/webapp/WEB-INF/web.xml +++ b/jee7/src/main/webapp/WEB-INF/web.xml @@ -32,6 +32,33 @@ + + + + + + contextConfigLocation + + /WEB-INF/spring/*.xml + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + + springSecurityFilterChain + /* + + + + org.springframework.web.context.ContextLoaderListener + + + + index.jsf welcome.jsf diff --git a/jee7/src/main/webapp/index.jsp b/jee7/src/main/webapp/index.jsp new file mode 100644 index 000000000000..66a47eb7ce37 --- /dev/null +++ b/jee7/src/main/webapp/index.jsp @@ -0,0 +1,18 @@ +<%-- + Created by IntelliJ IDEA. + User: smatt + Date: 02/08/2017 + Time: 07:03 AM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Index Page + + + Non-secured Index Page +
+ Login + + diff --git a/jee7/src/main/webapp/secure.jsp b/jee7/src/main/webapp/secure.jsp new file mode 100644 index 000000000000..0cadd2cd4f0e --- /dev/null +++ b/jee7/src/main/webapp/secure.jsp @@ -0,0 +1,24 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %> + + + + + Home Page + + +

Home Page

+ +

+ Hello
+ Roles: +

+ +
+ + +
+ + \ No newline at end of file From d6985a389ca92134444687bd4581af8d8b61d158 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Thu, 3 Aug 2017 08:45:17 +0100 Subject: [PATCH 12/17] spring security xml config --- jee7/src/main/webapp/WEB-INF/web.xml | 34 ++++++++++++++-------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/jee7/src/main/webapp/WEB-INF/web.xml b/jee7/src/main/webapp/WEB-INF/web.xml index 5be1bf8808e4..1bcbb96e240b 100644 --- a/jee7/src/main/webapp/WEB-INF/web.xml +++ b/jee7/src/main/webapp/WEB-INF/web.xml @@ -36,26 +36,26 @@ - - contextConfigLocation - - /WEB-INF/spring/*.xml - - + + + + + + - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - + + + + - - springSecurityFilterChain - /* - + + + + - - org.springframework.web.context.ContextLoaderListener - + + + From dedd4c11e82fe5de23d908f0f2e4ea6134dc1294 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Fri, 4 Aug 2017 10:39:21 +0100 Subject: [PATCH 13/17] remove redundant comment --- jee7/src/main/webapp/index.jsp | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/jee7/src/main/webapp/index.jsp b/jee7/src/main/webapp/index.jsp index 66a47eb7ce37..93fef9713dce 100644 --- a/jee7/src/main/webapp/index.jsp +++ b/jee7/src/main/webapp/index.jsp @@ -1,10 +1,3 @@ -<%-- - Created by IntelliJ IDEA. - User: smatt - Date: 02/08/2017 - Time: 07:03 AM - To change this template use File | Settings | File Templates. ---%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> @@ -15,4 +8,4 @@
Login - + \ No newline at end of file From 57ea6593ee142c5ab407f4c1ec65e32bb44c6bf9 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Tue, 15 Aug 2017 05:39:12 +0100 Subject: [PATCH 14/17] example code for apache-shiro --- apache-shiro/.gitignore | 4 + apache-shiro/README.md | 0 apache-shiro/pom.xml | 65 +++++++++++ .../src/main/java/com/baeldung/Main.java | 85 +++++++++++++++ .../main/java/com/baeldung/MyCustomRealm.java | 102 ++++++++++++++++++ .../src/main/resources/log4j.properties | 12 +++ apache-shiro/src/main/resources/shiro.ini | 3 + 7 files changed, 271 insertions(+) create mode 100644 apache-shiro/.gitignore create mode 100644 apache-shiro/README.md create mode 100644 apache-shiro/pom.xml create mode 100644 apache-shiro/src/main/java/com/baeldung/Main.java create mode 100644 apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java create mode 100644 apache-shiro/src/main/resources/log4j.properties create mode 100644 apache-shiro/src/main/resources/shiro.ini diff --git a/apache-shiro/.gitignore b/apache-shiro/.gitignore new file mode 100644 index 000000000000..020cda48984d --- /dev/null +++ b/apache-shiro/.gitignore @@ -0,0 +1,4 @@ + +/.idea/ +/target/ +/apache-shiro.iml \ No newline at end of file diff --git a/apache-shiro/README.md b/apache-shiro/README.md new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml new file mode 100644 index 000000000000..97ed872a2641 --- /dev/null +++ b/apache-shiro/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + com.baeldung + apache-shiro + 1.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.4.0 + 1.2.17 + 1.7.25 + + + + + org.apache.shiro + shiro-core + ${apache-shiro-core-version} + + + org.slf4j + jcl-over-slf4j + ${slf4j-version} + runtime + + + org.slf4j + slf4j-log4j12 + ${slf4j-version} + runtime + + + log4j + log4j + ${log4j-version} + runtime + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.2 + + 1.8 + 1.8 + + + + + + + \ No newline at end of file diff --git a/apache-shiro/src/main/java/com/baeldung/Main.java b/apache-shiro/src/main/java/com/baeldung/Main.java new file mode 100644 index 000000000000..a58400838703 --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/Main.java @@ -0,0 +1,85 @@ +package com.baeldung; + +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.*; +import org.apache.shiro.config.IniSecurityManagerFactory; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.session.Session; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.util.Factory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Main { + + private static final transient Logger log = LoggerFactory.getLogger(Main.class); + + public static void main(String[] args) { + + Factory factory + = new IniSecurityManagerFactory("classpath:shiro.ini"); + SecurityManager securityManager = factory.getInstance(); + + SecurityUtils.setSecurityManager(securityManager); + Subject currentUser = SecurityUtils.getSubject(); + + if (!currentUser.isAuthenticated()) { + UsernamePasswordToken token + = new UsernamePasswordToken("user", "password"); + token.setRememberMe(true); + try { + currentUser.login(token); + } catch (UnknownAccountException uae) { + log.error("Username Not Found!", uae); + } catch (IncorrectCredentialsException ice) { + log.error("Invalid Credentials!", ice); + } catch (LockedAccountException lae) { + log.error("Your Account is Locked!", lae); + } catch (AuthenticationException ae) { + log.error("Unexpected Error!", ae); + } + } + + log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); + + if (currentUser.hasRole("admin")) { + log.info("Welcome Admin"); + } else if(currentUser.hasRole("editor")) { + log.info("Welcome, Editor!"); + } else if(currentUser.hasRole("author")) { + log.info("Welcome, Author"); + } else { + log.info("Welcome, Guest"); + } + + if(currentUser.isPermitted("articles:compose")) { + log.info("You can compose an article"); + } else { + log.info("You are not permitted to compose an article!"); + } + + if(currentUser.isPermitted("articles:save")) { + log.info("You can save articles"); + } else { + log.info("You can not save articles"); + } + + if(currentUser.isPermitted("articles:publish")) { + log.info("You can publish articles"); + } else { + log.info("You can not publish articles"); + } + + Session session = currentUser.getSession(); + session.setAttribute("key", "value"); + String value = (String) session.getAttribute("key"); + if (value.equals("value")) { + log.info("Retrieved the correct value! [" + value + "]"); + } + + currentUser.logout(); + + System.exit(0); + } + +} diff --git a/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java new file mode 100644 index 000000000000..8d792c76a52d --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java @@ -0,0 +1,102 @@ +package com.baeldung; + +import org.apache.shiro.authc.*; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.jdbc.JdbcRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.*; + +public class MyCustomRealm extends JdbcRealm { + + private Map credentials = new HashMap<>(); + private Map> roles = new HashMap<>(); + private Map> perm = new HashMap<>(); + + { + credentials.put("user", "password"); + credentials.put("user2", "password2"); + credentials.put("user3", "password3"); + + roles.put("user", new HashSet<>(Arrays.asList("admin"))); + roles.put("user2", new HashSet<>(Arrays.asList("editor"))); + roles.put("user3", new HashSet<>(Arrays.asList("author"))); + + perm.put("admin", new HashSet<>(Arrays.asList("*"))); + perm.put("editor", new HashSet<>(Arrays.asList("articles:*"))); + perm.put("author", + new HashSet<>(Arrays.asList("articles:compose", + "articles:save"))); + + } + + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) + throws AuthenticationException { + + UsernamePasswordToken uToken = (UsernamePasswordToken) token; + + if(uToken.getUsername() == null + || uToken.getUsername().isEmpty() + || !credentials.containsKey(uToken.getUsername()) + ) { + throw new UnknownAccountException("username not found!"); + } + + + return new SimpleAuthenticationInfo( + uToken.getUsername(), credentials.get(uToken.getUsername()), + getName()); + } + + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { + Set roleNames = new HashSet<>(); + Set permissions = new HashSet<>(); + + principals.forEach(p -> { + try { + Set roles = getRoleNamesForUser(null, (String) p); + roleNames.addAll(roles); + permissions.addAll(getPermissions(null, null,roles)); + } catch (SQLException e) { + e.printStackTrace(); + } + }); + + SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); + info.setStringPermissions(permissions); + return info; + } + + @Override + protected Set getRoleNamesForUser(Connection conn, String username) throws SQLException { + if(!roles.containsKey(username)) { + throw new SQLException("username not found!"); + } + + return roles.get(username); + } + + @Override + protected Set getPermissions(Connection conn, String username, Collection roleNames) throws SQLException { + for (String role : roleNames) { + if (!perm.containsKey(role)) { + throw new SQLException("role not found!"); + } + } + + Set finalSet = new HashSet<>(); + for (String role : roleNames) { + finalSet.addAll(perm.get(role)); + } + + return finalSet; + } + +} diff --git a/apache-shiro/src/main/resources/log4j.properties b/apache-shiro/src/main/resources/log4j.properties new file mode 100644 index 000000000000..897bf08221dc --- /dev/null +++ b/apache-shiro/src/main/resources/log4j.properties @@ -0,0 +1,12 @@ +log4j.rootLogger=INFO, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n + +log4j.logger.org.apache=WARN + +log4j.logger.org.apache.shiro=INFO + +log4j.logger.org.apache.shiro.util.ThreadContext=WARN +log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN \ No newline at end of file diff --git a/apache-shiro/src/main/resources/shiro.ini b/apache-shiro/src/main/resources/shiro.ini new file mode 100644 index 000000000000..a75f59101502 --- /dev/null +++ b/apache-shiro/src/main/resources/shiro.ini @@ -0,0 +1,3 @@ +jdbcRealm = com.baeldung.MyCustomRealm + +securityManager.realms = $jdbcRealm \ No newline at end of file From e3fed15627ee375562eec33e659d7acb83bd3305 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Mon, 21 Aug 2017 09:43:23 +0100 Subject: [PATCH 15/17] updated example code for Vavr Collections --- .../collections/CollectionAPIUnitTest.java | 169 +++++++++++------- 1 file changed, 107 insertions(+), 62 deletions(-) diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java index 4b4eb55fc5f9..1de428739d05 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -30,16 +30,68 @@ public class CollectionAPIUnitTest { + + @Test + public void givenParams_whenListAPI_thenCorrect() { + + List list = List.of("Java", "PHP", "Jquery", "JavaScript", "JShell", "JAVA"); + + List list1 = list.drop(2); + assertFalse(list1.contains("Java") && list1.contains("PHP")); + + List list2 = list.dropRight(2); + assertFalse(list2.contains("JAVA") && list2.contains("JShell")); + + List list3 = list.dropUntil(s -> s.contains("Shell")); + assertEquals(list3.size(), 2); + + List list4 = list.dropWhile(s -> s.length() > 0); + assertTrue(list4.isEmpty()); + + List list5 = list.take(1); + assertEquals(list5.single(), "Java"); + + List list6 = list.takeRight(1); + assertEquals(list6.single(), "JAVA"); + + List list7 = list.takeUntil(s -> s.length() > 6); + assertEquals(list7.size(), 3); + + //distinct + List list8 = list.distinctBy( (s1, s2) -> s1.startsWith(s2.charAt(0)+"") ? 0 : 1); + assertEquals(list8.size(), 2); + + //groupBY + Iterator> iterator = list.grouped(2); + assertEquals(iterator.head().size(), 2); + + Map> map = list.groupBy(e -> e.startsWith("J")); + assertEquals(map.size(), 2); + assertEquals(map.get(false).get().size(), 1); + assertEquals(map.get(true).get().size(), 5); + + //interperse + String words = List.of("Boys", "Girls") + .intersperse("and") + .reduce((s1, s2) -> s1.concat( " " + s2 )) + .trim(); + + assertEquals(words, "Boys and Girls"); + + } + @Test - public void givenEmptyList_whenStacked_thenCorrect() { + public void givenEmptyList_whenStackAPI_thenCorrect() { + List intList = List.empty(); - List anotherList = intList.push(4) - .push(0); - Iterator iterator = anotherList.iterator(); + List intList1 = intList.pushAll(List.rangeClosed(5,10)); + + assertEquals(intList1.peek(), Integer.valueOf(10)); + + List intList2 = intList1.pop(); + assertEquals(intList2.size(), (intList1.size() - 1) ); - assertEquals(new Integer(0), iterator.next()); - assertEquals(new Integer(4), iterator.next()); } @Test @@ -61,27 +113,33 @@ public void givenList_whenPrependTail_thenCorrect() { @Test public void givenQueue_whenEnqueued_thenCorrect() { + Queue queue = Queue.of(1, 2, 3); - Queue secondQueue = queue.enqueue(4) - .enqueue(5); + Queue secondQueue = queue.enqueueAll(List.of(4,5)); assertEquals(3, queue.size()); assertEquals(5, secondQueue.size()); Tuple2> result = secondQueue.dequeue(); - Integer headValue = result.apply((head, tail) -> head); - assertEquals(new Integer(1), headValue); + assertEquals(Integer.valueOf(1), result._1); - Iterator iterator = result.apply((head, tail) -> tail.iterator()); - - assertEquals(new Integer(2), iterator.next()); - assertEquals(new Integer(3), iterator.next()); - assertEquals(new Integer(4), iterator.next()); - assertEquals(new Integer(5), iterator.next()); + Queue tailQueue = result._2; + assertFalse(tailQueue.contains(secondQueue.get(0))); } @Test public void givenStream_whenProcessed_thenCorrect() { + + Stream s1 = Stream.tabulate(5, (i)-> i + 1); + assertEquals(s1.get(2).intValue(), 3); + + Stream s = Stream.of(2,1,3,4); + + Stream> s2 = s.zip(List.of(7,8,9)); + Tuple2 t1 = s2.get(0); + assertEquals(t1._1().intValue(), 2); + assertEquals(t1._2().intValue(), 7); + Stream intStream = Stream.iterate(0, i -> i + 1) .take(10); @@ -92,7 +150,6 @@ public void givenStream_whenProcessed_thenCorrect() { .longValue(); assertEquals(20, evenSum); - assertEquals(new Integer(5), intStream.get(5)); } @Test @@ -102,11 +159,12 @@ public void givenArray_whenQueried_thenCorrect() { assertEquals(3, intArray.size()); assertEquals(2, newArray.size()); + assertEquals(3, newArray.get(1).intValue()); + + Array array2 = intArray.replace(1, 5); + assertEquals(array2.get(0).intValue(), 5); + - assertEquals(new Integer(1), intArray.get(0)); - assertEquals(new Integer(2), intArray.get(1)); - assertEquals(new Integer(3), intArray.get(2)); - assertEquals(new Integer(3), newArray.get(1)); } @Test @@ -117,10 +175,8 @@ public void givenVector_whenQueried_thenCorrect() { assertEquals(4, intVector.size()); assertEquals(4, newVector.size()); - assertEquals(new Integer(1), intVector.get(0)); - assertEquals(new Integer(2), intVector.get(1)); - assertEquals(new Integer(3), intVector.get(2)); - assertEquals(new Integer(6), newVector.get(1)); + assertEquals(2, intVector.get(1).intValue()); + assertEquals(6, newVector.get(1).intValue()); } @Test @@ -143,57 +199,48 @@ public void givenHashSet_whenModified_thenCorrect() { assertEquals(3, set.size()); assertEquals(4, newSet.size()); - assertFalse(set.contains("Yellow")); assertTrue(newSet.contains("Yellow")); } @Test public void givenSortedSet_whenIterated_thenCorrect() { SortedSet set = TreeSet.of("Red", "Green", "Blue"); + assertEquals("Blue", set.head()); - Iterator iterator = set.iterator(); - assertEquals("Blue", iterator.next()); - assertEquals("Green", iterator.next()); - assertEquals("Red", iterator.next()); + SortedSet intSet = TreeSet.of(1,2,3); + assertEquals(2, intSet.average().get().intValue()); + } @Test public void givenSortedSet_whenReversed_thenCorrect() { - SortedSet set = TreeSet.of(Comparator.reverseOrder(), "Green", "Red", "Blue"); + SortedSet set = TreeSet.of( "Green", "Red", "Blue"); + assertEquals("Blue", set.head()); + + SortedSet reversedSet = set.toSortedSet(Comparator.reverseOrder()); + assertEquals("Red", reversedSet.head()); - Iterator iterator = set.iterator(); - assertEquals("Red", iterator.next()); - assertEquals("Green", iterator.next()); - assertEquals("Blue", iterator.next()); + String str = set.mkString(" and "); + assertEquals("Blue and Green and Red", str); } @Test public void givenMap_whenIterated_thenCorrect() { Map> map = List.rangeClosed(0, 10) .groupBy(i -> i % 2); - + assertEquals(2, map.size()); - - Iterator>> iterator = map.iterator(); - assertEquals(6, iterator.next() - ._2() - .size()); - assertEquals(5, iterator.next() - ._2() - .size()); + assertEquals(6, map.get(0).get().size()); + assertEquals(5, map.get(1).get().size()); } @Test public void givenTreeMap_whenIterated_thenCorrect() { - SortedMap map = TreeMap.of(3, "Three", 2, "Two", 4, "Four", 1, "One"); - - Iterator> iterator = map.iterator(); - assertEquals(new Integer(1), iterator.next() - ._1()); - assertEquals(new Integer(2), iterator.next() - ._1()); - assertEquals(new Integer(3), iterator.next() - ._1()); + SortedMap map + = TreeMap.of(3, "Three", 2, "Two", 4, "Four", 1, "One"); + + assertEquals(1, map.keySet().toJavaArray()[0]); + assertEquals("Four", map.get(4).get()); } @Test @@ -202,14 +249,13 @@ public void givenJavaList_whenConverted_thenCorrect() { List vavrList = List.ofAll(javaList); assertEquals(4, vavrList.size()); - assertEquals(new Integer(1), vavrList.head()); + assertEquals(1, vavrList.head().intValue()); java.util.stream.Stream javaStream = javaList.stream(); Set vavrSet = HashSet.ofAll(javaStream); assertEquals(4, vavrSet.size()); - assertEquals(new Integer(2), vavrSet.tail() - .head()); + assertEquals(2, vavrSet.tail().head().intValue()); } @Test @@ -220,7 +266,7 @@ public void givenJavaStream_whenCollected_thenCorrect() { .collect(List.collector()); assertEquals(4, vavrList.size()); - assertEquals(new Integer(2), vavrList.head()); + assertEquals(2, vavrList.head().intValue()); } @Test @@ -231,7 +277,7 @@ public void givenVavrList_whenConverted_thenCorrect() { java.util.Map map = List.of("1", "2", "3") .toJavaMap(i -> Tuple.of(i, Integer.valueOf(i))); - assertEquals(new Integer(2), map.get("2")); + assertEquals(2, map.get("2").intValue()); } @Test @@ -240,8 +286,7 @@ public void givenVavrList_whenCollected_thenCorrect() { .collect(Collectors.toSet()); assertEquals(3, javaSet.size()); - assertEquals(new Integer(1), javaSet.iterator() - .next()); + assertEquals(1, javaSet.toArray()[0]); } @Test @@ -250,7 +295,7 @@ public void givenVavrList_whenConvertedView_thenCorrect() { .asJavaMutable(); javaList.add(4); - assertEquals(new Integer(4), javaList.get(3)); + assertEquals(4, javaList.get(3).intValue()); } @Test(expected = UnsupportedOperationException.class) @@ -258,7 +303,7 @@ public void givenVavrList_whenConvertedView_thenException() { java.util.List javaList = List.of(1, 2, 3) .asJava(); - assertEquals(new Integer(3), javaList.get(2)); + assertEquals(3, javaList.get(2).intValue()); javaList.add(4); } From 17ce271e8d6bd7c0c4c1ff22cfd85d2c2a0399e8 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Mon, 21 Aug 2017 12:11:27 +0100 Subject: [PATCH 16/17] updated Vavr's Collection example --- .../vavr/collections/CollectionAPIUnitTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java index 1de428739d05..3db43148ebf4 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -34,7 +34,8 @@ public class CollectionAPIUnitTest { @Test public void givenParams_whenListAPI_thenCorrect() { - List list = List.of("Java", "PHP", "Jquery", "JavaScript", "JShell", "JAVA"); + List list + = List.of("Java", "PHP", "Jquery", "JavaScript", "JShell", "JAVA"); List list1 = list.drop(2); assertFalse(list1.contains("Java") && list1.contains("PHP")); @@ -58,7 +59,8 @@ public void givenParams_whenListAPI_thenCorrect() { assertEquals(list7.size(), 3); //distinct - List list8 = list.distinctBy( (s1, s2) -> s1.startsWith(s2.charAt(0)+"") ? 0 : 1); + List list8 + = list.distinctBy( (s1, s2) -> s1.startsWith(s2.charAt(0)+"") ? 0 : 1); assertEquals(list8.size(), 2); //groupBY @@ -214,14 +216,12 @@ public void givenSortedSet_whenIterated_thenCorrect() { @Test public void givenSortedSet_whenReversed_thenCorrect() { - SortedSet set = TreeSet.of( "Green", "Red", "Blue"); - assertEquals("Blue", set.head()); - - SortedSet reversedSet = set.toSortedSet(Comparator.reverseOrder()); + SortedSet reversedSet + = TreeSet.of(Comparator.reverseOrder(), "Green", "Red", "Blue"); assertEquals("Red", reversedSet.head()); - String str = set.mkString(" and "); - assertEquals("Blue and Green and Red", str); + String str = reversedSet.mkString(" and "); + assertEquals("Red and Green and Blue", str); } @Test From 31c5db1aa63d09ce771604eea707f2caf124043a Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Thu, 24 Aug 2017 16:22:38 +0100 Subject: [PATCH 17/17] updated Vavr Collection file --- .../com/baeldung/vavr/collections/CollectionAPIUnitTest.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java index 3db43148ebf4..cfc789a8375a 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -58,12 +58,10 @@ public void givenParams_whenListAPI_thenCorrect() { List list7 = list.takeUntil(s -> s.length() > 6); assertEquals(list7.size(), 3); - //distinct List list8 = list.distinctBy( (s1, s2) -> s1.startsWith(s2.charAt(0)+"") ? 0 : 1); assertEquals(list8.size(), 2); - //groupBY Iterator> iterator = list.grouped(2); assertEquals(iterator.head().size(), 2); @@ -72,7 +70,6 @@ public void givenParams_whenListAPI_thenCorrect() { assertEquals(map.get(false).get().size(), 1); assertEquals(map.get(true).get().size(), 5); - //interperse String words = List.of("Boys", "Girls") .intersperse("and") .reduce((s1, s2) -> s1.concat( " " + s2 ))