diff --git a/Twitter4J/pom.xml b/Twitter4J/pom.xml index 80236a2cd4..982c1adc23 100644 --- a/Twitter4J/pom.xml +++ b/Twitter4J/pom.xml @@ -1,13 +1,9 @@ 4.0.0 - - com.mabsisa Twitter4J jar - 1.0-SNAPSHOT Twitter4J - http://maven.apache.org com.baeldung @@ -23,27 +19,6 @@ - - ${project.artifactId} - - - src/main/resources - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/ApplicationTest.java - - - - - - 4.0.6 diff --git a/activejdbc/pom.xml b/activejdbc/pom.xml index 0c8047f10b..542e674ff3 100644 --- a/activejdbc/pom.xml +++ b/activejdbc/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung activejdbc 1.0-SNAPSHOT jar @@ -79,55 +78,11 @@ - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - brief - true - false - - **/*Spec*.java - **/*Test*.java - - - **/helpers/* - **/*$* - - - - - - snapshots1 - JavaLite Snapshots1 - http://repo.javalite.io/ - - true - always - warn - - - - - - - snapshots2 - JavaLite Snapshots2 - http://repo.javalite.io/ - - true - always - warn - - - - - 1.4.13 + 2.0 development.test,development 5.1.34 diff --git a/activejdbc/src/main/java/com/baeldung/model/Employee.java b/activejdbc/src/main/java/com/baeldung/model/Employee.java index b7fa8aaf1f..e6e9be2aac 100644 --- a/activejdbc/src/main/java/com/baeldung/model/Employee.java +++ b/activejdbc/src/main/java/com/baeldung/model/Employee.java @@ -16,4 +16,8 @@ public class Employee extends Model { set("created_by",createdBy); } + public String getLastName() { + return getString("last_name"); + } + } diff --git a/activejdbc/src/main/java/com/baeldung/model/Role.java b/activejdbc/src/main/java/com/baeldung/model/Role.java index 3f425dbe6b..bbd5a7d169 100644 --- a/activejdbc/src/main/java/com/baeldung/model/Role.java +++ b/activejdbc/src/main/java/com/baeldung/model/Role.java @@ -15,4 +15,8 @@ public class Role extends Model { set("role_name",role); set("created_by",createdBy); } + + public String getRoleName() { + return getString("role_name"); + } } diff --git a/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppTest.java b/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java similarity index 97% rename from activejdbc/src/test/java/com/baeldung/ActiveJDBCAppTest.java rename to activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java index 316dc34712..22eb87f930 100644 --- a/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppTest.java +++ b/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java @@ -7,7 +7,7 @@ import org.junit.Test; import java.util.List; -public class ActiveJDBCAppTest extends DBSpec +public class ActiveJDBCAppManualTest extends DBSpec { @Test public void ifEmployeeCreated_thenIsValid() { diff --git a/algorithms/roundUpToHundred/.gitignore b/algorithms/roundUpToHundred/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/algorithms/roundUpToHundred/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java new file mode 100644 index 0000000000..f5024c227d --- /dev/null +++ b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java @@ -0,0 +1,20 @@ +package com.java.src; + +import java.util.Scanner; + +public class RoundUpToHundred { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + double input = scanner.nextDouble(); + scanner.close(); + + RoundUpToHundred.round(input); + } + + static long round(double input) { + long i = (long) Math.ceil(input); + return ((i + 99) / 100) * 100; + }; + +} diff --git a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java new file mode 100644 index 0000000000..f35a9a249f --- /dev/null +++ b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java @@ -0,0 +1,14 @@ +package com.java.src; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class RoundUpToHundredTest { + @Test + public void givenInput_whenRound_thenRoundUpToTheNearestHundred() { + assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99)); + assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2)); + assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400)); + } +} diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml index 3a72804ab1..98d9563284 100644 --- a/apache-shiro/pom.xml +++ b/apache-shiro/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung apache-shiro 1.0-SNAPSHOT @@ -36,13 +35,11 @@ org.slf4j jcl-over-slf4j - ${slf4j-version} runtime org.slf4j slf4j-log4j12 - ${slf4j-version} runtime @@ -53,26 +50,9 @@ - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - - 1.4.0 - 3.7.0 - 1.8 1.2.17 - 1.7.25 \ No newline at end of file diff --git a/asm/pom.xml b/asm/pom.xml index 7bbaa2a8f1..5aad2a0e37 100644 --- a/asm/pom.xml +++ b/asm/pom.xml @@ -42,14 +42,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - -javaagent:"C:\asm-1.0.jar" - - diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 22d1522fbe..2291da9084 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - com.baeldung cas-secured-app - 0.0.1-SNAPSHOT jar cas-secured-app - Demo project for Spring Boot + Demo project for CAS parent-boot-1 @@ -60,10 +58,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml index a15b4b58d5..9b61aaec3d 100644 --- a/cas/cas-server/pom.xml +++ b/cas/cas-server/pom.xml @@ -2,11 +2,17 @@ 4.0.0 - com.baeldung cas-server war 1.0 + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 + + org.apereo.cas @@ -39,7 +45,6 @@ org.springframework.boot spring-boot-maven-plugin - ${springboot.version} ${mainClassName} true @@ -74,42 +79,10 @@ - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - cas - - - sonatype-releases - http://oss.sonatype.org/content/repositories/releases/ - - false - - - true - - - - sonatype-snapshots - https://oss.sonatype.org/content/repositories/snapshots/ - - true - - - false - - - - shibboleth-releases - https://build.shibboleth.net/nexus/content/repositories/releases - - - @@ -214,8 +187,7 @@ - 5.3.0-SNAPSHOT - 1.5.13.RELEASE + 5.3.3 -tomcat @@ -223,14 +195,12 @@ false ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF - 1.8 - 1.8 - UTF-8 0.0.4 2.6 3.3 + 0.3.0 1.1.0 - \ No newline at end of file + diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index 92e4278593..d0c3c25beb 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -63,6 +63,12 @@ jmh-generator-annprocess ${openjdk.jmh.version} + + org.apache.commons + commons-exec + 1.3 + + diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningArrays.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningArrays.java new file mode 100644 index 0000000000..2ad48033c0 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningArrays.java @@ -0,0 +1,39 @@ +package com.baeldung.combiningcollections; + +import java.util.Arrays; +import java.util.stream.Stream; + +import org.apache.commons.lang3.ArrayUtils; + +import com.google.common.collect.ObjectArrays; + +public class CombiningArrays { + + public static Object[] usingNativeJava(Object[] first, Object[] second) { + Object[] combined = new Object[first.length + second.length]; + System.arraycopy(first, 0, combined, 0, first.length); + System.arraycopy(second, 0, combined, first.length, second.length); + return combined; + } + + public static Object[] usingJava8ObjectStream(Object[] first, Object[] second) { + Object[] combined = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(); + return combined; + } + + public static Object[] usingJava8FlatMaps(Object[] first, Object[] second) { + Object[] combined = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new); + return combined; + } + + public static Object[] usingApacheCommons(Object[] first, Object[] second) { + Object[] combined = ArrayUtils.addAll(first, second); + return combined; + } + + public static Object[] usingGuava(Object[] first, Object[] second) { + Object [] combined = ObjectArrays.concat(first, second, Object.class); + return combined; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningLists.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningLists.java new file mode 100644 index 0000000000..3fdf672758 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningLists.java @@ -0,0 +1,46 @@ +package com.baeldung.combiningcollections; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.collections4.ListUtils; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +public class CombiningLists { + + public static List usingNativeJava(List first, List second) { + List combined = new ArrayList<>(); + combined.addAll(first); + combined.addAll(second); + return combined; + } + + public static List usingJava8ObjectStream(List first, List second) { + List combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toList()); + return combined; + } + + public static List usingJava8FlatMaps(List first, List second) { + List combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toList()); + return combined; + } + + public static List usingApacheCommons(List first, List second) { + List combined = ListUtils.union(first, second); + return combined; + } + + public static List usingGuava(List first, List second) { + Iterable combinedIterables = Iterables.unmodifiableIterable( + Iterables.concat(first, second)); + + List combined = Lists.newArrayList(combinedIterables); + return combined; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningMaps.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningMaps.java new file mode 100644 index 0000000000..d8bbd01ed3 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningMaps.java @@ -0,0 +1,47 @@ +package com.baeldung.combiningcollections; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.exec.util.MapUtils; + +import com.google.common.collect.ImmutableMap; + +public class CombiningMaps { + + public static Map usingPlainJava(Map first, Map second) { + Map combined = new HashMap<>(); + combined.putAll(first); + combined.putAll(second); + return combined; + } + + public static Map usingJava8ForEach(Map first, Map second) { + second.forEach((key, value) -> first.merge(key, value, String::concat)); + return first; + } + + public static Map usingJava8FlatMaps(Map first, Map second) { + Map combined = Stream.of(first, second).map(Map::entrySet).flatMap(Collection::stream) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, String::concat)); + return combined; + + } + + public static Map usingApacheCommons(Map first, Map second) { + Map combined = MapUtils.merge(first, second); + return combined; + } + + public static Map usingGuava(Map first, Map second) { + Map combined = ImmutableMap.builder() + .putAll(first) + .putAll(second) + .build(); + return combined; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningSets.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningSets.java new file mode 100644 index 0000000000..5f531c1d43 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningSets.java @@ -0,0 +1,42 @@ +package com.baeldung.combiningcollections; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.collections4.SetUtils; + +import com.google.common.collect.Sets; + +public class CombiningSets { + + public static Set usingNativeJava(Set first, Set second) { + Set combined = new HashSet<>(); + combined.addAll(first); + combined.addAll(second); + return combined; + } + + public static Set usingJava8ObjectStream(Set first, Set second) { + Set combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toSet()); + return combined; + } + + public static Set usingJava8FlatMaps(Set first, Set second) { + Set combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toSet()); + return combined; + } + + public static Set usingApacheCommons(Set first, Set second) { + Set combined = SetUtils.union(first, second); + return combined; + } + + public static Set usingGuava(Set first, Set second) { + Set combined = Sets.union(first, second); + return combined; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java index d811cfbb7d..1ed4410371 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java @@ -44,4 +44,12 @@ public class Employee { result = 31 * result + name.hashCode(); return result; } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } } diff --git a/core-java-collections/src/main/java/com/baeldung/sort/Employee.java b/core-java-collections/src/main/java/com/baeldung/sort/Employee.java new file mode 100644 index 0000000000..b5e56f6141 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/sort/Employee.java @@ -0,0 +1,60 @@ +package com.baeldung.sort; + +public class Employee implements Comparable { + + private Long id; + private String name; + + public Employee(Long id, String name) { + this.name = name; + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Employee employee = (Employee) o; + + if (!id.equals(employee.id)) return false; + return name.equals(employee.name); + + } + + @Override + public int hashCode() { + int result = id.hashCode(); + result = 31 * result + name.hashCode(); + return result; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } + + @Override + public int compareTo(Employee employee) { + return (int)(this.id - employee.getId()); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java new file mode 100644 index 0000000000..b8a2b32060 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -0,0 +1,104 @@ +package com.baeldung.sort; + +import com.google.common.base.Functions; +import com.google.common.collect.ImmutableSortedMap; +import com.google.common.collect.Lists; +import com.google.common.collect.Ordering; + +import java.util.*; +import java.util.stream.Collectors; + +public class SortHashMap { + + private static Map map = new HashMap<>(); + + public static void main(String[] args) { + + initialize(); + + treeMapSortByKey(); + + arrayListSortByValue(); + arrayListSortByKey(); + + sortStream(); + + sortGuava(); + + addDuplicates(); + + treeSetByKey(); + treeSetByValue(); + + } + + private static void sortGuava() { + final Ordering naturalOrdering = + Ordering.natural().onResultOf(Functions.forMap(map, null)); + + System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering)); + } + + private static void sortStream() { + map.entrySet().stream() + .sorted(Map.Entry.comparingByKey().reversed()) + .forEach(System.out::println); + + Map result = map.entrySet().stream() + .sorted(Map.Entry.comparingByValue()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, + (oldValue, newValue) -> oldValue, LinkedHashMap::new)); + + result.entrySet().forEach(System.out::println); + } + + private static void treeSetByValue() { + SortedSet values = new TreeSet<>(map.values()); + System.out.println(values); + } + + private static void treeSetByKey() { + SortedSet keysSet = new TreeSet<>(map.keySet()); + System.out.println(keysSet); + } + + private static void treeMapSortByKey() { + TreeMap sorted = new TreeMap<>(map); + sorted.putAll(map); + + sorted.entrySet().forEach(System.out::println); + + } + + private static void arrayListSortByValue() { + List employeeById = new ArrayList<>(map.values()); + + Collections.sort(employeeById); + + System.out.println(employeeById); + } + + private static void arrayListSortByKey() { + List employeeByKey = new ArrayList<>(map.keySet()); + Collections.sort(employeeByKey); + System.out.println(employeeByKey); + } + + private static void initialize() { + Employee employee1 = new Employee(1L, "Mher"); + map.put(employee1.getName(), employee1); + Employee employee2 = new Employee(22L, "Annie"); + map.put(employee2.getName(), employee2); + Employee employee3 = new Employee(8L, "John"); + map.put(employee3.getName(), employee3); + Employee employee4 = new Employee(2L, "George"); + map.put(employee4.getName(), employee4); + } + + private static void addDuplicates() { + Employee employee5 = new Employee(1L, "Mher"); + map.put(employee5.getName(), employee5); + Employee employee6 = new Employee(22L, "Annie"); + map.put(employee6.getName(), employee6); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningArraysUnitTest.java b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningArraysUnitTest.java new file mode 100644 index 0000000000..3b80d773ad --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningArraysUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.combiningcollections; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class CombiningArraysUnitTest { + private static final String first[] = { + "One", + "Two", + "Three" + }; + + private static final String second[] = { + "Four", + "Five", + "Six" + }; + + private static final String expected[] = { + "One", + "Two", + "Three", + "Four", + "Five", + "Six" + }; + + @Test + public void givenTwoArrays_whenUsingNativeJava_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingNativeJava(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingObjectStreams_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingJava8ObjectStream(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingFlatMaps_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingJava8FlatMaps(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingApacheCommons_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingApacheCommons(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingGuava_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingGuava(first, second)); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningListsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningListsUnitTest.java new file mode 100644 index 0000000000..c5851d7daf --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningListsUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.combiningcollections; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class CombiningListsUnitTest { + private static final List first = Arrays.asList(new Object[]{ + "One", + "Two", + "Three" + }); + + private static final List second = Arrays.asList(new Object[]{ + "Four", + "Five", + "Six" + }); + + private static final List expected = Arrays.asList(new Object[]{ + "One", + "Two", + "Three", + "Four", + "Five", + "Six" + }); + + @Test + public void givenTwoLists_whenUsingNativeJava_thenArraysCombined() { + assertThat(CombiningLists.usingNativeJava(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingObjectStreams_thenArraysCombined() { + assertThat(CombiningLists.usingJava8ObjectStream(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingFlatMaps_thenArraysCombined() { + assertThat(CombiningLists.usingJava8FlatMaps(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingApacheCommons_thenArraysCombined() { + assertThat(CombiningLists.usingApacheCommons(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingGuava_thenArraysCombined() { + assertThat(CombiningLists.usingGuava(first, second), is(expected)); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningMapsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningMapsUnitTest.java new file mode 100644 index 0000000000..3fa9cc7dc4 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningMapsUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.combiningcollections; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class CombiningMapsUnitTest { + private static final Map first = new HashMap<>(); + private static final Map second = new HashMap<>(); + private static Map expected = new HashMap<>(); + + static { + first.put("one", "first String"); + first.put("two", "second String"); + + second.put("three", "third String"); + second.put("four", "fourth String"); + + expected.put("one", "first String"); + expected.put("two", "second String"); + expected.put("three", "third String"); + expected.put("four", "fourth String"); + } + + @Test + public void givenTwoMaps_whenUsingNativeJava_thenMapsCombined() { + assertThat(CombiningMaps.usingPlainJava(first, second), is(expected)); + } + + + @Test + public void givenTwoMaps_whenUsingForEach_thenMapsCombined() { + assertThat(CombiningMaps.usingJava8ForEach(first, second), is(expected)); + } + + @Test + public void givenTwoMaps_whenUsingFlatMaps_thenMapsCombined() { + assertThat(CombiningMaps.usingJava8FlatMaps(first, second), is(expected)); + } + + @Test + public void givenTwoMaps_whenUsingApacheCommons_thenMapsCombined() { + assertThat(CombiningMaps.usingApacheCommons(first, second), is(expected)); + } + + @Test + public void givenTwoMaps_whenUsingGuava_thenMapsCombined() { + assertThat(CombiningMaps.usingGuava(first, second), is(expected)); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningSetsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningSetsUnitTest.java new file mode 100644 index 0000000000..330827bdc2 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningSetsUnitTest.java @@ -0,0 +1,45 @@ + +package com.baeldung.combiningcollections; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; + +public class CombiningSetsUnitTest { + private static final Set first = new HashSet(Arrays.asList(new Object[] { "One", "Two", "Three" })); + + private static final Set second = new HashSet(Arrays.asList(new Object[] { "Four", "Five", "Six" })); + + private static final Set expected = new HashSet(Arrays + .asList(new Object[] { "One", "Two", "Three", "Four", "Five", "Six" })); + + @Test + public void givenTwoSets_whenUsingNativeJava_thenArraysCombined() { + assertThat(CombiningSets.usingNativeJava(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingObjectStreams_thenArraysCombined() { + assertThat(CombiningSets.usingJava8ObjectStream(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingFlatMaps_thenArraysCombined() { + assertThat(CombiningSets.usingJava8FlatMaps(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingApacheCommons_thenArraysCombined() { + assertThat(CombiningSets.usingApacheCommons(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingGuava_thenArraysCombined() { + assertThat(CombiningSets.usingGuava(first, second), is(expected)); + } +} \ No newline at end of file diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml index bc71fb8838..cf3e950cb8 100644 --- a/core-java-io/pom.xml +++ b/core-java-io/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung core-java-io 0.1.0-SNAPSHOT jar @@ -166,36 +165,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - - true - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - repackage - - - spring-boot - org.baeldung.executable.ExecutableMavenJar - - - - org.codehaus.mojo exec-maven-plugin @@ -229,32 +198,6 @@ integration - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - org.codehaus.mojo exec-maven-plugin @@ -310,14 +253,11 @@ 1.7.0 - 1.8 - 1.8 3.0.0-M1 2.4.0 2.1.0.1 1.19 2.4.5 - 2.0.4.RELEASE \ No newline at end of file diff --git a/core-java-io/src/main/java/com/baeldung/zip/ZipDirectory.java b/core-java-io/src/main/java/com/baeldung/zip/ZipDirectory.java index 7da71a093d..42147b07db 100644 --- a/core-java-io/src/main/java/com/baeldung/zip/ZipDirectory.java +++ b/core-java-io/src/main/java/com/baeldung/zip/ZipDirectory.java @@ -24,6 +24,13 @@ public class ZipDirectory { return; } if (fileToZip.isDirectory()) { + if (fileName.endsWith("/")) { + zipOut.putNextEntry(new ZipEntry(fileName)); + zipOut.closeEntry(); + } else { + zipOut.putNextEntry(new ZipEntry(fileName + "/")); + zipOut.closeEntry(); + } final File[] children = fileToZip.listFiles(); for (final File childFile : children) { zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); diff --git a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java index 7968967679..6a020f5eae 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java @@ -1,6 +1,7 @@ package com.baeldung.file; import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Test; @@ -120,4 +121,14 @@ public class FileOperationsManualTest { return resultStringBuilder.toString(); } + + @Test + public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException { + String expectedData = "This is a content of the file"; + + FileInputStream fis = new FileInputStream("src/test/resources/fileToRead.txt"); + String data = IOUtils.toString(fis, "UTF-8"); + + assertEquals(expectedData, data.trim()); + } } \ No newline at end of file diff --git a/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleUnitTest.java b/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java similarity index 96% rename from core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleUnitTest.java rename to core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java index 803d8881b4..caa7049475 100644 --- a/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java @@ -9,7 +9,7 @@ import java.nio.file.Paths; import org.junit.Test; -public class SymLinkExampleUnitTest { +public class SymLinkExampleManualTest { @Test public void whenUsingFiles_thenCreateSymbolicLink() throws IOException { diff --git a/core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java b/core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java new file mode 100644 index 0000000000..a28ac3d5a1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java @@ -0,0 +1,40 @@ +package com.baeldung.doubles; + +import java.math.BigDecimal; + +public class SplitFloatingPointNumbers { + + public static void main(String[] args) { + + double doubleNumber = 24.04; + splitUsingFloatingTypes(doubleNumber); + splitUsingString(doubleNumber); + splitUsingBigDecimal(doubleNumber); + } + + private static void splitUsingFloatingTypes(double doubleNumber) { + System.out.println("Using Floating Point Arithmetics:"); + int intPart = (int) doubleNumber; + System.out.println("Double Number: "+doubleNumber); + System.out.println("Integer Part: "+ intPart); + System.out.println("Decimal Part: "+ (doubleNumber - intPart)); + } + + private static void splitUsingString(double doubleNumber) { + System.out.println("Using String Operations:"); + String doubleAsString = String.valueOf(doubleNumber); + int indexOfDecimal = doubleAsString.indexOf("."); + System.out.println("Double Number: "+doubleNumber); + System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal)); + System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal)); + } + + private static void splitUsingBigDecimal(double doubleNumber) { + System.out.println("Using BigDecimal Operations:"); + BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber)); + int intValue = bigDecimal.intValue(); + System.out.println("Double Number: "+bigDecimal.toPlainString()); + System.out.println("Integer Part: "+intValue); + System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString()); + } +} diff --git a/core-java/src/main/java/com/baeldung/heapdump/HeapDump.java b/core-java/src/main/java/com/baeldung/heapdump/HeapDump.java new file mode 100644 index 0000000000..8cce20de8d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/heapdump/HeapDump.java @@ -0,0 +1,25 @@ +package com.baeldung.heapdump; + +import com.sun.management.HotSpotDiagnosticMXBean; + +import javax.management.MBeanServer; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.nio.file.Paths; + +public class HeapDump { + + public static void dumpHeap(String filePath, boolean live) throws IOException { + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy( + server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class); + mxBean.dumpHeap(filePath, live); + } + + public static void main(String[] args) throws IOException { + String file = Paths.get("dump.hprof").toFile().getPath(); + + dumpHeap(file, true); + } +} diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java new file mode 100644 index 0000000000..e2259e4249 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java @@ -0,0 +1,149 @@ +package com.baeldung.passwordhashing; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; + +/** + * Hash passwords for storage, and test passwords against password tokens. + * + * Instances of this class can be used concurrently by multiple threads. + * + * @author erickson + * @see StackOverflow + */ +public final class PBKDF2Hasher +{ + + /** + * Each token produced by this class uses this identifier as a prefix. + */ + public static final String ID = "$31$"; + + /** + * The minimum recommended cost, used by default + */ + public static final int DEFAULT_COST = 16; + + private static final String ALGORITHM = "PBKDF2WithHmacSHA1"; + + private static final int SIZE = 128; + + private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})"); + + private final SecureRandom random; + + private final int cost; + + public PBKDF2Hasher() + { + this(DEFAULT_COST); + } + + /** + * Create a password manager with a specified cost + * + * @param cost the exponential computational cost of hashing a password, 0 to 30 + */ + public PBKDF2Hasher(int cost) + { + iterations(cost); /* Validate cost */ + this.cost = cost; + this.random = new SecureRandom(); + } + + private static int iterations(int cost) + { + if ((cost < 0) || (cost > 30)) + throw new IllegalArgumentException("cost: " + cost); + return 1 << cost; + } + + /** + * Hash a password for storage. + * + * @return a secure authentication token to be stored for later authentication + */ + public String hash(char[] password) + { + byte[] salt = new byte[SIZE / 8]; + random.nextBytes(salt); + byte[] dk = pbkdf2(password, salt, 1 << cost); + byte[] hash = new byte[salt.length + dk.length]; + System.arraycopy(salt, 0, hash, 0, salt.length); + System.arraycopy(dk, 0, hash, salt.length, dk.length); + Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding(); + return ID + cost + '$' + enc.encodeToString(hash); + } + + /** + * Authenticate with a password and a stored password token. + * + * @return true if the password and token match + */ + public boolean checkPassword(char[] password, String token) + { + Matcher m = layout.matcher(token); + if (!m.matches()) + throw new IllegalArgumentException("Invalid token format"); + int iterations = iterations(Integer.parseInt(m.group(1))); + byte[] hash = Base64.getUrlDecoder().decode(m.group(2)); + byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8); + byte[] check = pbkdf2(password, salt, iterations); + int zero = 0; + for (int idx = 0; idx < check.length; ++idx) + zero |= hash[salt.length + idx] ^ check[idx]; + return zero == 0; + } + + private static byte[] pbkdf2(char[] password, byte[] salt, int iterations) + { + KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE); + try { + SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM); + return f.generateSecret(spec).getEncoded(); + } + catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex); + } + catch (InvalidKeySpecException ex) { + throw new IllegalStateException("Invalid SecretKeyFactory", ex); + } + } + + /** + * Hash a password in an immutable {@code String}. + * + * Passwords should be stored in a {@code char[]} so that it can be filled + * with zeros after use instead of lingering on the heap and elsewhere. + * + * @deprecated Use {@link #hash(char[])} instead + */ + @Deprecated + public String hash(String password) + { + return hash(password.toCharArray()); + } + + /** + * Authenticate with a password in an immutable {@code String} and a stored + * password token. + * + * @deprecated Use {@link #checkPassword(char[],String)} instead. + * @see #hash(String) + */ + @Deprecated + public boolean checkPassword(String password, String token) + { + return checkPassword(password.toCharArray(), token); + } + +} diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java new file mode 100644 index 0000000000..4f5337f963 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java @@ -0,0 +1,35 @@ +package com.baeldung.passwordhashing; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + + +/** A really simple SHA_512 Encryption example. + * + */ +public class SHA512Hasher { + + public String hash(String passwordToHash, byte[] salt){ + String generatedPassword = null; + try { + MessageDigest md = MessageDigest.getInstance("SHA-512"); + md.update(salt); + byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for(int i=0; i< bytes.length ;i++){ + sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); + } + generatedPassword = sb.toString(); + } + catch (NoSuchAlgorithmException e){ + e.printStackTrace(); + } + return generatedPassword; + } + + public boolean checkPassword(String hash, String attempt, byte[] salt){ + String generatedHash = hash(attempt, salt); + return hash.equals(generatedHash); + } +} diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java new file mode 100644 index 0000000000..36c9b65070 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java @@ -0,0 +1,18 @@ +package com.baeldung.passwordhashing; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import java.security.spec.KeySpec; + +/** A really simple SimplePBKDF2 Encryption example. + * + */ +public class SimplePBKDF2Hasher { + + public static String hashSimple(String password, byte[] salt) throws Exception{ + KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128); + SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + byte[] hash = f.generateSecret(spec).getEncoded(); + return String.valueOf(hash); + } +} diff --git a/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java b/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java new file mode 100644 index 0000000000..69e151bfcb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java @@ -0,0 +1,70 @@ +package com.baeldung.switchstatement; + +public class SwitchStatement { + + public String exampleOfIF(String animal) { + + String result; + + if (animal.equals("DOG") || animal.equals("CAT")) { + result = "domestic animal"; + } else if (animal.equals("TIGER")) { + result = "wild animal"; + } else { + result = "unknown animal"; + } + return result; + } + + public String exampleOfSwitch(String animal) { + + String result; + + switch (animal) { + case "DOG": + case "CAT": + result = "domestic animal"; + break; + case "TIGER": + result = "wild animal"; + break; + default: + result = "unknown animal"; + break; + } + return result; + } + + public String forgetBreakInSwitch(String animal) { + + String result; + + switch (animal) { + + case "DOG": + System.out.println("domestic animal"); + result = "domestic animal"; + + default: + System.out.println("unknown animal"); + result = "unknown animal"; + + } + return result; + } + + public String constantCaseValue(String animal) { + + String result = ""; + + final String dog = "DOG"; + + switch (animal) { + + case dog: + result = "domestic animal"; + } + return result; + } + +} diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java index a22de0db18..fb92eb8d0d 100644 --- a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java @@ -1,16 +1,12 @@ package com.baeldung.zoneddatetime; -import java.time.LocalDateTime; import java.time.OffsetDateTime; -import java.time.ZoneId; import java.time.ZoneOffset; public class OffsetDateTimeExample { - public OffsetDateTime getCurrentTimeByZoneOffset(String region) { - LocalDateTime now = LocalDateTime.now(); - ZoneId zone = ZoneId.of(region); - ZoneOffset zoneOffSet= zone.getRules().getOffset(now); + public OffsetDateTime getCurrentTimeByZoneOffset(String offset) { + ZoneOffset zoneOffSet= ZoneOffset.of(offset); OffsetDateTime date = OffsetDateTime.now(zoneOffSet); return date; } diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java index 7d926c0562..58e2d4d5ad 100644 --- a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java @@ -1,17 +1,12 @@ package com.baeldung.zoneddatetime; -import java.time.LocalDateTime; import java.time.OffsetTime; -import java.time.ZoneId; import java.time.ZoneOffset; public class OffsetTimeExample { - public OffsetTime getCurrentTimeByZoneOffset(String region) { - LocalDateTime now = LocalDateTime.now(); - ZoneId zone = ZoneId.of(region); - ZoneOffset zoneOffSet = zone.getRules() - .getOffset(now); + public OffsetTime getCurrentTimeByZoneOffset(String offset) { + ZoneOffset zoneOffSet = ZoneOffset.of(offset); OffsetTime time = OffsetTime.now(zoneOffSet); return time; } diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java b/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java new file mode 100644 index 0000000000..8e90725c77 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.passwordhashing; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + + +public class PBKDF2HasherUnitTest { + + private PBKDF2Hasher mPBKDF2Hasher; + + @Before + public void setUp() throws Exception { + mPBKDF2Hasher = new PBKDF2Hasher(); + } + + @Test + public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception { + String message1 = "password123"; + + String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); + + assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1)); + + } + + @Test + public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception { + String message1 = "password123"; + + String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); + + String wrongPasswordAttempt = "IamWrong"; + + assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1)); + + } + + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java b/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java new file mode 100644 index 0000000000..3acfb0ba9d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.passwordhashing; + +import org.junit.Before; +import org.junit.Test; + +import java.security.SecureRandom; + +import static org.junit.Assert.*; + +/** + * Created by PhysicsSam on 06-Sep-18. + */ +public class SHA512HasherUnitTest { + + private SHA512Hasher hasher; + private SecureRandom secureRandom; + + @Before + public void setUp() throws Exception { + hasher = new SHA512Hasher(); + secureRandom = new SecureRandom(); + } + + @Test + public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception { + + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String hash1 = hasher.hash("password", salt); + String hash2 = hasher.hash("password", salt); + + assertEquals(hash1, hash2); + + } + + @Test + public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception { + + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + String hash1 = hasher.hash("password", salt); + //generate a second salt + byte[] secondSalt = new byte[16]; + String hash2 = hasher.hash("password", secondSalt); + + assertNotEquals(hash1, hash2); + + } + + @Test + public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception { + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String originalHash = hasher.hash("password123", salt); + + assertTrue(hasher.checkPassword(originalHash, "password123", salt)); + } + + @Test + public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception { + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String originalHash = hasher.hash("password123", salt); + + assertFalse(hasher.checkPassword(originalHash, "password124", salt)); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java b/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java new file mode 100644 index 0000000000..e8ac645531 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.switchstatement; + +import org.junit.Test; + +import org.junit.Assert; + +public class SwitchStatementUnitTest { + private SwitchStatement s = new SwitchStatement(); + + + @Test + public void whenDog_thenDomesticAnimal() { + + String animal = "DOG"; + Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal)); + } + + @Test + public void whenNoBreaks_thenGoThroughBlocks() { + String animal = "DOG"; + Assert.assertEquals("unknown animal", s.forgetBreakInSwitch(animal)); + } + + @Test(expected=NullPointerException.class) + public void whenSwitchAgumentIsNull_thenNullPointerException() { + String animal = null; + Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal)); + } + + + @Test + public void whenCompareStrings_thenByEqual() { + String animal = new String("DOG"); + Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal)); + } + + +} diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java index c60f6967f9..a08d3737cd 100644 --- a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java @@ -2,9 +2,8 @@ package com.baeldung.zoneddatetime; import static org.junit.Assert.assertTrue; -import java.time.LocalDateTime; import java.time.OffsetDateTime; -import java.time.ZoneId; +import java.time.ZoneOffset; import org.junit.Test; @@ -14,12 +13,10 @@ public class OffsetDateTimeExampleUnitTest { @Test public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() { - String zone = "Europe/Berlin"; - OffsetDateTime time = offsetDateTimeExample.getCurrentTimeByZoneOffset(zone); + String offset = "+02:00"; + OffsetDateTime time = offsetDateTimeExample.getCurrentTimeByZoneOffset(offset); assertTrue(time.getOffset() - .equals(ZoneId.of(zone) - .getRules() - .getOffset(LocalDateTime.now()))); + .equals(ZoneOffset.of(offset))); } } diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java index 0e1206dc5b..488f934179 100644 --- a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java @@ -2,9 +2,8 @@ package com.baeldung.zoneddatetime; import static org.junit.Assert.assertTrue; -import java.time.LocalDateTime; import java.time.OffsetTime; -import java.time.ZoneId; +import java.time.ZoneOffset; import org.junit.Test; @@ -14,12 +13,10 @@ public class OffsetTimeExampleUnitTest { @Test public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() { - String zone = "Europe/Berlin"; - OffsetTime time = offsetTimeExample.getCurrentTimeByZoneOffset(zone); + String offset = "+02:00"; + OffsetTime time = offsetTimeExample.getCurrentTimeByZoneOffset(offset); assertTrue(time.getOffset() - .equals(ZoneId.of(zone) - .getRules() - .getOffset(LocalDateTime.now()))); + .equals(ZoneOffset.of(offset))); } } diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java index 7f4f9cd17c..e78ff3e3fd 100644 --- a/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java @@ -15,16 +15,19 @@ public class ZoneDateTimeExampleUnitTest { public void givenZone_whenGetCurrentTime_thenResultHasZone() { String zone = "Europe/Berlin"; ZonedDateTime time = zoneDateTimeExample.getCurrentTimeByZoneId(zone); + assertTrue(time.getZone() .equals(ZoneId.of(zone))); } - + @Test public void givenZones_whenConvertDateByZone_thenGetConstantDiff() { String sourceZone = "Europe/Berlin"; String destZone = "Asia/Tokyo"; ZonedDateTime sourceDate = zoneDateTimeExample.getCurrentTimeByZoneId(sourceZone); ZonedDateTime destDate = zoneDateTimeExample.convertZonedDateTime(sourceDate, destZone); - assertTrue(sourceDate.toInstant().compareTo(destDate.toInstant()) == 0); + + assertTrue(sourceDate.toInstant() + .compareTo(destDate.toInstant()) == 0); } } diff --git a/java-streams/pom.xml b/java-streams/pom.xml index 023a5f695b..e4670c268d 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -105,7 +105,7 @@ 3.5 1.16.12 0.9.0 - 1.13 + 1.15 0.6.5 2.10 diff --git a/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java b/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java new file mode 100644 index 0000000000..1b64c8924a --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java @@ -0,0 +1,209 @@ +package com.baeldung.protonpack; + +import com.codepoetics.protonpack.Indexed; +import com.codepoetics.protonpack.StreamUtils; +import com.codepoetics.protonpack.collectors.CollectorUtils; +import com.codepoetics.protonpack.collectors.NonUniqueValueException; +import com.codepoetics.protonpack.selectors.Selector; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Arrays.stream; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +@SuppressWarnings("unchecked") +public class ProtonpackUnitTest { + @Test + public void whenTakeWhile_thenTakenWhile() { + Stream streamOfInt = Stream.iterate(1, i -> i + 1); + List result = StreamUtils.takeWhile(streamOfInt, i -> i < 5).collect(Collectors.toList()); + assertThat(result).contains(1, 2, 3, 4); + } + + @Test + public void whenTakeUntil_thenTakenUntil() { + Stream streamOfInt = Stream.iterate(1, i -> i + 1); + List result = StreamUtils.takeUntil(streamOfInt, i -> i > 50).collect(Collectors.toList()); + assertThat(result).contains(10, 20, 30, 40); + } + + @Test + public void givenMultipleStream_whenZipped_thenZipped() { + String[] clubs = { "Juventus", "Barcelona", "Liverpool", "PSG" }; + String[] players = { "Ronaldo", "Messi", "Salah" }; + Set zippedFrom2Sources = StreamUtils.zip(stream(clubs), stream(players), (club, player) -> club + " " + player) + .collect(Collectors.toSet()); + assertThat(zippedFrom2Sources).contains("Juventus Ronaldo", "Barcelona Messi", "Liverpool Salah"); + + String[] leagues = { "Serie A", "La Liga", "Premier League" }; + Set zippedFrom3Sources = StreamUtils.zip(stream(clubs), stream(players), stream(leagues), + (club, player, league) -> club + " " + player + " " + league).collect(Collectors.toSet()); + assertThat(zippedFrom3Sources).contains("Juventus Ronaldo Serie A", "Barcelona Messi La Liga", + "Liverpool Salah Premier League"); + } + + @Test + public void whenZippedWithIndex_thenZippedWithIndex() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool"); + Set> zipsWithIndex = StreamUtils.zipWithIndex(streamOfClubs).collect(Collectors.toSet()); + assertThat(zipsWithIndex).contains(Indexed.index(0, "Juventus"), Indexed.index(1, "Barcelona"), + Indexed.index(2, "Liverpool")); + } + + @Test + public void givenMultipleStream_whenMerged_thenMerged() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool", "PSG"); + Stream streamOfPlayers = Stream.of("Ronaldo", "Messi", "Salah"); + Stream streamOfLeagues = Stream.of("Serie A", "La Liga", "Premier League"); + + Set merged = StreamUtils.merge(() -> "", (valOne, valTwo) -> valOne + " " + valTwo, streamOfClubs, + streamOfPlayers, streamOfLeagues).collect(Collectors.toSet()); + + assertThat(merged).contains(" Juventus Ronaldo Serie A", " Barcelona Messi La Liga", " Liverpool Salah Premier League", + " PSG"); + } + + @Test + public void givenMultipleStream_whenMergedToList_thenMergedToList() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "PSG"); + Stream streamOfPlayers = Stream.of("Ronaldo", "Messi"); + + List> mergedListOfList = StreamUtils.mergeToList(streamOfClubs, streamOfPlayers) + .collect(Collectors.toList()); + assertThat(mergedListOfList.get(0)).isInstanceOf(List.class); + assertThat(mergedListOfList.get(0)).containsExactly("Juventus", "Ronaldo"); + assertThat(mergedListOfList.get(1)).containsExactly("Barcelona", "Messi"); + assertThat(mergedListOfList.get(2)).containsExactly("PSG"); + } + + @Test + public void givenMultipleStream_whenInterleaved_thenInterleaved() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool"); + Stream streamOfPlayers = Stream.of("Ronaldo", "Messi"); + Stream streamOfLeagues = Stream.of("Serie A", "La Liga"); + + AtomicInteger counter = new AtomicInteger(0); + Selector roundRobinSelector = (o) -> { + Object[] vals = (Object[]) o; + while (counter.get() >= vals.length || vals[counter.get()] == null) { + if (counter.incrementAndGet() >= vals.length) + counter.set(0); + } + return counter.getAndIncrement(); + }; + Stream interleavedStream = StreamUtils.interleave(roundRobinSelector, streamOfClubs, streamOfPlayers, + streamOfLeagues); + List interleavedList = interleavedStream.collect(Collectors.toList()); + assertThat(interleavedList).containsExactly("Juventus", "Ronaldo", "Serie A", "Barcelona", "Messi", "La Liga", + "Liverpool"); + } + + @Test + public void whenSkippedUntil_thenSkippedUntil() { + Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + List skippedUntilGreaterThan5 = StreamUtils.skipUntil(stream(numbers), i -> i > 5).collect(Collectors.toList()); + assertThat(skippedUntilGreaterThan5).containsExactly(6, 7, 8, 9, 10); + + List skippedUntilLessThanEquals5 = StreamUtils.skipUntil(stream(numbers), i -> i <= 5) + .collect(Collectors.toList()); + assertThat(skippedUntilLessThanEquals5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + + @Test + public void whenSkippedWhile_thenSkippedWhile() { + Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + List skippedWhileLessThanEquals5 = StreamUtils.skipWhile(stream(numbers), i -> i <= 5) + .collect(Collectors.toList()); + assertThat(skippedWhileLessThanEquals5).containsExactly(6, 7, 8, 9, 10); + + List skippedWhileGreaterThan5 = StreamUtils.skipWhile(stream(numbers), i -> i > 5).collect(Collectors.toList()); + assertThat(skippedWhileGreaterThan5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + + @Test + public void givenFibonacciGenerator_whenUnfolded_thenUnfolded() { + AtomicInteger lastValue = new AtomicInteger(0); + Function> fibonacciGenerator = (i) -> (i < 10) ? + Optional.of(i + lastValue.getAndSet(i)) : + Optional.empty(); + + List fib = StreamUtils.unfold(1, fibonacciGenerator).collect(Collectors.toList()); + assertThat(fib).containsExactly(1, 1, 2, 3, 5, 8, 13); + } + + @Test + public void whenWindowed_thenWindowed() { + Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7 }; + + List> windowedWithSkip1 = StreamUtils.windowed(stream(numbers), 3, 1).collect(Collectors.toList()); + assertThat(windowedWithSkip1).containsExactly(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5, 6), + asList(5, 6, 7)); + + List> windowedWithSkip2 = StreamUtils.windowed(stream(numbers), 3, 2).collect(Collectors.toList()); + assertThat(windowedWithSkip2).containsExactly(asList(1, 2, 3), asList(3, 4, 5), asList(5, 6, 7)); + } + + @Test + public void whenAggregated_thenAggregated() { + Integer[] numbers = { 1, 2, 2, 3, 4, 4, 4, 5 }; + List> aggregated = StreamUtils.aggregate(stream(numbers), (int1, int2) -> int1.compareTo(int2) == 0) + .collect(Collectors.toList()); + assertThat(aggregated).containsExactly(asList(1), asList(2, 2), asList(3), asList(4, 4, 4), asList(5)); + + List> aggregatedFixSize = StreamUtils.aggregate(stream(numbers), 5).collect(Collectors.toList()); + assertThat(aggregatedFixSize).containsExactly(asList(1, 2, 2, 3, 4), asList(4, 4, 5)); + } + + @Test + public void whenGroupedRun_thenGroupedRun() { + Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 }; + List> grouped = StreamUtils.groupRuns(stream(numbers)).collect(Collectors.toList()); + assertThat(grouped).containsExactly(asList(1, 1), asList(2), asList(3), asList(4, 4), asList(5)); + + Integer[] numbers2 = { 1, 2, 3, 1 }; + List> grouped2 = StreamUtils.groupRuns(stream(numbers2)).collect(Collectors.toList()); + assertThat(grouped2).containsExactly(asList(1), asList(2), asList(3), asList(1)); + } + + @Test + public void whenAggregatedOnListCondition_thenAggregatedOnListCondition() { + Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 }; + Stream> aggregated = StreamUtils.aggregateOnListCondition(stream(numbers), + (currentList, nextInt) -> currentList.stream().mapToInt(Integer::intValue).sum() + nextInt <= 5); + assertThat(aggregated).containsExactly(asList(1, 1, 2), asList(3), asList(4), asList(4), asList(5)); + } + + @Test + public void givenProjectionFunction_whenMaxedBy_thenMaxedBy() { + Stream clubs = Stream.of("Juventus", "Barcelona", "PSG"); + Optional longestName = clubs.collect(CollectorUtils.maxBy(String::length)); + assertThat(longestName.get()).isEqualTo("Barcelona"); + } + + @Test + public void givenStreamOfMultipleElem_whenUniqueCollector_thenValueReturned() { + Stream singleElement = Stream.of(1); + Optional unique = singleElement.collect(CollectorUtils.unique()); + assertThat(unique.get()).isEqualTo(1); + + } + + @Test + public void givenStreamOfMultipleElem_whenUniqueCollector_thenExceptionThrown() { + Stream multipleElement = Stream.of(1, 2, 3); + assertThatExceptionOfType(NonUniqueValueException.class).isThrownBy(() -> { + multipleElement.collect(CollectorUtils.unique()); + }); + } + +} diff --git a/java-strings/pom.xml b/java-strings/pom.xml index 2afe18f07a..b1ba49b33a 100644 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -47,11 +47,21 @@ jmh-core ${jmh-core.version} + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-core.version} + com.ibm.icu icu4j ${icu4j.version} + + com.google.guava + guava + ${guava.version} + com.vdurmont @@ -92,6 +102,7 @@ 3.6.1 1.19 61.1 + 26.0-jre \ No newline at end of file diff --git a/java-strings/src/main/java/com/baeldung/string/StringPerformance.java b/java-strings/src/main/java/com/baeldung/string/StringPerformance.java new file mode 100644 index 0000000000..4873bd320c --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/StringPerformance.java @@ -0,0 +1,163 @@ +package com.baeldung.string; + +import org.apache.commons.lang3.StringUtils; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Measurement(batchSize = 10000, iterations = 10) +@Warmup(batchSize = 10000, iterations = 10) +public class StringPerformance extends StringPerformanceHints { + + @Benchmark + public String benchmarkStringDynamicConcat() { + return dynamicConcat(); + } + + @Benchmark + public StringBuilder benchmarkStringBuilder() { + StringBuilder stringBuilder = new StringBuilder(result); + stringBuilder.append(baeldung); + return stringBuilder; + } + + @Benchmark + public StringBuffer benchmarkStringBuffer() { + StringBuffer stringBuffer = new StringBuffer(result); + stringBuffer.append(baeldung); + return stringBuffer; + } + + @Benchmark + public String benchmarkStringConstructor() { + return stringConstructor(); + } + + @Benchmark + public String benchmarkStringLiteral() { + return stringLiteral(); + } + + @Benchmark + public String benchmarkStringFormat_s() { + return stringFormat_s(); + } + + @Benchmark + public String benchmarkStringConcat() { + return stringConcat(); + } + + @Benchmark + public String benchmarkStringIntern() { + return stringIntern(); + } + + @Benchmark + public String benchmarkStringReplace() { + return longString.replace("average", " average !!!"); + } + + @Benchmark + public String benchmarkStringUtilsReplace() { + return StringUtils.replace(longString, "average", " average !!!"); + } + + @Benchmark + public List benchmarkGuavaSplitter() { + return guavaSplitter(); + } + + @Benchmark + public String [] benchmarkStringSplit() { + return stringSplit(); + } + + @Benchmark + public String [] benchmarkStringSplitPattern() { + return stringSplitPattern(); + } + + @Benchmark + public List benchmarkStringTokenizer() { + return stringTokenizer(); + } + + @Benchmark + public List benchmarkStringIndexOf() { + return stringIndexOf(); + } + + + @Benchmark + public String benchmarkIntegerToString() { + return stringIntegerToString(); + } + + @Benchmark + public String benchmarkStringValueOf() { + return stringValueOf(); + } + + + @Benchmark + public String benchmarkStringConvertPlus() { + return stringConvertPlus(); + } + + @Benchmark + public String benchmarkStringFormat_d() { + return stringFormat_d(); + } + + @Benchmark + public boolean benchmarkStringEquals() { + return stringEquals(); + } + + + @Benchmark + public boolean benchmarkStringEqualsIgnoreCase() { + return stringEqualsIgnoreCase(); + } + + @Benchmark + public boolean benchmarkStringMatches() { + return stringIsMatch(); + } + + @Benchmark + public boolean benchmarkPrecompiledMatches() { + return precompiledMatches(); + } + + @Benchmark + public int benchmarkStringCompareTo() { + return stringCompareTo(); + } + + @Benchmark + public boolean benchmarkStringIsEmpty() { + return stringIsEmpty(); + } + + @Benchmark + public boolean benchmarkStringLengthZero() { + return stringLengthZero(); + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(StringPerformance.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/StringPerformanceHints.java b/java-strings/src/main/java/com/baeldung/string/StringPerformanceHints.java new file mode 100644 index 0000000000..509222136f --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/StringPerformanceHints.java @@ -0,0 +1,133 @@ +package com.baeldung.string; + +import com.google.common.base.Splitter; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.regex.Pattern; + +@State(Scope.Thread) +public class StringPerformanceHints { + + protected String baeldung = "baeldung"; + protected String longString = "Hello baeldung, I am a bit longer than other Strings"; + protected String formatString = "hello %s, nice to meet you"; + protected String formatDigit = "%d"; + protected String emptyString = " "; + protected String result = ""; + + protected int sampleNumber = 100; + + protected Pattern spacePattern = Pattern.compile(emptyString); + protected Pattern longPattern = Pattern.compile(longString); + protected List stringSplit = new ArrayList<>(); + protected List stringTokenizer = new ArrayList<>(); + + protected String dynamicConcat() { + result += baeldung; + return result; + } + + protected String stringConstructor() { + return new String(baeldung); + } + + protected String stringLiteral() { + result = baeldung; + return result; + } + + protected String stringFormat_s() { + return String.format(formatString, baeldung); + } + + protected String stringFormat_d() { + return String.format(formatDigit, sampleNumber); + } + + protected String stringConcat() { + result = result.concat(baeldung); + return result; + } + + protected List stringTokenizer() { + StringTokenizer st = new StringTokenizer(longString); + while (st.hasMoreTokens()) { + stringTokenizer.add(st.nextToken()); + } + return stringTokenizer; + } + + protected List stringIndexOf() { + int pos = 0, end; + while ((end = longString.indexOf(' ', pos)) >= 0) { + stringSplit.add(longString.substring(pos, end)); + pos = end + 1; + } + return stringSplit; + } + + protected String stringIntegerToString() { + return Integer.toString(sampleNumber); + } + + protected String stringValueOf() { + return String.valueOf(sampleNumber); + } + + + protected String stringConvertPlus() { + return sampleNumber + ""; + } + + + protected boolean stringEquals() { + return longString.equals(baeldung); + } + + + protected boolean stringEqualsIgnoreCase() { + return longString.equalsIgnoreCase(baeldung); + } + + protected boolean stringIsMatch() { + return longString.matches(baeldung); + } + + protected boolean precompiledMatches() { + return longPattern.matcher(baeldung).matches(); + } + + protected int stringCompareTo() { + return longString.compareTo(baeldung); + } + + protected boolean stringIsEmpty() { + return longString.isEmpty(); + } + + protected boolean stringLengthZero() { + return longString.length() == 0; + } + + protected String [] stringSplitPattern() { + return spacePattern.split(longString, 0); + } + + protected String [] stringSplit() { + return longString.split(emptyString); + } + + protected List guavaSplitter() { + return Splitter.on(" ").trimResults() + .omitEmptyStrings() + .splitToList(longString); + } + + protected String stringIntern() { + return baeldung.intern(); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java new file mode 100644 index 0000000000..17b13f89de --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.string; + +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; +import static org.hamcrest.text.IsEmptyString.isEmptyString; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.lang3.StringUtils; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import com.google.common.base.Strings; + +public class StringEmptyUnitTest { + + private String text = "baeldung"; + + @Test + public void givenAString_whenCheckedForEmptyUsingJunit_shouldAssertSuccessfully() { + assertTrue(!text.isEmpty()); + assertFalse(text.isEmpty()); + assertNotEquals("", text); + assertNotSame("", text); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingHamcrest_shouldAssertSuccessfully() { + assertThat(text, not(isEmptyString())); + assertThat(text, not(isEmptyOrNullString())); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingCommonsLang_shouldAssertSuccessfully() { + assertTrue(StringUtils.isNotBlank(text)); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingAssertJ_shouldAssertSuccessfully() { + Assertions.assertThat(text).isNotEmpty(); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingGuava_shouldAssertSuccessfully() { + assertFalse(Strings.isNullOrEmpty(text)); + } + +} diff --git a/libraries-security/.gitignore b/libraries-security/.gitignore new file mode 100644 index 0000000000..71881ad3ca --- /dev/null +++ b/libraries-security/.gitignore @@ -0,0 +1,14 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear +/bin/ diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml new file mode 100644 index 0000000000..a57f029702 --- /dev/null +++ b/libraries-security/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + libraries-security + libraries-security + jar + + + com.baeldung + parent-boot-1 + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.security.oauth + spring-security-oauth2 + 2.3.3.RELEASE + + + + com.github.scribejava + scribejava-apis + ${scribejava.version} + + + + junit + junit + ${junit.version} + test + + + + + + 4.12 + 2.0.4.RELEASE + 5.6.0 + + + + diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java new file mode 100644 index 0000000000..bb86c497b0 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.scribejava; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +public class ScribejavaApplication { + + public static void main(String[] args) { + SpringApplication.run(ScribejavaApplication.class, args); + } + + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java new file mode 100644 index 0000000000..cf073d3035 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java @@ -0,0 +1,27 @@ +package com.baeldung.scribejava.api; + +import com.github.scribejava.core.builder.api.DefaultApi20; + +public class MyApi extends DefaultApi20 { + + private MyApi() { + } + + private static class InstanceHolder { + private static final MyApi INSTANCE = new MyApi(); + } + + public static MyApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "http://localhost:8080/oauth/token"; + } + + @Override + protected String getAuthorizationBaseUrl() { + return null; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java new file mode 100644 index 0000000000..ffe4f0cc8a --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java @@ -0,0 +1,49 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.GoogleService; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; + +@RestController +public class GoogleController { + + @Autowired + private GoogleService service; + + + @GetMapping(value ="/me/google") + public void me(HttpServletResponse response){ + String auth = service.getService().getAuthorizationUrl(); + + response.setHeader("Location", auth); + response.setStatus(302); + + } + + @GetMapping(value = "/auth/google") + public String google(@RequestParam String code, HttpServletResponse servletResponse){ + + try { + OAuth2AccessToken token = service.getService().getAccessToken(code); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"); + service.getService().signRequest(token, request); + Response response = service.getService().execute(request); + return response.getBody(); + + }catch (Exception e){ + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java new file mode 100644 index 0000000000..bfcd6d960c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java @@ -0,0 +1,57 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.TwitterService; +import com.github.scribejava.core.model.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Scanner; +import java.util.concurrent.ExecutionException; + +@RestController +public class TwitterController { + + @Autowired + private TwitterService service; + + + @GetMapping(value ="/me/twitter") + public String me(HttpServletResponse servletResponse){ + try { + OAuth1RequestToken requestToken = service.getService().getRequestToken(); + + String auth = service.getService().getAuthorizationUrl(requestToken); + + Runtime runtime = Runtime.getRuntime(); + try { + runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth); + } catch (IOException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return null; + } + + System.out.println("Insert twitter code:"); + Scanner in = new Scanner(System.in); + + String oauthverifier = in.nextLine(); + + final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json"); + service.getService().signRequest(accessToken, request); + Response response = service.getService().execute(request); + return response.getBody(); + + } catch (IOException | InterruptedException | ExecutionException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + } + + + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java new file mode 100644 index 0000000000..68a11250de --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java @@ -0,0 +1,46 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.MyService; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.security.Principal; + +@RestController(value = "/user") +public class UserController { + + @Autowired + private MyService service; + + @GetMapping("/me/myapi") + public String me(@RequestParam String username, @RequestParam String password, HttpServletResponse responsehttp) { + + try { + OAuth2AccessToken token = service.getService().getAccessTokenPasswordGrant(username, password); + + OAuthRequest request = new OAuthRequest(Verb.GET, "http://localhost:8080/me"); + service.getService().signRequest(token, request); + Response response = service.getService().execute(request); + + return response.getBody(); + + } catch (Exception e) { + responsehttp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + + } + + @GetMapping("/me") + public Principal user(Principal principal) { + return principal; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java new file mode 100644 index 0000000000..2c7162399b --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java @@ -0,0 +1,45 @@ +package com.baeldung.scribejava.oauth; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; + + +@Configuration +@EnableAuthorizationServer +public class AuthServiceConfig extends AuthorizationServerConfigurerAdapter { + + @Autowired + @Qualifier("authenticationManagerBean") + private AuthenticationManager authenticationManager; + + @Override + public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { + oauthServer.tokenKeyAccess("permitAll()") + .checkTokenAccess("isAuthenticated()"); + } + + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + clients.inMemory() + .withClient("baeldung_api_key") + .secret("baeldung_api_secret") + .authorizedGrantTypes("password","refresh_token") + .scopes("read","write").autoApprove(true); + } + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { + endpoints + .authenticationManager(authenticationManager) + .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java new file mode 100644 index 0000000000..7aa51400ea --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.scribejava.oauth; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; + +@Configuration +@EnableResourceServer +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .headers().frameOptions().disable() + .and() + .csrf().disable(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("baeldung") + .password("scribejava") + .roles("USER"); + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + + @EnableResourceServer + @Configuration + public class ResourceServerConfig extends ResourceServerConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/user/me").authenticated() + .and() + .csrf().disable(); + } + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java new file mode 100644 index 0000000000..fbcc39763c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java @@ -0,0 +1,31 @@ +package com.baeldung.scribejava.service; + +import com.github.scribejava.apis.GoogleApi20; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +@Component +public class GoogleService { + + private OAuth20Service service; + private final String API_KEY = "api_key"; + private final String API_SECRET = "api_secret"; + private final String SCOPE = "https://www.googleapis.com/auth/userinfo.email"; + private final String CALLBACK = "http://localhost:8080/auth/google"; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .scope(SCOPE) + .callback(CALLBACK) + .build(GoogleApi20.instance()); + } + + + public OAuth20Service getService() { + return service; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java new file mode 100644 index 0000000000..739c82172c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java @@ -0,0 +1,29 @@ +package com.baeldung.scribejava.service; + +import com.baeldung.scribejava.api.MyApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class MyService { + + private OAuth20Service service; + private final String API_KEY = "baeldung_api_key"; + private final String API_SECRET = "baeldung_api_secret"; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .scope("read write") + .build(MyApi.instance()); + } + + + public OAuth20Service getService() { + return service; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java new file mode 100644 index 0000000000..df49f74679 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java @@ -0,0 +1,29 @@ +package com.baeldung.scribejava.service; + +import com.github.scribejava.apis.TwitterApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth10aService; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class TwitterService { + + private final String API_KEY = "api_key"; + private final String API_SECRET = "api_secret"; + private OAuth10aService service; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .build(TwitterApi.instance()); + } + + public OAuth10aService getService(){ + return service; + } + + +} diff --git a/libraries-security/src/main/resources/application.properties b/libraries-security/src/main/resources/application.properties new file mode 100644 index 0000000000..71c6176533 --- /dev/null +++ b/libraries-security/src/main/resources/application.properties @@ -0,0 +1 @@ +security.oauth2.resource.filter-order = 3 \ No newline at end of file diff --git a/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java new file mode 100644 index 0000000000..6565a5b085 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.scribejava; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ScribejavaUnitTest { + + @Test + public void contextLoad(){ + + } + +} diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java b/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java new file mode 100644 index 0000000000..15488bbaf4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java @@ -0,0 +1,56 @@ +package com.baeldung.kafka; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.KafkaException; + +import java.util.Properties; +import java.util.stream.Stream; + +import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.TRANSACTIONAL_ID_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG; + +public class TransactionalMessageProducer { + + private static final String DATA_MESSAGE_1 = "Put any space separated data here for count"; + private static final String DATA_MESSAGE_2 = "Output will contain count of every word in the message"; + + public static void main(String[] args) { + + KafkaProducer producer = createKafkaProducer(); + + producer.initTransactions(); + + try{ + + producer.beginTransaction(); + + Stream.of(DATA_MESSAGE_1, DATA_MESSAGE_2).forEach(s -> producer.send( + new ProducerRecord("input", null, s))); + + producer.commitTransaction(); + + }catch (KafkaException e){ + + producer.abortTransaction(); + + } + + } + + private static KafkaProducer createKafkaProducer() { + + Properties props = new Properties(); + props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ENABLE_IDEMPOTENCE_CONFIG, "true"); + props.put(TRANSACTIONAL_ID_CONFIG, "prod-0"); + props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + + return new KafkaProducer(props); + + } +} diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalApp.java b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java similarity index 66% rename from libraries/src/main/java/com/baeldung/kafka/TransactionalApp.java rename to libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java index 1e95041a0d..0563ba6684 100644 --- a/libraries/src/main/java/com/baeldung/kafka/TransactionalApp.java +++ b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java @@ -14,6 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static java.time.Duration.ofSeconds; import static java.util.Collections.singleton; @@ -21,16 +23,16 @@ import static org.apache.kafka.clients.consumer.ConsumerConfig.*; import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG; import static org.apache.kafka.clients.producer.ProducerConfig.*; -public class TransactionalApp { +public class TransactionalWordCount { - private static final String CONSUMER_GROUP_ID = "test"; + private static final String CONSUMER_GROUP_ID = "my-group-id"; private static final String OUTPUT_TOPIC = "output"; private static final String INPUT_TOPIC = "input"; public static void main(String[] args) { - KafkaConsumer consumer = initConsumer(); - KafkaProducer producer = initProducer(); + KafkaConsumer consumer = createKafkaConsumer(); + KafkaProducer producer = createKafkaProducer(); producer.initTransactions(); @@ -38,12 +40,17 @@ public class TransactionalApp { while (true) { - ConsumerRecords records = consumer.poll(ofSeconds(20)); + ConsumerRecords records = consumer.poll(ofSeconds(60)); + + Map wordCountMap = records.records(new TopicPartition(INPUT_TOPIC, 0)) + .stream() + .flatMap(record -> Stream.of(record.value().split(" "))) + .map(word -> Tuple.of(word, 1)) + .collect(Collectors.toMap(tuple -> tuple.getKey(), t1 -> t1.getValue(), (v1, v2) -> v1 + v2)); producer.beginTransaction(); - for (ConsumerRecord record : records) - producer.send(new ProducerRecord(OUTPUT_TOPIC, record)); + wordCountMap.forEach((key, value) -> producer.send(new ProducerRecord(OUTPUT_TOPIC, key, value.toString()))); Map offsetsToCommit = new HashMap<>(); @@ -51,7 +58,7 @@ public class TransactionalApp { List> partitionedRecords = records.records(partition); long offset = partitionedRecords.get(partitionedRecords.size() - 1).offset(); - offsetsToCommit.put(partition, new OffsetAndMetadata(offset)); + offsetsToCommit.put(partition, new OffsetAndMetadata(offset + 1)); } producer.sendOffsetsToTransaction(offsetsToCommit, CONSUMER_GROUP_ID); @@ -68,11 +75,12 @@ public class TransactionalApp { } - private static KafkaConsumer initConsumer() { + private static KafkaConsumer createKafkaConsumer() { Properties props = new Properties(); props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(GROUP_ID_CONFIG, CONSUMER_GROUP_ID); props.put(ENABLE_AUTO_COMMIT_CONFIG, "false"); + props.put(ISOLATION_LEVEL_CONFIG, "read_committed"); props.put(KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put(VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); @@ -81,19 +89,14 @@ public class TransactionalApp { return consumer; } - private static KafkaProducer initProducer() { + private static KafkaProducer createKafkaProducer() { Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put(ACKS_CONFIG, "all"); - props.put(RETRIES_CONFIG, 3); - props.put(BATCH_SIZE_CONFIG, 16384); - props.put(LINGER_MS_CONFIG, 1); - props.put(BUFFER_MEMORY_CONFIG, 33554432); + props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ENABLE_IDEMPOTENCE_CONFIG, "true"); props.put(TRANSACTIONAL_ID_CONFIG, "prod-1"); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); return new KafkaProducer(props); diff --git a/libraries/src/main/java/com/baeldung/kafka/Tuple.java b/libraries/src/main/java/com/baeldung/kafka/Tuple.java new file mode 100644 index 0000000000..883de4ba21 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/Tuple.java @@ -0,0 +1,24 @@ +package com.baeldung.kafka; + +public class Tuple { + + private String key; + private Integer value; + + private Tuple(String key, Integer value) { + this.key = key; + this.value = value; + } + + public static Tuple of(String key, Integer value){ + return new Tuple(key,value); + } + + public String getKey() { + return key; + } + + public Integer getValue() { + return value; + } +} diff --git a/pom.xml b/pom.xml index 66293fe31b..4ffd9ba4a4 100644 --- a/pom.xml +++ b/pom.xml @@ -408,6 +408,7 @@ libraries libraries-data + libraries-security libraries-server linkrest logging-modules/log-mdc @@ -470,7 +471,7 @@ spring-boot-persistence spring-boot-security spring-boot-mvc - spring-boot-vue + spring-boot-vue spring-boot-logging-log4j2 spring-cloud-data-flow spring-cloud @@ -606,7 +607,7 @@ jta java-websocket - + activejdbc apache-bval @@ -634,7 +635,7 @@ spring-boot-autoconfiguration spring-boot-custom-starter - + spring-boot-jasypt spring-data-rest-querydsl @@ -651,11 +652,11 @@ stripe - + Twitter4J wicket xstream cas/cas-secured-app - + cas/cas-server @@ -674,7 +675,7 @@ spring-boot-custom-starter/greeter spring-boot-h2/spring-boot-h2-database - spring-boot-h2/spring-boot-h2-remote-app + @@ -991,7 +992,7 @@ spring-boot-custom-starter/greeter spring-boot-h2/spring-boot-h2-database - spring-boot-h2/spring-boot-h2-remote-app + diff --git a/spring-4/pom.xml b/spring-4/pom.xml index cf10f64aa2..78939bba95 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -71,10 +71,8 @@ - UTF-8 1.0.1 1.16.18 - 1.8 1.4.197 diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java index 8d7860ccdc..76b697c1aa 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java @@ -39,7 +39,7 @@ public class EmployeeFunctionalConfig { } @Bean - RouterFunction updateEmployee() { + RouterFunction updateEmployeeRoute() { return route(POST("/employees/update"), req -> req.body(toMono(Employee.class)) .doOnNext(employeeRepository()::updateEmployee) diff --git a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java index 1197820066..6e73e8072c 100644 --- a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java @@ -1,13 +1,37 @@ package com.baeldung.reactive.functional; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class EmployeeSpringFunctionalIntegrationTest { - private static EmployeeFunctionalConfig config = new EmployeeFunctionalConfig(); + @Autowired + private EmployeeFunctionalConfig config; + + @MockBean + private EmployeeRepository employeeRepository; @Test public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { @@ -15,7 +39,9 @@ public class EmployeeSpringFunctionalIntegrationTest { .bindToRouterFunction(config.getEmployeeByIdRoute()) .build(); - Employee expected = new Employee("1", "Employee 1"); + Employee employee = new Employee("1", "Employee 1"); + + given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); client.get() .uri("/employees/1") @@ -23,6 +49,50 @@ public class EmployeeSpringFunctionalIntegrationTest { .expectStatus() .isOk() .expectBody(Employee.class) - .isEqualTo(expected); + .isEqualTo(employee); + } + + @Test + public void whenGetAllEmployees_thenCorrectEmployees() { + WebTestClient client = WebTestClient + .bindToRouterFunction(config.getAllEmployeesRoute()) + .build(); + + List employeeList = new ArrayList<>(); + + Employee employee1 = new Employee("1", "Employee 1"); + Employee employee2 = new Employee("2", "Employee 2"); + + employeeList.add(employee1); + employeeList.add(employee2); + + Flux employeeFlux = Flux.fromIterable(employeeList); + given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); + + client.get() + .uri("/employees") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Employee.class) + .isEqualTo(employeeList); + } + + @Test + public void whenUpdateEmployee_thenEmployeeUpdated() { + WebTestClient client = WebTestClient + .bindToRouterFunction(config.updateEmployeeRoute()) + .build(); + + Employee employee = new Employee("1", "Employee 1 Updated"); + + client.post() + .uri("/employees/update") + .body(Mono.just(employee), Employee.class) + .exchange() + .expectStatus() + .isOk(); + + verify(employeeRepository).updateEmployee(employee); } } diff --git a/spring-boot-h2/spring-boot-h2-database/pom.xml b/spring-boot-h2/spring-boot-h2-database/pom.xml index 4b660334da..94f2293c34 100644 --- a/spring-boot-h2/spring-boot-h2-database/pom.xml +++ b/spring-boot-h2/spring-boot-h2-database/pom.xml @@ -22,6 +22,8 @@ UTF-8 UTF-8 1.8 + + com.mycorp.starter.HelloWorldApplication diff --git a/spring-boot-h2/spring-boot-h2-remote-app/src/main/java/com/baeldung/h2db/demo/ClientSpringBootApp.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java similarity index 85% rename from spring-boot-h2/spring-boot-h2-remote-app/src/main/java/com/baeldung/h2db/demo/ClientSpringBootApp.java rename to spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java index 39e52afd2c..7402312e1c 100644 --- a/spring-boot-h2/spring-boot-h2-remote-app/src/main/java/com/baeldung/h2db/demo/ClientSpringBootApp.java +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java @@ -1,4 +1,4 @@ -package com.baeldung.h2db.demo; +package com.baeldung.h2db.demo.client; import java.sql.ResultSet; import java.sql.SQLException; @@ -7,16 +7,20 @@ import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; @SpringBootApplication +@ComponentScan("com.baeldung.h2db.demo.client") public class ClientSpringBootApp { @Autowired private JdbcTemplate jdbcTemplate; public static void main(String[] args) { + System.setProperty("spring.datasource.url","jdbc:h2:tcp://localhost:9091/mem:mydb"); SpringApplication.run(ClientSpringBootApp.class, args); } @@ -46,4 +50,4 @@ public class ClientSpringBootApp { } }); } -} \ No newline at end of file +} diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/SpringBootApp.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java similarity index 88% rename from spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/SpringBootApp.java rename to spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java index 1fe080ec22..e75b42a934 100644 --- a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/SpringBootApp.java +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java @@ -1,4 +1,4 @@ -package com.baeldung.h2db.demo; +package com.baeldung.h2db.demo.server; import java.sql.ResultSet; import java.sql.SQLException; @@ -9,10 +9,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; @SpringBootApplication +@ComponentScan("com.baeldung.h2db.demo.server") public class SpringBootApp { @Autowired @@ -24,8 +26,7 @@ public class SpringBootApp { @PostConstruct private void initDb() { - System.out.println(String.format( - "****** Creating table: %s, and Inserting test data ******", "Employees")); + System.out.println(String.format("****** Creating table: %s, and Inserting test data ******", "Employees")); String sqlStatements[] = { "drop table employees if exists", @@ -57,4 +58,4 @@ public class SpringBootApp { public Server inMemoryH2DatabaseServer() throws SQLException { return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9091"); } -} \ No newline at end of file +} diff --git a/spring-boot-h2/spring-boot-h2-remote-app/.gitignore b/spring-boot-h2/spring-boot-h2-remote-app/.gitignore deleted file mode 100644 index 82eca336e3..0000000000 --- a/spring-boot-h2/spring-boot-h2-remote-app/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/build/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-remote-app/pom.xml b/spring-boot-h2/spring-boot-h2-remote-app/pom.xml deleted file mode 100644 index 8eb59d2098..0000000000 --- a/spring-boot-h2/spring-boot-h2-remote-app/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - 4.0.0 - - com.baeldung.h2db - spring-boot-h2-remote-app - 0.0.1-SNAPSHOT - jar - - Demo Spring Boot applications that access H2 in memory database created - in another Spring Boot application - - - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - com.h2database - h2 - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - diff --git a/spring-boot-h2/spring-boot-h2-remote-app/src/main/resources/application.properties b/spring-boot-h2/spring-boot-h2-remote-app/src/main/resources/application.properties deleted file mode 100644 index 6c3446f03a..0000000000 --- a/spring-boot-h2/spring-boot-h2-remote-app/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -spring.datasource.url=jdbc:h2:tcp://localhost:9091/mem:mydb -spring.datasource.driverClassName=org.h2.Driver -spring.datasource.username=sa -spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/spring-boot-jasypt/pom.xml b/spring-boot-jasypt/pom.xml index 212f524da6..de0df92678 100644 --- a/spring-boot-jasypt/pom.xml +++ b/spring-boot-jasypt/pom.xml @@ -5,7 +5,6 @@ com.example.jasypt spring-boot-jasypt - 0.0.1-SNAPSHOT jar spring-boot-jasypt Demo project for Spring Boot @@ -52,9 +51,6 @@ - UTF-8 - UTF-8 - 1.8 2.0.0 diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java similarity index 94% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java rename to spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java index 58c2dc7bb2..c24cfe6efa 100644 --- a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.jasypt.Main; @RunWith(SpringRunner.class) @SpringBootTest(classes = {Main.class}) -public class CustomJasyptTest { +public class CustomJasyptIntegrationTest { @Autowired ApplicationContext appCtx; diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java similarity index 95% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java rename to spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java index f9b66b5044..e8dda73b4a 100644 --- a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java @@ -13,7 +13,7 @@ import com.baeldung.jasypt.simple.PropertyServiceForJasyptSimple; @RunWith(SpringRunner.class) @SpringBootTest -public class JasyptSimpleTest { +public class JasyptSimpleIntegrationTest { @Autowired ApplicationContext appCtx; diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java similarity index 95% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java rename to spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java index d246c21036..5f5d409ab9 100644 --- a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.jasypt.starter.PropertyServiceForJasyptStarter; @RunWith(SpringRunner.class) @SpringBootTest -public class JasyptWithStarterTest { +public class JasyptWithStarterIntegrationTest { @Autowired ApplicationContext appCtx; diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml index c4f9b12676..c3bad74352 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml @@ -1,15 +1,13 @@ 4.0.0 - com.baeldung - 0.0.1-SNAPSHOT disabling-console-jul - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - + + com.baeldung + disabling-console-logging + 0.0.1-SNAPSHOT + @@ -45,9 +43,4 @@ - - UTF-8 - UTF-8 - 1.8 - \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml index 97d10c574a..f9b34ec7d9 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml @@ -1,49 +1,42 @@ - 4.0.0 - com.baeldung - 0.0.1-SNAPSHOT - disabling-console-log4j2 - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + disabling-console-log4j2 - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-log4j2 - - + + com.baeldung + disabling-console-logging + 0.0.1-SNAPSHOT + - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + - - UTF-8 - UTF-8 - 1.8 - + + + + org.springframework.boot + spring-boot-maven-plugin + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/pom.xml index bc248e49b2..39a4a40f12 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/pom.xml +++ b/spring-boot-logging-log4j2/disabling-console-logging/pom.xml @@ -1,8 +1,6 @@ 4.0.0 - 0.0.1-SNAPSHOT - com.baeldung disabling-console-logging pom Projects for Disabling Spring Boot Console Logging tutorials diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index ee4d07c3e8..7caf1e8690 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-boot-logging-log4j2 - 0.0.1-SNAPSHOT pom Projects for Spring Boot Logging tutorials @@ -43,10 +41,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml index 1d4c8867fb..571794167e 100644 --- a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml +++ b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-boot-logging-log4j2-app - 0.0.1-SNAPSHOT jar Demo project for Spring Boot Logging with Log4J2 diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index 9ca187db5d..06712e4791 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - com.baeldung spring-boot-mvc - 0.0.1-SNAPSHOT jar spring-boot-mvc - Demo project for Spring Boot + Module For Spring Boot MVC parent-boot-2 @@ -21,6 +19,32 @@ org.springframework.boot spring-boot-starter-web + + + com.sun.faces + jsf-api + 2.2.9 + + + org.apache.tomcat.embed + tomcat-embed-jasper + + + javax.faces + javax.faces-api + 2.1 + + + javax.servlet + jstl + 1.2 + + + com.sun.faces + jsf-impl + 2.2.8-02 + + org.springframework.boot @@ -55,9 +79,6 @@ - UTF-8 - UTF-8 - 1.8 1.10.0 com.baeldung.springbootmvc.SpringBootMvcApplication diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanA.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java similarity index 73% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanA.java rename to spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java index 21d7007917..030216b747 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanA.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java @@ -1,4 +1,4 @@ -package com.baeldung.springbootmvc.nosuchbeandefinitionexception; +package com.baeldung.nosuchbeandefinitionexception; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java new file mode 100644 index 0000000000..f0cc263504 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.nosuchbeandefinitionexception; + +public class BeanB { + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java similarity index 82% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java rename to spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java index 01d19437c5..8709cf85ac 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java @@ -1,4 +1,4 @@ -package com.baeldung.springbootmvc.nosuchbeandefinitionexception; +package com.baeldung.nosuchbeandefinitionexception; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java new file mode 100644 index 0000000000..5b4250d5e3 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java @@ -0,0 +1,31 @@ +package com.baeldung.springbootmvc.jsfapplication; + +import javax.faces.webapp.FacesServlet; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +import com.baeldung.springbootmvc.jsfapplication.controller.JsfController; +import com.baeldung.springbootmvc.jsfapplication.model.TodoDao; +import com.baeldung.springbootmvc.jsfapplication.service.TodoService; + +@SpringBootApplication +@ComponentScan(basePackageClasses = { JsfController.class, TodoDao.class, TodoService.class }) +public class JsfApplication extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(JsfApplication.class, args); + } + + @Bean + public ServletRegistrationBean servletRegistrationBean() { + FacesServlet servlet = new FacesServlet(); + ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.jsf"); + return servletRegistrationBean; + } + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java new file mode 100644 index 0000000000..a9d21175c7 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java @@ -0,0 +1,19 @@ +package com.baeldung.springbootmvc.jsfapplication.controller; + +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Scope(value = "session") +@Component(value = "jsfController") +public class JsfController { + + public String loadTodoPage() { + checkPermission(); + return "/todo.xhtml"; + } + + private void checkPermission() { + // Details omitted + } + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java new file mode 100644 index 0000000000..0b97c5a78e --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java @@ -0,0 +1,17 @@ +package com.baeldung.springbootmvc.jsfapplication.model; + +import java.util.Collection; +import java.util.Optional; + +public interface Dao { + + Optional get(int id); + + Collection getAll(); + + int save(T t); + + void update(T t); + + void delete(T t); +} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java new file mode 100644 index 0000000000..7aa8480f43 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java @@ -0,0 +1,32 @@ +package com.baeldung.springbootmvc.jsfapplication.model; + +public class Todo { + + private int id; + private String message; + private int priority; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java new file mode 100644 index 0000000000..96d44474af --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java @@ -0,0 +1,48 @@ +package com.baeldung.springbootmvc.jsfapplication.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Component; + +@Component +public class TodoDao implements Dao { + + private List todoList = new ArrayList<>(); + + @Override + public Optional get(int id) { + return Optional.ofNullable(todoList.get(id)); + } + + @Override + public Collection getAll() { + return todoList.stream() + .filter(Objects::nonNull) + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); + } + + @Override + public int save(Todo todo) { + todoList.add(todo); + int index = todoList.size() - 1; + todo.setId(index); + return index; + } + + @Override + public void update(Todo todo) { + todoList.set(todo.getId(), todo); + } + + @Override + public void delete(Todo todo) { + todoList.set(todo.getId(), null); + } + +} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java new file mode 100644 index 0000000000..89af3c66b9 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java @@ -0,0 +1,50 @@ +package com.baeldung.springbootmvc.jsfapplication.service; + +import java.util.Collection; +import java.util.Comparator; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import com.baeldung.springbootmvc.jsfapplication.model.Dao; +import com.baeldung.springbootmvc.jsfapplication.model.Todo; + +@Scope(value = "session") +@Component(value = "todoService") +public class TodoService { + + @Autowired + private Dao todoDao; + private Todo todo = new Todo(); + + public void save() { + todoDao.save(todo); + todo = new Todo(); + } + + public Collection getAllTodo() { + return todoDao.getAll(); + } + + public Collection getAllTodoSortedByPriority() { + return todoDao.getAll() + .stream() + .sorted(Comparator.comparingInt(Todo::getId)) + .collect(Collectors.toList()); + } + + public int saveTodo(Todo todo) { + validate(todo); + return todoDao.save(todo); + } + + private void validate(Todo todo) { + // Details omitted + } + + public Todo getTodo() { + return todo; + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanB.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanB.java deleted file mode 100644 index 3dd72aacc6..0000000000 --- a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.springbootmvc.nosuchbeandefinitionexception; - -public class BeanB { - -} diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml b/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml new file mode 100644 index 0000000000..9e31a2e09d --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml @@ -0,0 +1,9 @@ + + + + org.springframework.web.jsf.el.SpringBeanFacesELResolver + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml b/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e0cd4d8850 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + + Faces Servlet + javax.faces.webapp.FacesServlet + 1 + + + Faces Servlet + *.jsf + + + com.sun.faces.forceLoadConfiguration + true + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/index.xhtml b/spring-boot-mvc/src/main/webapp/index.xhtml new file mode 100644 index 0000000000..40042b812c --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/index.xhtml @@ -0,0 +1,20 @@ + + + + + TO-DO application + + + + Welcome in the TO-DO application! + + This is a static message rendered from xhtml. + + + + + + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/todo.xhtml b/spring-boot-mvc/src/main/webapp/todo.xhtml new file mode 100644 index 0000000000..426e101908 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/todo.xhtml @@ -0,0 +1,38 @@ + + + + + TO-DO application + + + + + List of TO-DO items + + + + Message + #{item.message} + + + Priority + #{item.priority} + + + + + + Add new to-do item: + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 376d8099ed..d0095e9a8a 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -35,6 +35,7 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault + spring-cloud-security diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml b/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml new file mode 100644 index 0000000000..3ffbf8f619 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + dynamodb-config + jar + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + com.amazonaws + aws-java-sdk-dynamodb + ${aws.sdk.dynamo.version} + + + com.github.derjust + spring-data-dynamodb + ${spring.dynamo.version} + + + com.netflix.archaius + archaius-aws + ${archaius.version} + + + org.projectlombok + lombok + provided + + + + + 1.11.407 + 5.0.3 + 0.7.6 + + diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java new file mode 100644 index 0000000000..ee08f2b1fb --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.archaius.dynamosources; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DynamoSourcesApplication { + + public static void main(String[] args) { + SpringApplication.run(DynamoSourcesApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java new file mode 100644 index 0000000000..7b533e8021 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.config; + +import java.util.Arrays; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; +import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; +import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; +import com.amazonaws.services.dynamodbv2.util.TableUtils; +import com.baeldung.spring.cloud.archaius.dynamosources.dynamodb.ArchaiusProperties; +import com.baeldung.spring.cloud.archaius.dynamosources.dynamodb.ArchaiusPropertiesRepository; +import com.netflix.config.DynamicConfiguration; +import com.netflix.config.FixedDelayPollingScheduler; +import com.netflix.config.PolledConfigurationSource; +import com.netflix.config.sources.DynamoDbConfigurationSource; + +@Configuration +public class ApplicationPropertiesConfigurations { + + @Autowired + AmazonDynamoDB amazonDynamoDb; + + @Autowired + private ArchaiusPropertiesRepository repository; + + @Bean + public AbstractConfiguration addApplicationPropertiesSource() { + // Normally, the DB Table would be already created and populated. + // In this case, we'll do it just before creating the archaius config source that uses it + initDatabase(); + PolledConfigurationSource source = new DynamoDbConfigurationSource(amazonDynamoDb); + return new DynamicConfiguration(source, new FixedDelayPollingScheduler()); + } + + private void initDatabase() { + // Create the table + DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDb); + CreateTableRequest tableRequest = mapper.generateCreateTableRequest(ArchaiusProperties.class); + tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L)); + TableUtils.createTableIfNotExists(amazonDynamoDb, tableRequest); + + // Populate the table + ArchaiusProperties property = new ArchaiusProperties("baeldung.archaius.properties.one", "one FROM:dynamoDB"); + ArchaiusProperties property3 = new ArchaiusProperties("baeldung.archaius.properties.three", "three FROM:dynamoDB"); + repository.saveAll(Arrays.asList(property, property3)); + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java new file mode 100644 index 0000000000..8f12051a7f --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.config; + +import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.amazonaws.auth.AWSCredentialsProvider; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; + +@Configuration +@EnableDynamoDBRepositories(basePackages = "com.baeldung.spring.cloud.archaius.dynamosources.dynamodb") +public class DynamoDbConfiguration { + + @Value("${amazon.dynamodb.endpoint}") + private String amazonDynamoDBEndpoint; + + @Value("${aws.accessKeyId}") + private String amazonDynamoDBAccessKeyId; + + @Value("${aws.secretKey}") + private String amazonDynamoDBSecretKey; + + @Bean + public AmazonDynamoDB amazonDynamoDB() { + AmazonDynamoDB amazonDynamoDB = AmazonDynamoDBClientBuilder.standard() + .withCredentials(amazonAWSCredentials()) + .withEndpointConfiguration(setupEndpointConfiguration()) + .build(); + + return amazonDynamoDB; + } + + private AWSCredentialsProvider amazonAWSCredentials() { + return new AWSStaticCredentialsProvider(new BasicAWSCredentials(amazonDynamoDBAccessKeyId, amazonDynamoDBSecretKey)); + } + + private EndpointConfiguration setupEndpointConfiguration() { + return new EndpointConfiguration(amazonDynamoDBEndpoint, Regions.DEFAULT_REGION.getName()); + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..2ac5055fe3 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java new file mode 100644 index 0000000000..016f8433cf --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.dynamodb; + +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +@DynamoDBTable(tableName = "archaiusProperties") +public class ArchaiusProperties { + + @DynamoDBHashKey + @DynamoDBAttribute + private String key; + + @DynamoDBAttribute + private String value; +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java new file mode 100644 index 0000000000..fbcc953261 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.dynamodb; + +import org.springframework.data.repository.CrudRepository; + +public interface ArchaiusPropertiesRepository extends CrudRepository { + +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties new file mode 100644 index 0000000000..3823d2685f --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties @@ -0,0 +1,6 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties +amazon.dynamodb.endpoint=http://localhost:8000/ +aws.accessKeyId=key +aws.secretKey=key2 diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java new file mode 100644 index 0000000000..3802cb99cd --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.cloud.archaius.dynamosources; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusDynamoDbLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:dynamoDB"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:dynamoDB"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml b/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml new file mode 100644 index 0000000000..bb283576d8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + jdbc-config + jar + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java new file mode 100644 index 0000000000..ee7beec87b --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class JdbcSourcesApplication { + + public static void main(String[] args) { + SpringApplication.run(JdbcSourcesApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java new file mode 100644 index 0000000000..f3eed0c2b5 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig.config; + +import javax.sql.DataSource; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.netflix.config.DynamicConfiguration; +import com.netflix.config.FixedDelayPollingScheduler; +import com.netflix.config.PolledConfigurationSource; +import com.netflix.config.sources.JDBCConfigurationSource; + +@Configuration +public class ApplicationPropertiesConfigurations { + + @Autowired + DataSource h2DataSource; + + @Bean + public AbstractConfiguration addApplicationPropertiesSource() { + PolledConfigurationSource source = new JDBCConfigurationSource(h2DataSource, "select distinct key, value from properties", "key", "value"); + return new DynamicConfiguration(source, new FixedDelayPollingScheduler()); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..a793f39b29 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java new file mode 100644 index 0000000000..cc2783b506 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig.jdbc; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Properties { + + @Id + private String key; + + @SuppressWarnings("unused") + private String value; +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties new file mode 100644 index 0000000000..eca873f897 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties +spring.h2.console.enabled=true diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql new file mode 100644 index 0000000000..eb80126d48 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql @@ -0,0 +1,5 @@ +insert into properties +values('baeldung.archaius.properties.one', 'one FROM:jdbc_source'); + +insert into properties +values('baeldung.archaius.properties.three', 'three FROM:jdbc_source'); \ No newline at end of file diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java new file mode 100644 index 0000000000..91d5f5754e --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusJDBCSourceLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:jdbc_source"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:jdbc_source"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/pom.xml b/spring-cloud/spring-cloud-archaius/pom.xml index cd102f86cd..fd3e34e463 100644 --- a/spring-cloud/spring-cloud-archaius/pom.xml +++ b/spring-cloud/spring-cloud-archaius/pom.xml @@ -21,6 +21,9 @@ basic-config additional-sources-simple extra-configs + jdbc-config + dynamodb-config + zookeeper-config diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml new file mode 100644 index 0000000000..8f8ec99ad8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + zookeeper-config + jar + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-zookeeper-config + ${cloud.zookeeper.version} + + + org.apache.zookeeper + zookeeper + + + + + org.apache.zookeeper + zookeeper + ${zookeeper.version} + + + org.slf4j + slf4j-log4j12 + + + + + + + 2.0.0.RELEASE + 3.4.13 + + diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java new file mode 100644 index 0000000000..12119e3e29 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ZookeeperConfigApplication { + + public static void main(String[] args) { + SpringApplication.run(ZookeeperConfigApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java new file mode 100644 index 0000000000..59ef10aaf7 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java @@ -0,0 +1,58 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig.config; + +import org.apache.curator.framework.CuratorFramework; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +/** + * + * Ideally, we wouldn't need to initialize the zookeeper config values. + * Here we do it to verify that configurations are being retrieved. + * + */ +@Component +public class ZookeeperConfigsInitializer { + + private static final String CONFIG_BASE_NODE_PATH = "/config"; + private static final String APPLICATION_BASE_NODE_PATH = CONFIG_BASE_NODE_PATH + "/application"; + + @Autowired + CuratorFramework client; + + @EventListener + public void appReady(ApplicationReadyEvent event) throws Exception { + String pathOne = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.one"; + String valueOne = "one FROM:zookeeper"; + String pathThree = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.three"; + String valueThree = "three FROM:zookeeper"; + createBaseNodes(); + setValue(pathOne, valueOne); + setValue(pathThree, valueThree); + } + + private void setValue(String path, String value) throws Exception { + if (client.checkExists() + .forPath(path) == null) { + client.create() + .forPath(path, value.getBytes()); + } else { + client.setData() + .forPath(path, value.getBytes()); + } + } + + private void createBaseNodes() throws Exception { + if (client.checkExists() + .forPath(CONFIG_BASE_NODE_PATH) == null) { + client.create() + .forPath(CONFIG_BASE_NODE_PATH); + } + if (client.checkExists() + .forPath(APPLICATION_BASE_NODE_PATH) == null) { + client.create() + .forPath(APPLICATION_BASE_NODE_PATH); + } + } +} diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..c8a5e53ee4 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java @@ -0,0 +1,51 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + @Value("${baeldung.archaius.properties.one:not found!}") + private String propertyOneWithValue; + + @Value("${baeldung.archaius.properties.two:not found!}") + private String propertyTwoWithValue; + + @Value("${baeldung.archaius.properties.three:not found!}") + private String propertyThreeWithValue; + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + return properties; + } + + @GetMapping("/properties-from-value") + public Map getPropertiesFromValue() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithValue); + properties.put("baeldung.archaius.properties.two", propertyTwoWithValue); + properties.put("baeldung.archaius.properties.three", propertyThreeWithValue); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties new file mode 100644 index 0000000000..91ad18a932 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties +spring.application.name=zookeeper-config diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java new file mode 100644 index 0000000000..ff4358cb8f --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusZookeeperLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:zookeeper"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:zookeeper"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-functions/README.MD b/spring-cloud/spring-cloud-functions/README.MD new file mode 100644 index 0000000000..c766dd1dc6 --- /dev/null +++ b/spring-cloud/spring-cloud-functions/README.MD @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Serverless Functions with Spring Cloud Function](https://www.baeldung.com/spring-cloud-function) diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml index e3c17329d0..8b2b0ad385 100644 --- a/spring-cloud/spring-cloud-functions/pom.xml +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -1,19 +1,94 @@ - + 4.0.0 - spring-cloud-functions - pom + + com.baeldung.spring + cloudfunction-aws + 0.0.1-SNAPSHOT + jar + + cloudfunction-aws + Demo project for Spring Cloud Function - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + - - spring-cloud-function-aws - - - \ No newline at end of file + + UTF-8 + UTF-8 + 1.8 + 1.0.1.RELEASE + 2.0.2 + + + + + org.springframework.cloud + spring-cloud-function-adapter-aws + ${spring-cloud-function.version} + + + + + org.springframework.cloud + spring-cloud-starter-function-web + 1.0.1.RELEASE + + + com.amazonaws + aws-lambda-java-events + ${aws-lambda-events.version} + provided + + + com.amazonaws + aws-lambda-java-core + 1.1.0 + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.springframework.boot.experimental + spring-boot-thin-layout + 1.0.10.RELEASE + + + + + org.apache.maven.plugins + maven-shade-plugin + + false + true + aws + + + + + + diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/pom.xml b/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/pom.xml deleted file mode 100644 index 8b2b0ad385..0000000000 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/pom.xml +++ /dev/null @@ -1,94 +0,0 @@ - - - 4.0.0 - - com.baeldung.spring - cloudfunction-aws - 0.0.1-SNAPSHOT - jar - - cloudfunction-aws - Demo project for Spring Cloud Function - - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - 1.0.1.RELEASE - 2.0.2 - - - - - org.springframework.cloud - spring-cloud-function-adapter-aws - ${spring-cloud-function.version} - - - - - org.springframework.cloud - spring-cloud-starter-function-web - 1.0.1.RELEASE - - - com.amazonaws - aws-lambda-java-events - ${aws-lambda-events.version} - provided - - - com.amazonaws - aws-lambda-java-core - 1.1.0 - provided - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - true - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.springframework.boot.experimental - spring-boot-thin-layout - 1.0.10.RELEASE - - - - - org.apache.maven.plugins - maven-shade-plugin - - false - true - aws - - - - - - diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/CloudFunctionAwsApplication.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java similarity index 92% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/CloudFunctionAwsApplication.java rename to spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java index cc8f11beca..34e97d3b6c 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/CloudFunctionAwsApplication.java +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloudfunction; +package com.baeldung.spring.cloudfunction.aws; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/StringReverseHandler.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java similarity index 78% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/StringReverseHandler.java rename to spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java index d103bc98d9..52514dcd12 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/StringReverseHandler.java +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloudfunction; +package com.baeldung.spring.cloudfunction.aws; import org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler; diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/functions/Greeter.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java similarity index 80% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/functions/Greeter.java rename to spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java index 124aefe56e..c443b98c18 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/functions/Greeter.java +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloudfunction.functions; +package com.baeldung.spring.cloudfunction.functions.aws; import java.util.function.Function; diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/resources/application.properties b/spring-cloud/spring-cloud-functions/src/main/resources/application.properties similarity index 76% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/resources/application.properties rename to spring-cloud/spring-cloud-functions/src/main/resources/application.properties index 14426a848c..b445bfa4ed 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-functions/src/main/resources/application.properties @@ -1 +1 @@ -spring.cloud.function.scan.packages: com.baeldung.spring.cloudfunction.functions \ No newline at end of file +spring.cloud.function.scan.packages: com.baeldung.spring.cloudfunction.functions.aws \ No newline at end of file diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/test/java/com/baeldung/spring/cloudfunction/CloudFunctionApplicationTests.java b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java similarity index 96% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/test/java/com/baeldung/spring/cloudfunction/CloudFunctionApplicationTests.java rename to spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java index 01199475fb..6039debe3f 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/test/java/com/baeldung/spring/cloudfunction/CloudFunctionApplicationTests.java +++ b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloudfunction; +package com.baeldung.spring.cloudfunction.aws; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-cloud/spring-cloud-security/README.md b/spring-cloud/spring-cloud-security/README.md deleted file mode 100644 index 39af52c077..0000000000 --- a/spring-cloud/spring-cloud-security/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# README # - -This README would normally document whatever steps are necessary to get your application up and running. - -### What is this repository for? ### - -* Quick summary -* Version -* [Learn Markdown](https://bitbucket.org/tutorials/markdowndemo) - -### How do I get set up? ### - -* Summary of set up -* Configuration -* Dependencies -* Database configuration -* How to run tests -* Deployment instructions - -### Contribution guidelines ### - -* Writing tests -* Code review -* Other guidelines - -### Who do I talk to? ### - -* Repo owner or admin -* Other community or team contact \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index f2d6308374..340c276c2d 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -2,18 +2,15 @@ 4.0.0 - com.baeldung auth-client - 0.0.1-SNAPSHOT jar auth-client - Demo project for Spring Boot - + Spring Cloud Security APP Client Module + - parent-boot-1 + spring-cloud-security com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + 1.0.0-SNAPSHOT @@ -88,9 +85,6 @@ - UTF-8 - UTF-8 - 1.8 2.1.0 Dalston.SR4 diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java similarity index 87% rename from spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java rename to spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java index ca89575ee0..37cff095db 100644 --- a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java @@ -9,7 +9,7 @@ import com.baeldung.CloudSite; @RunWith(SpringRunner.class) @SpringBootTest(classes = CloudSite.class) -public class Springoath2ApplicationTests { +public class Springoath2ApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index 0115259108..09474b2a4d 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -3,21 +3,18 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung auth-resource - 0.0.1-SNAPSHOT jar auth-resource - Demo project for Spring Boot + Spring Cloud Security APP Resource Module - parent-boot-1 + spring-cloud-security com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + 1.0.0-SNAPSHOT - + org.springframework.security.oauth @@ -60,9 +57,6 @@ - UTF-8 - UTF-8 - 1.8 Edgware.RELEASE diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationTests.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationIntegrationTest.java similarity index 85% rename from spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationTests.java rename to spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationIntegrationTest.java index e0fe7006d9..3caa06ba4d 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationTests.java +++ b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class PersonserviceApplicationTests { +public class PersonserviceApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-security/auth-server/pom.xml b/spring-cloud/spring-cloud-security/auth-server/pom.xml index b4367935e3..92f92808f6 100644 --- a/spring-cloud/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-server/pom.xml @@ -2,15 +2,13 @@ 4.0.0 - com.baeldung auth-server - 0.0.1-SNAPSHOT - + Spring Cloud Security APP Server Module + - parent-boot-1 + spring-cloud-security com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-security/pom.xml b/spring-cloud/spring-cloud-security/pom.xml new file mode 100644 index 0000000000..1cf8751548 --- /dev/null +++ b/spring-cloud/spring-cloud-security/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + spring-cloud-security + pom + 1.0.0-SNAPSHOT + spring-cloud-security + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 + + + + auth-client + auth-resource + auth-server + + + diff --git a/spring-core/src/main/java/com/baeldung/definition/Config.java b/spring-core/src/main/java/com/baeldung/definition/Config.java new file mode 100644 index 0000000000..126e6259ca --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/Config.java @@ -0,0 +1,16 @@ +package com.baeldung.definition; + +import com.baeldung.definition.domain.Address; +import com.baeldung.definition.domain.Company; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackageClasses = Company.class) +public class Config { + @Bean + public Address getAddress() { + return new Address("High Street", 1000); + } +} diff --git a/spring-core/src/main/java/com/baeldung/definition/domain/Address.java b/spring-core/src/main/java/com/baeldung/definition/domain/Address.java new file mode 100644 index 0000000000..91be18398e --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/domain/Address.java @@ -0,0 +1,14 @@ +package com.baeldung.definition.domain; + +import lombok.Data; + +@Data +public class Address { + private String street; + private int number; + + public Address(String street, int number) { + this.street = street; + this.number = number; + } +} diff --git a/spring-core/src/main/java/com/baeldung/definition/domain/Company.java b/spring-core/src/main/java/com/baeldung/definition/domain/Company.java new file mode 100644 index 0000000000..eabde8afdf --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/domain/Company.java @@ -0,0 +1,14 @@ +package com.baeldung.definition.domain; + +import lombok.Data; +import org.springframework.stereotype.Component; + +@Data +@Component +public class Company { + private Address address; + + public Company(Address address) { + this.address = address; + } +} diff --git a/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java b/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java new file mode 100644 index 0000000000..0057611308 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java @@ -0,0 +1,18 @@ +package com.baeldung.definition; + +import com.baeldung.definition.domain.Company; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.Assert.assertEquals; + +public class SpringBeanIntegrationTest { + @Test + public void whenUsingIoC_thenDependenciesAreInjected() { + ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); + Company company = context.getBean("company", Company.class); + assertEquals("High Street", company.getAddress().getStreet()); + assertEquals(1000, company.getAddress().getNumber()); + } +} diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml index 9f6eb0d703..3cbbf63d94 100644 --- a/spring-rest-embedded-tomcat/pom.xml +++ b/spring-rest-embedded-tomcat/pom.xml @@ -3,7 +3,6 @@ 4.0.0 org.baeldung.embedded spring-rest-embedded-tomcat - 0.0.1-SNAPSHOT spring-rest-embedded-tomcat war @@ -61,33 +60,8 @@ - - spring-rest-embedded-tomcat - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - - 2.9.2 - 1.8 - 1.8 4.0.0 9.0.1 4.5.3 diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml index 2f7d1c8933..7a604946b6 100644 --- a/spring-rest-shell/pom.xml +++ b/spring-rest-shell/pom.xml @@ -2,9 +2,7 @@ 4.0.0 - com.baeldung spring-rest-shell - 0.0.1-SNAPSHOT jar spring-rest-shell A simple project to demonstrate Spring REST Shell features. @@ -48,10 +46,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/spring-security-mvc-socket/README.md b/spring-security-mvc-socket/README.md index 828d9a3448..3daf9199e6 100644 --- a/spring-security-mvc-socket/README.md +++ b/spring-security-mvc-socket/README.md @@ -1,3 +1,10 @@ +To build the project, run the command: mvn clean install. This will build a war file in the target folder that you can deploye on a server like Tomcat. + +Alternatively, run the project from an IDE. + +To login, use credentials from the data.sql file in src/main/resource, eg: user/password. + + ### Relevant Articles: - [Intro to Security and WebSockets](http://www.baeldung.com/spring-security-websockets) -- [Spring WebSockets: Specific User Chat](http://www.baeldung.com/spring-websocket-specific-user-chat) \ No newline at end of file +- [Spring WebSockets: Specific User Chat](https://www.baeldung.com/spring-websockets-send-message-to-user) diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index b7559753b5..ade24d8f7b 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -151,7 +151,7 @@ - + org.apache.tomcat.maven @@ -171,7 +171,6 @@ - spring-security-mvc-socket diff --git a/spring-security-openid/pom.xml b/spring-security-openid/pom.xml index a2c0b6b119..4343996e02 100644 --- a/spring-security-openid/pom.xml +++ b/spring-security-openid/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-security-openid - 0.0.1-SNAPSHOT war spring-security-openid Spring OpenID sample project diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 5bde78db7e..57ce5ddb92 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -300,7 +300,7 @@ 2.9.0 - 2.7.0 + 2.9.2 2.6 diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index d14dcc3176..8e551d850f 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-swagger-codegen 0.0.1-SNAPSHOT pom diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index 0f1cfa27ac..06a92ffae7 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -38,23 +38,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - org.apache.maven.plugins diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml index 281ed59857..0fb5cf8e75 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -1,11 +1,8 @@ 4.0.0 - - com.baeldung spring-swagger-codegen-app - 0.0.1-SNAPSHOT - + com.baeldung spring-swagger-codegen @@ -37,7 +34,6 @@ - 1.8 0.0.1-SNAPSHOT 1.5.10.RELEASE diff --git a/spring-vertx/pom.xml b/spring-vertx/pom.xml index 69a043ed01..790eeff128 100644 --- a/spring-vertx/pom.xml +++ b/spring-vertx/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-vertx - 0.0.1-SNAPSHOT jar Spring Vertx A demo project with vertx spring integration @@ -57,31 +55,10 @@ org.springframework.boot spring-boot-maven-plugin - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - UTF-8 - UTF-8 - 1.8 3.4.1 diff --git a/testing-modules/spring-context-testing/pom.xml b/testing-modules/spring-context-testing/pom.xml deleted file mode 100644 index 148192d6c5..0000000000 --- a/testing-modules/spring-context-testing/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - 4.0.0 - com.baeldung - spring-context-testing - 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-starter - ${spring.boot.starter.version} - - - org.springframework.boot - spring-boot-starter-test - test - ${spring.boot.starter.version} - - - - - 2.0.4.RELEASE - - diff --git a/testing-modules/spring-context-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java b/testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java similarity index 100% rename from testing-modules/spring-context-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java rename to testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java diff --git a/testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java similarity index 100% rename from testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java diff --git a/testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java similarity index 100% rename from testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java diff --git a/testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java similarity index 100% rename from testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java diff --git a/testing-modules/spring-context-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties b/testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties similarity index 100% rename from testing-modules/spring-context-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties rename to testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties diff --git a/testing-modules/spring-context-testing/src/test/resources/other-location.properties b/testing-modules/spring-testing/src/test/resources/other-location.properties similarity index 100% rename from testing-modules/spring-context-testing/src/test/resources/other-location.properties rename to testing-modules/spring-testing/src/test/resources/other-location.properties diff --git a/twilio/pom.xml b/twilio/pom.xml index 8683192b5c..610cc04b60 100644 --- a/twilio/pom.xml +++ b/twilio/pom.xml @@ -2,11 +2,15 @@ 4.0.0 - - com.baeldung twilio 1.0-SNAPSHOT + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + com.twilio.sdk @@ -15,9 +19,4 @@ - - 1.8 - 1.8 - -
Passwords should be stored in a {@code char[]} so that it can be filled + * with zeros after use instead of lingering on the heap and elsewhere. + * + * @deprecated Use {@link #hash(char[])} instead + */ + @Deprecated + public String hash(String password) + { + return hash(password.toCharArray()); + } + + /** + * Authenticate with a password in an immutable {@code String} and a stored + * password token. + * + * @deprecated Use {@link #checkPassword(char[],String)} instead. + * @see #hash(String) + */ + @Deprecated + public boolean checkPassword(String password, String token) + { + return checkPassword(password.toCharArray(), token); + } + +} diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java new file mode 100644 index 0000000000..4f5337f963 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java @@ -0,0 +1,35 @@ +package com.baeldung.passwordhashing; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + + +/** A really simple SHA_512 Encryption example. + * + */ +public class SHA512Hasher { + + public String hash(String passwordToHash, byte[] salt){ + String generatedPassword = null; + try { + MessageDigest md = MessageDigest.getInstance("SHA-512"); + md.update(salt); + byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for(int i=0; i< bytes.length ;i++){ + sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); + } + generatedPassword = sb.toString(); + } + catch (NoSuchAlgorithmException e){ + e.printStackTrace(); + } + return generatedPassword; + } + + public boolean checkPassword(String hash, String attempt, byte[] salt){ + String generatedHash = hash(attempt, salt); + return hash.equals(generatedHash); + } +} diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java new file mode 100644 index 0000000000..36c9b65070 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java @@ -0,0 +1,18 @@ +package com.baeldung.passwordhashing; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import java.security.spec.KeySpec; + +/** A really simple SimplePBKDF2 Encryption example. + * + */ +public class SimplePBKDF2Hasher { + + public static String hashSimple(String password, byte[] salt) throws Exception{ + KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128); + SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + byte[] hash = f.generateSecret(spec).getEncoded(); + return String.valueOf(hash); + } +} diff --git a/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java b/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java new file mode 100644 index 0000000000..69e151bfcb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java @@ -0,0 +1,70 @@ +package com.baeldung.switchstatement; + +public class SwitchStatement { + + public String exampleOfIF(String animal) { + + String result; + + if (animal.equals("DOG") || animal.equals("CAT")) { + result = "domestic animal"; + } else if (animal.equals("TIGER")) { + result = "wild animal"; + } else { + result = "unknown animal"; + } + return result; + } + + public String exampleOfSwitch(String animal) { + + String result; + + switch (animal) { + case "DOG": + case "CAT": + result = "domestic animal"; + break; + case "TIGER": + result = "wild animal"; + break; + default: + result = "unknown animal"; + break; + } + return result; + } + + public String forgetBreakInSwitch(String animal) { + + String result; + + switch (animal) { + + case "DOG": + System.out.println("domestic animal"); + result = "domestic animal"; + + default: + System.out.println("unknown animal"); + result = "unknown animal"; + + } + return result; + } + + public String constantCaseValue(String animal) { + + String result = ""; + + final String dog = "DOG"; + + switch (animal) { + + case dog: + result = "domestic animal"; + } + return result; + } + +} diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java index a22de0db18..fb92eb8d0d 100644 --- a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java @@ -1,16 +1,12 @@ package com.baeldung.zoneddatetime; -import java.time.LocalDateTime; import java.time.OffsetDateTime; -import java.time.ZoneId; import java.time.ZoneOffset; public class OffsetDateTimeExample { - public OffsetDateTime getCurrentTimeByZoneOffset(String region) { - LocalDateTime now = LocalDateTime.now(); - ZoneId zone = ZoneId.of(region); - ZoneOffset zoneOffSet= zone.getRules().getOffset(now); + public OffsetDateTime getCurrentTimeByZoneOffset(String offset) { + ZoneOffset zoneOffSet= ZoneOffset.of(offset); OffsetDateTime date = OffsetDateTime.now(zoneOffSet); return date; } diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java index 7d926c0562..58e2d4d5ad 100644 --- a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java @@ -1,17 +1,12 @@ package com.baeldung.zoneddatetime; -import java.time.LocalDateTime; import java.time.OffsetTime; -import java.time.ZoneId; import java.time.ZoneOffset; public class OffsetTimeExample { - public OffsetTime getCurrentTimeByZoneOffset(String region) { - LocalDateTime now = LocalDateTime.now(); - ZoneId zone = ZoneId.of(region); - ZoneOffset zoneOffSet = zone.getRules() - .getOffset(now); + public OffsetTime getCurrentTimeByZoneOffset(String offset) { + ZoneOffset zoneOffSet = ZoneOffset.of(offset); OffsetTime time = OffsetTime.now(zoneOffSet); return time; } diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java b/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java new file mode 100644 index 0000000000..8e90725c77 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.passwordhashing; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + + +public class PBKDF2HasherUnitTest { + + private PBKDF2Hasher mPBKDF2Hasher; + + @Before + public void setUp() throws Exception { + mPBKDF2Hasher = new PBKDF2Hasher(); + } + + @Test + public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception { + String message1 = "password123"; + + String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); + + assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1)); + + } + + @Test + public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception { + String message1 = "password123"; + + String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); + + String wrongPasswordAttempt = "IamWrong"; + + assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1)); + + } + + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java b/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java new file mode 100644 index 0000000000..3acfb0ba9d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.passwordhashing; + +import org.junit.Before; +import org.junit.Test; + +import java.security.SecureRandom; + +import static org.junit.Assert.*; + +/** + * Created by PhysicsSam on 06-Sep-18. + */ +public class SHA512HasherUnitTest { + + private SHA512Hasher hasher; + private SecureRandom secureRandom; + + @Before + public void setUp() throws Exception { + hasher = new SHA512Hasher(); + secureRandom = new SecureRandom(); + } + + @Test + public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception { + + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String hash1 = hasher.hash("password", salt); + String hash2 = hasher.hash("password", salt); + + assertEquals(hash1, hash2); + + } + + @Test + public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception { + + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + String hash1 = hasher.hash("password", salt); + //generate a second salt + byte[] secondSalt = new byte[16]; + String hash2 = hasher.hash("password", secondSalt); + + assertNotEquals(hash1, hash2); + + } + + @Test + public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception { + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String originalHash = hasher.hash("password123", salt); + + assertTrue(hasher.checkPassword(originalHash, "password123", salt)); + } + + @Test + public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception { + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String originalHash = hasher.hash("password123", salt); + + assertFalse(hasher.checkPassword(originalHash, "password124", salt)); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java b/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java new file mode 100644 index 0000000000..e8ac645531 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.switchstatement; + +import org.junit.Test; + +import org.junit.Assert; + +public class SwitchStatementUnitTest { + private SwitchStatement s = new SwitchStatement(); + + + @Test + public void whenDog_thenDomesticAnimal() { + + String animal = "DOG"; + Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal)); + } + + @Test + public void whenNoBreaks_thenGoThroughBlocks() { + String animal = "DOG"; + Assert.assertEquals("unknown animal", s.forgetBreakInSwitch(animal)); + } + + @Test(expected=NullPointerException.class) + public void whenSwitchAgumentIsNull_thenNullPointerException() { + String animal = null; + Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal)); + } + + + @Test + public void whenCompareStrings_thenByEqual() { + String animal = new String("DOG"); + Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal)); + } + + +} diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java index c60f6967f9..a08d3737cd 100644 --- a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java @@ -2,9 +2,8 @@ package com.baeldung.zoneddatetime; import static org.junit.Assert.assertTrue; -import java.time.LocalDateTime; import java.time.OffsetDateTime; -import java.time.ZoneId; +import java.time.ZoneOffset; import org.junit.Test; @@ -14,12 +13,10 @@ public class OffsetDateTimeExampleUnitTest { @Test public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() { - String zone = "Europe/Berlin"; - OffsetDateTime time = offsetDateTimeExample.getCurrentTimeByZoneOffset(zone); + String offset = "+02:00"; + OffsetDateTime time = offsetDateTimeExample.getCurrentTimeByZoneOffset(offset); assertTrue(time.getOffset() - .equals(ZoneId.of(zone) - .getRules() - .getOffset(LocalDateTime.now()))); + .equals(ZoneOffset.of(offset))); } } diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java index 0e1206dc5b..488f934179 100644 --- a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java @@ -2,9 +2,8 @@ package com.baeldung.zoneddatetime; import static org.junit.Assert.assertTrue; -import java.time.LocalDateTime; import java.time.OffsetTime; -import java.time.ZoneId; +import java.time.ZoneOffset; import org.junit.Test; @@ -14,12 +13,10 @@ public class OffsetTimeExampleUnitTest { @Test public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() { - String zone = "Europe/Berlin"; - OffsetTime time = offsetTimeExample.getCurrentTimeByZoneOffset(zone); + String offset = "+02:00"; + OffsetTime time = offsetTimeExample.getCurrentTimeByZoneOffset(offset); assertTrue(time.getOffset() - .equals(ZoneId.of(zone) - .getRules() - .getOffset(LocalDateTime.now()))); + .equals(ZoneOffset.of(offset))); } } diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java index 7f4f9cd17c..e78ff3e3fd 100644 --- a/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java @@ -15,16 +15,19 @@ public class ZoneDateTimeExampleUnitTest { public void givenZone_whenGetCurrentTime_thenResultHasZone() { String zone = "Europe/Berlin"; ZonedDateTime time = zoneDateTimeExample.getCurrentTimeByZoneId(zone); + assertTrue(time.getZone() .equals(ZoneId.of(zone))); } - + @Test public void givenZones_whenConvertDateByZone_thenGetConstantDiff() { String sourceZone = "Europe/Berlin"; String destZone = "Asia/Tokyo"; ZonedDateTime sourceDate = zoneDateTimeExample.getCurrentTimeByZoneId(sourceZone); ZonedDateTime destDate = zoneDateTimeExample.convertZonedDateTime(sourceDate, destZone); - assertTrue(sourceDate.toInstant().compareTo(destDate.toInstant()) == 0); + + assertTrue(sourceDate.toInstant() + .compareTo(destDate.toInstant()) == 0); } } diff --git a/java-streams/pom.xml b/java-streams/pom.xml index 023a5f695b..e4670c268d 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -105,7 +105,7 @@ 3.5 1.16.12 0.9.0 - 1.13 + 1.15 0.6.5 2.10 diff --git a/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java b/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java new file mode 100644 index 0000000000..1b64c8924a --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java @@ -0,0 +1,209 @@ +package com.baeldung.protonpack; + +import com.codepoetics.protonpack.Indexed; +import com.codepoetics.protonpack.StreamUtils; +import com.codepoetics.protonpack.collectors.CollectorUtils; +import com.codepoetics.protonpack.collectors.NonUniqueValueException; +import com.codepoetics.protonpack.selectors.Selector; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Arrays.stream; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +@SuppressWarnings("unchecked") +public class ProtonpackUnitTest { + @Test + public void whenTakeWhile_thenTakenWhile() { + Stream streamOfInt = Stream.iterate(1, i -> i + 1); + List result = StreamUtils.takeWhile(streamOfInt, i -> i < 5).collect(Collectors.toList()); + assertThat(result).contains(1, 2, 3, 4); + } + + @Test + public void whenTakeUntil_thenTakenUntil() { + Stream streamOfInt = Stream.iterate(1, i -> i + 1); + List result = StreamUtils.takeUntil(streamOfInt, i -> i > 50).collect(Collectors.toList()); + assertThat(result).contains(10, 20, 30, 40); + } + + @Test + public void givenMultipleStream_whenZipped_thenZipped() { + String[] clubs = { "Juventus", "Barcelona", "Liverpool", "PSG" }; + String[] players = { "Ronaldo", "Messi", "Salah" }; + Set zippedFrom2Sources = StreamUtils.zip(stream(clubs), stream(players), (club, player) -> club + " " + player) + .collect(Collectors.toSet()); + assertThat(zippedFrom2Sources).contains("Juventus Ronaldo", "Barcelona Messi", "Liverpool Salah"); + + String[] leagues = { "Serie A", "La Liga", "Premier League" }; + Set zippedFrom3Sources = StreamUtils.zip(stream(clubs), stream(players), stream(leagues), + (club, player, league) -> club + " " + player + " " + league).collect(Collectors.toSet()); + assertThat(zippedFrom3Sources).contains("Juventus Ronaldo Serie A", "Barcelona Messi La Liga", + "Liverpool Salah Premier League"); + } + + @Test + public void whenZippedWithIndex_thenZippedWithIndex() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool"); + Set> zipsWithIndex = StreamUtils.zipWithIndex(streamOfClubs).collect(Collectors.toSet()); + assertThat(zipsWithIndex).contains(Indexed.index(0, "Juventus"), Indexed.index(1, "Barcelona"), + Indexed.index(2, "Liverpool")); + } + + @Test + public void givenMultipleStream_whenMerged_thenMerged() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool", "PSG"); + Stream streamOfPlayers = Stream.of("Ronaldo", "Messi", "Salah"); + Stream streamOfLeagues = Stream.of("Serie A", "La Liga", "Premier League"); + + Set merged = StreamUtils.merge(() -> "", (valOne, valTwo) -> valOne + " " + valTwo, streamOfClubs, + streamOfPlayers, streamOfLeagues).collect(Collectors.toSet()); + + assertThat(merged).contains(" Juventus Ronaldo Serie A", " Barcelona Messi La Liga", " Liverpool Salah Premier League", + " PSG"); + } + + @Test + public void givenMultipleStream_whenMergedToList_thenMergedToList() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "PSG"); + Stream streamOfPlayers = Stream.of("Ronaldo", "Messi"); + + List> mergedListOfList = StreamUtils.mergeToList(streamOfClubs, streamOfPlayers) + .collect(Collectors.toList()); + assertThat(mergedListOfList.get(0)).isInstanceOf(List.class); + assertThat(mergedListOfList.get(0)).containsExactly("Juventus", "Ronaldo"); + assertThat(mergedListOfList.get(1)).containsExactly("Barcelona", "Messi"); + assertThat(mergedListOfList.get(2)).containsExactly("PSG"); + } + + @Test + public void givenMultipleStream_whenInterleaved_thenInterleaved() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool"); + Stream streamOfPlayers = Stream.of("Ronaldo", "Messi"); + Stream streamOfLeagues = Stream.of("Serie A", "La Liga"); + + AtomicInteger counter = new AtomicInteger(0); + Selector roundRobinSelector = (o) -> { + Object[] vals = (Object[]) o; + while (counter.get() >= vals.length || vals[counter.get()] == null) { + if (counter.incrementAndGet() >= vals.length) + counter.set(0); + } + return counter.getAndIncrement(); + }; + Stream interleavedStream = StreamUtils.interleave(roundRobinSelector, streamOfClubs, streamOfPlayers, + streamOfLeagues); + List interleavedList = interleavedStream.collect(Collectors.toList()); + assertThat(interleavedList).containsExactly("Juventus", "Ronaldo", "Serie A", "Barcelona", "Messi", "La Liga", + "Liverpool"); + } + + @Test + public void whenSkippedUntil_thenSkippedUntil() { + Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + List skippedUntilGreaterThan5 = StreamUtils.skipUntil(stream(numbers), i -> i > 5).collect(Collectors.toList()); + assertThat(skippedUntilGreaterThan5).containsExactly(6, 7, 8, 9, 10); + + List skippedUntilLessThanEquals5 = StreamUtils.skipUntil(stream(numbers), i -> i <= 5) + .collect(Collectors.toList()); + assertThat(skippedUntilLessThanEquals5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + + @Test + public void whenSkippedWhile_thenSkippedWhile() { + Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + List skippedWhileLessThanEquals5 = StreamUtils.skipWhile(stream(numbers), i -> i <= 5) + .collect(Collectors.toList()); + assertThat(skippedWhileLessThanEquals5).containsExactly(6, 7, 8, 9, 10); + + List skippedWhileGreaterThan5 = StreamUtils.skipWhile(stream(numbers), i -> i > 5).collect(Collectors.toList()); + assertThat(skippedWhileGreaterThan5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + + @Test + public void givenFibonacciGenerator_whenUnfolded_thenUnfolded() { + AtomicInteger lastValue = new AtomicInteger(0); + Function> fibonacciGenerator = (i) -> (i < 10) ? + Optional.of(i + lastValue.getAndSet(i)) : + Optional.empty(); + + List fib = StreamUtils.unfold(1, fibonacciGenerator).collect(Collectors.toList()); + assertThat(fib).containsExactly(1, 1, 2, 3, 5, 8, 13); + } + + @Test + public void whenWindowed_thenWindowed() { + Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7 }; + + List> windowedWithSkip1 = StreamUtils.windowed(stream(numbers), 3, 1).collect(Collectors.toList()); + assertThat(windowedWithSkip1).containsExactly(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5, 6), + asList(5, 6, 7)); + + List> windowedWithSkip2 = StreamUtils.windowed(stream(numbers), 3, 2).collect(Collectors.toList()); + assertThat(windowedWithSkip2).containsExactly(asList(1, 2, 3), asList(3, 4, 5), asList(5, 6, 7)); + } + + @Test + public void whenAggregated_thenAggregated() { + Integer[] numbers = { 1, 2, 2, 3, 4, 4, 4, 5 }; + List> aggregated = StreamUtils.aggregate(stream(numbers), (int1, int2) -> int1.compareTo(int2) == 0) + .collect(Collectors.toList()); + assertThat(aggregated).containsExactly(asList(1), asList(2, 2), asList(3), asList(4, 4, 4), asList(5)); + + List> aggregatedFixSize = StreamUtils.aggregate(stream(numbers), 5).collect(Collectors.toList()); + assertThat(aggregatedFixSize).containsExactly(asList(1, 2, 2, 3, 4), asList(4, 4, 5)); + } + + @Test + public void whenGroupedRun_thenGroupedRun() { + Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 }; + List> grouped = StreamUtils.groupRuns(stream(numbers)).collect(Collectors.toList()); + assertThat(grouped).containsExactly(asList(1, 1), asList(2), asList(3), asList(4, 4), asList(5)); + + Integer[] numbers2 = { 1, 2, 3, 1 }; + List> grouped2 = StreamUtils.groupRuns(stream(numbers2)).collect(Collectors.toList()); + assertThat(grouped2).containsExactly(asList(1), asList(2), asList(3), asList(1)); + } + + @Test + public void whenAggregatedOnListCondition_thenAggregatedOnListCondition() { + Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 }; + Stream> aggregated = StreamUtils.aggregateOnListCondition(stream(numbers), + (currentList, nextInt) -> currentList.stream().mapToInt(Integer::intValue).sum() + nextInt <= 5); + assertThat(aggregated).containsExactly(asList(1, 1, 2), asList(3), asList(4), asList(4), asList(5)); + } + + @Test + public void givenProjectionFunction_whenMaxedBy_thenMaxedBy() { + Stream clubs = Stream.of("Juventus", "Barcelona", "PSG"); + Optional longestName = clubs.collect(CollectorUtils.maxBy(String::length)); + assertThat(longestName.get()).isEqualTo("Barcelona"); + } + + @Test + public void givenStreamOfMultipleElem_whenUniqueCollector_thenValueReturned() { + Stream singleElement = Stream.of(1); + Optional unique = singleElement.collect(CollectorUtils.unique()); + assertThat(unique.get()).isEqualTo(1); + + } + + @Test + public void givenStreamOfMultipleElem_whenUniqueCollector_thenExceptionThrown() { + Stream multipleElement = Stream.of(1, 2, 3); + assertThatExceptionOfType(NonUniqueValueException.class).isThrownBy(() -> { + multipleElement.collect(CollectorUtils.unique()); + }); + } + +} diff --git a/java-strings/pom.xml b/java-strings/pom.xml index 2afe18f07a..b1ba49b33a 100644 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -47,11 +47,21 @@ jmh-core ${jmh-core.version} + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-core.version} + com.ibm.icu icu4j ${icu4j.version} + + com.google.guava + guava + ${guava.version} + com.vdurmont @@ -92,6 +102,7 @@ 3.6.1 1.19 61.1 + 26.0-jre \ No newline at end of file diff --git a/java-strings/src/main/java/com/baeldung/string/StringPerformance.java b/java-strings/src/main/java/com/baeldung/string/StringPerformance.java new file mode 100644 index 0000000000..4873bd320c --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/StringPerformance.java @@ -0,0 +1,163 @@ +package com.baeldung.string; + +import org.apache.commons.lang3.StringUtils; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Measurement(batchSize = 10000, iterations = 10) +@Warmup(batchSize = 10000, iterations = 10) +public class StringPerformance extends StringPerformanceHints { + + @Benchmark + public String benchmarkStringDynamicConcat() { + return dynamicConcat(); + } + + @Benchmark + public StringBuilder benchmarkStringBuilder() { + StringBuilder stringBuilder = new StringBuilder(result); + stringBuilder.append(baeldung); + return stringBuilder; + } + + @Benchmark + public StringBuffer benchmarkStringBuffer() { + StringBuffer stringBuffer = new StringBuffer(result); + stringBuffer.append(baeldung); + return stringBuffer; + } + + @Benchmark + public String benchmarkStringConstructor() { + return stringConstructor(); + } + + @Benchmark + public String benchmarkStringLiteral() { + return stringLiteral(); + } + + @Benchmark + public String benchmarkStringFormat_s() { + return stringFormat_s(); + } + + @Benchmark + public String benchmarkStringConcat() { + return stringConcat(); + } + + @Benchmark + public String benchmarkStringIntern() { + return stringIntern(); + } + + @Benchmark + public String benchmarkStringReplace() { + return longString.replace("average", " average !!!"); + } + + @Benchmark + public String benchmarkStringUtilsReplace() { + return StringUtils.replace(longString, "average", " average !!!"); + } + + @Benchmark + public List benchmarkGuavaSplitter() { + return guavaSplitter(); + } + + @Benchmark + public String [] benchmarkStringSplit() { + return stringSplit(); + } + + @Benchmark + public String [] benchmarkStringSplitPattern() { + return stringSplitPattern(); + } + + @Benchmark + public List benchmarkStringTokenizer() { + return stringTokenizer(); + } + + @Benchmark + public List benchmarkStringIndexOf() { + return stringIndexOf(); + } + + + @Benchmark + public String benchmarkIntegerToString() { + return stringIntegerToString(); + } + + @Benchmark + public String benchmarkStringValueOf() { + return stringValueOf(); + } + + + @Benchmark + public String benchmarkStringConvertPlus() { + return stringConvertPlus(); + } + + @Benchmark + public String benchmarkStringFormat_d() { + return stringFormat_d(); + } + + @Benchmark + public boolean benchmarkStringEquals() { + return stringEquals(); + } + + + @Benchmark + public boolean benchmarkStringEqualsIgnoreCase() { + return stringEqualsIgnoreCase(); + } + + @Benchmark + public boolean benchmarkStringMatches() { + return stringIsMatch(); + } + + @Benchmark + public boolean benchmarkPrecompiledMatches() { + return precompiledMatches(); + } + + @Benchmark + public int benchmarkStringCompareTo() { + return stringCompareTo(); + } + + @Benchmark + public boolean benchmarkStringIsEmpty() { + return stringIsEmpty(); + } + + @Benchmark + public boolean benchmarkStringLengthZero() { + return stringLengthZero(); + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(StringPerformance.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/StringPerformanceHints.java b/java-strings/src/main/java/com/baeldung/string/StringPerformanceHints.java new file mode 100644 index 0000000000..509222136f --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/StringPerformanceHints.java @@ -0,0 +1,133 @@ +package com.baeldung.string; + +import com.google.common.base.Splitter; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.regex.Pattern; + +@State(Scope.Thread) +public class StringPerformanceHints { + + protected String baeldung = "baeldung"; + protected String longString = "Hello baeldung, I am a bit longer than other Strings"; + protected String formatString = "hello %s, nice to meet you"; + protected String formatDigit = "%d"; + protected String emptyString = " "; + protected String result = ""; + + protected int sampleNumber = 100; + + protected Pattern spacePattern = Pattern.compile(emptyString); + protected Pattern longPattern = Pattern.compile(longString); + protected List stringSplit = new ArrayList<>(); + protected List stringTokenizer = new ArrayList<>(); + + protected String dynamicConcat() { + result += baeldung; + return result; + } + + protected String stringConstructor() { + return new String(baeldung); + } + + protected String stringLiteral() { + result = baeldung; + return result; + } + + protected String stringFormat_s() { + return String.format(formatString, baeldung); + } + + protected String stringFormat_d() { + return String.format(formatDigit, sampleNumber); + } + + protected String stringConcat() { + result = result.concat(baeldung); + return result; + } + + protected List stringTokenizer() { + StringTokenizer st = new StringTokenizer(longString); + while (st.hasMoreTokens()) { + stringTokenizer.add(st.nextToken()); + } + return stringTokenizer; + } + + protected List stringIndexOf() { + int pos = 0, end; + while ((end = longString.indexOf(' ', pos)) >= 0) { + stringSplit.add(longString.substring(pos, end)); + pos = end + 1; + } + return stringSplit; + } + + protected String stringIntegerToString() { + return Integer.toString(sampleNumber); + } + + protected String stringValueOf() { + return String.valueOf(sampleNumber); + } + + + protected String stringConvertPlus() { + return sampleNumber + ""; + } + + + protected boolean stringEquals() { + return longString.equals(baeldung); + } + + + protected boolean stringEqualsIgnoreCase() { + return longString.equalsIgnoreCase(baeldung); + } + + protected boolean stringIsMatch() { + return longString.matches(baeldung); + } + + protected boolean precompiledMatches() { + return longPattern.matcher(baeldung).matches(); + } + + protected int stringCompareTo() { + return longString.compareTo(baeldung); + } + + protected boolean stringIsEmpty() { + return longString.isEmpty(); + } + + protected boolean stringLengthZero() { + return longString.length() == 0; + } + + protected String [] stringSplitPattern() { + return spacePattern.split(longString, 0); + } + + protected String [] stringSplit() { + return longString.split(emptyString); + } + + protected List guavaSplitter() { + return Splitter.on(" ").trimResults() + .omitEmptyStrings() + .splitToList(longString); + } + + protected String stringIntern() { + return baeldung.intern(); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java new file mode 100644 index 0000000000..17b13f89de --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.string; + +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; +import static org.hamcrest.text.IsEmptyString.isEmptyString; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.lang3.StringUtils; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import com.google.common.base.Strings; + +public class StringEmptyUnitTest { + + private String text = "baeldung"; + + @Test + public void givenAString_whenCheckedForEmptyUsingJunit_shouldAssertSuccessfully() { + assertTrue(!text.isEmpty()); + assertFalse(text.isEmpty()); + assertNotEquals("", text); + assertNotSame("", text); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingHamcrest_shouldAssertSuccessfully() { + assertThat(text, not(isEmptyString())); + assertThat(text, not(isEmptyOrNullString())); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingCommonsLang_shouldAssertSuccessfully() { + assertTrue(StringUtils.isNotBlank(text)); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingAssertJ_shouldAssertSuccessfully() { + Assertions.assertThat(text).isNotEmpty(); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingGuava_shouldAssertSuccessfully() { + assertFalse(Strings.isNullOrEmpty(text)); + } + +} diff --git a/libraries-security/.gitignore b/libraries-security/.gitignore new file mode 100644 index 0000000000..71881ad3ca --- /dev/null +++ b/libraries-security/.gitignore @@ -0,0 +1,14 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear +/bin/ diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml new file mode 100644 index 0000000000..a57f029702 --- /dev/null +++ b/libraries-security/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + libraries-security + libraries-security + jar + + + com.baeldung + parent-boot-1 + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.security.oauth + spring-security-oauth2 + 2.3.3.RELEASE + + + + com.github.scribejava + scribejava-apis + ${scribejava.version} + + + + junit + junit + ${junit.version} + test + + + + + + 4.12 + 2.0.4.RELEASE + 5.6.0 + + + + diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java new file mode 100644 index 0000000000..bb86c497b0 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.scribejava; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +public class ScribejavaApplication { + + public static void main(String[] args) { + SpringApplication.run(ScribejavaApplication.class, args); + } + + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java new file mode 100644 index 0000000000..cf073d3035 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java @@ -0,0 +1,27 @@ +package com.baeldung.scribejava.api; + +import com.github.scribejava.core.builder.api.DefaultApi20; + +public class MyApi extends DefaultApi20 { + + private MyApi() { + } + + private static class InstanceHolder { + private static final MyApi INSTANCE = new MyApi(); + } + + public static MyApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "http://localhost:8080/oauth/token"; + } + + @Override + protected String getAuthorizationBaseUrl() { + return null; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java new file mode 100644 index 0000000000..ffe4f0cc8a --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java @@ -0,0 +1,49 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.GoogleService; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; + +@RestController +public class GoogleController { + + @Autowired + private GoogleService service; + + + @GetMapping(value ="/me/google") + public void me(HttpServletResponse response){ + String auth = service.getService().getAuthorizationUrl(); + + response.setHeader("Location", auth); + response.setStatus(302); + + } + + @GetMapping(value = "/auth/google") + public String google(@RequestParam String code, HttpServletResponse servletResponse){ + + try { + OAuth2AccessToken token = service.getService().getAccessToken(code); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"); + service.getService().signRequest(token, request); + Response response = service.getService().execute(request); + return response.getBody(); + + }catch (Exception e){ + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java new file mode 100644 index 0000000000..bfcd6d960c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java @@ -0,0 +1,57 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.TwitterService; +import com.github.scribejava.core.model.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Scanner; +import java.util.concurrent.ExecutionException; + +@RestController +public class TwitterController { + + @Autowired + private TwitterService service; + + + @GetMapping(value ="/me/twitter") + public String me(HttpServletResponse servletResponse){ + try { + OAuth1RequestToken requestToken = service.getService().getRequestToken(); + + String auth = service.getService().getAuthorizationUrl(requestToken); + + Runtime runtime = Runtime.getRuntime(); + try { + runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth); + } catch (IOException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return null; + } + + System.out.println("Insert twitter code:"); + Scanner in = new Scanner(System.in); + + String oauthverifier = in.nextLine(); + + final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json"); + service.getService().signRequest(accessToken, request); + Response response = service.getService().execute(request); + return response.getBody(); + + } catch (IOException | InterruptedException | ExecutionException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + } + + + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java new file mode 100644 index 0000000000..68a11250de --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java @@ -0,0 +1,46 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.MyService; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.security.Principal; + +@RestController(value = "/user") +public class UserController { + + @Autowired + private MyService service; + + @GetMapping("/me/myapi") + public String me(@RequestParam String username, @RequestParam String password, HttpServletResponse responsehttp) { + + try { + OAuth2AccessToken token = service.getService().getAccessTokenPasswordGrant(username, password); + + OAuthRequest request = new OAuthRequest(Verb.GET, "http://localhost:8080/me"); + service.getService().signRequest(token, request); + Response response = service.getService().execute(request); + + return response.getBody(); + + } catch (Exception e) { + responsehttp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + + } + + @GetMapping("/me") + public Principal user(Principal principal) { + return principal; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java new file mode 100644 index 0000000000..2c7162399b --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java @@ -0,0 +1,45 @@ +package com.baeldung.scribejava.oauth; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; + + +@Configuration +@EnableAuthorizationServer +public class AuthServiceConfig extends AuthorizationServerConfigurerAdapter { + + @Autowired + @Qualifier("authenticationManagerBean") + private AuthenticationManager authenticationManager; + + @Override + public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { + oauthServer.tokenKeyAccess("permitAll()") + .checkTokenAccess("isAuthenticated()"); + } + + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + clients.inMemory() + .withClient("baeldung_api_key") + .secret("baeldung_api_secret") + .authorizedGrantTypes("password","refresh_token") + .scopes("read","write").autoApprove(true); + } + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { + endpoints + .authenticationManager(authenticationManager) + .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java new file mode 100644 index 0000000000..7aa51400ea --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.scribejava.oauth; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; + +@Configuration +@EnableResourceServer +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .headers().frameOptions().disable() + .and() + .csrf().disable(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("baeldung") + .password("scribejava") + .roles("USER"); + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + + @EnableResourceServer + @Configuration + public class ResourceServerConfig extends ResourceServerConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/user/me").authenticated() + .and() + .csrf().disable(); + } + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java new file mode 100644 index 0000000000..fbcc39763c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java @@ -0,0 +1,31 @@ +package com.baeldung.scribejava.service; + +import com.github.scribejava.apis.GoogleApi20; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +@Component +public class GoogleService { + + private OAuth20Service service; + private final String API_KEY = "api_key"; + private final String API_SECRET = "api_secret"; + private final String SCOPE = "https://www.googleapis.com/auth/userinfo.email"; + private final String CALLBACK = "http://localhost:8080/auth/google"; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .scope(SCOPE) + .callback(CALLBACK) + .build(GoogleApi20.instance()); + } + + + public OAuth20Service getService() { + return service; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java new file mode 100644 index 0000000000..739c82172c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java @@ -0,0 +1,29 @@ +package com.baeldung.scribejava.service; + +import com.baeldung.scribejava.api.MyApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class MyService { + + private OAuth20Service service; + private final String API_KEY = "baeldung_api_key"; + private final String API_SECRET = "baeldung_api_secret"; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .scope("read write") + .build(MyApi.instance()); + } + + + public OAuth20Service getService() { + return service; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java new file mode 100644 index 0000000000..df49f74679 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java @@ -0,0 +1,29 @@ +package com.baeldung.scribejava.service; + +import com.github.scribejava.apis.TwitterApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth10aService; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class TwitterService { + + private final String API_KEY = "api_key"; + private final String API_SECRET = "api_secret"; + private OAuth10aService service; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .build(TwitterApi.instance()); + } + + public OAuth10aService getService(){ + return service; + } + + +} diff --git a/libraries-security/src/main/resources/application.properties b/libraries-security/src/main/resources/application.properties new file mode 100644 index 0000000000..71c6176533 --- /dev/null +++ b/libraries-security/src/main/resources/application.properties @@ -0,0 +1 @@ +security.oauth2.resource.filter-order = 3 \ No newline at end of file diff --git a/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java new file mode 100644 index 0000000000..6565a5b085 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.scribejava; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ScribejavaUnitTest { + + @Test + public void contextLoad(){ + + } + +} diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java b/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java new file mode 100644 index 0000000000..15488bbaf4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java @@ -0,0 +1,56 @@ +package com.baeldung.kafka; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.KafkaException; + +import java.util.Properties; +import java.util.stream.Stream; + +import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.TRANSACTIONAL_ID_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG; + +public class TransactionalMessageProducer { + + private static final String DATA_MESSAGE_1 = "Put any space separated data here for count"; + private static final String DATA_MESSAGE_2 = "Output will contain count of every word in the message"; + + public static void main(String[] args) { + + KafkaProducer producer = createKafkaProducer(); + + producer.initTransactions(); + + try{ + + producer.beginTransaction(); + + Stream.of(DATA_MESSAGE_1, DATA_MESSAGE_2).forEach(s -> producer.send( + new ProducerRecord("input", null, s))); + + producer.commitTransaction(); + + }catch (KafkaException e){ + + producer.abortTransaction(); + + } + + } + + private static KafkaProducer createKafkaProducer() { + + Properties props = new Properties(); + props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ENABLE_IDEMPOTENCE_CONFIG, "true"); + props.put(TRANSACTIONAL_ID_CONFIG, "prod-0"); + props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + + return new KafkaProducer(props); + + } +} diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalApp.java b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java similarity index 66% rename from libraries/src/main/java/com/baeldung/kafka/TransactionalApp.java rename to libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java index 1e95041a0d..0563ba6684 100644 --- a/libraries/src/main/java/com/baeldung/kafka/TransactionalApp.java +++ b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java @@ -14,6 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static java.time.Duration.ofSeconds; import static java.util.Collections.singleton; @@ -21,16 +23,16 @@ import static org.apache.kafka.clients.consumer.ConsumerConfig.*; import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG; import static org.apache.kafka.clients.producer.ProducerConfig.*; -public class TransactionalApp { +public class TransactionalWordCount { - private static final String CONSUMER_GROUP_ID = "test"; + private static final String CONSUMER_GROUP_ID = "my-group-id"; private static final String OUTPUT_TOPIC = "output"; private static final String INPUT_TOPIC = "input"; public static void main(String[] args) { - KafkaConsumer consumer = initConsumer(); - KafkaProducer producer = initProducer(); + KafkaConsumer consumer = createKafkaConsumer(); + KafkaProducer producer = createKafkaProducer(); producer.initTransactions(); @@ -38,12 +40,17 @@ public class TransactionalApp { while (true) { - ConsumerRecords records = consumer.poll(ofSeconds(20)); + ConsumerRecords records = consumer.poll(ofSeconds(60)); + + Map wordCountMap = records.records(new TopicPartition(INPUT_TOPIC, 0)) + .stream() + .flatMap(record -> Stream.of(record.value().split(" "))) + .map(word -> Tuple.of(word, 1)) + .collect(Collectors.toMap(tuple -> tuple.getKey(), t1 -> t1.getValue(), (v1, v2) -> v1 + v2)); producer.beginTransaction(); - for (ConsumerRecord record : records) - producer.send(new ProducerRecord(OUTPUT_TOPIC, record)); + wordCountMap.forEach((key, value) -> producer.send(new ProducerRecord(OUTPUT_TOPIC, key, value.toString()))); Map offsetsToCommit = new HashMap<>(); @@ -51,7 +58,7 @@ public class TransactionalApp { List> partitionedRecords = records.records(partition); long offset = partitionedRecords.get(partitionedRecords.size() - 1).offset(); - offsetsToCommit.put(partition, new OffsetAndMetadata(offset)); + offsetsToCommit.put(partition, new OffsetAndMetadata(offset + 1)); } producer.sendOffsetsToTransaction(offsetsToCommit, CONSUMER_GROUP_ID); @@ -68,11 +75,12 @@ public class TransactionalApp { } - private static KafkaConsumer initConsumer() { + private static KafkaConsumer createKafkaConsumer() { Properties props = new Properties(); props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(GROUP_ID_CONFIG, CONSUMER_GROUP_ID); props.put(ENABLE_AUTO_COMMIT_CONFIG, "false"); + props.put(ISOLATION_LEVEL_CONFIG, "read_committed"); props.put(KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put(VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); @@ -81,19 +89,14 @@ public class TransactionalApp { return consumer; } - private static KafkaProducer initProducer() { + private static KafkaProducer createKafkaProducer() { Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put(ACKS_CONFIG, "all"); - props.put(RETRIES_CONFIG, 3); - props.put(BATCH_SIZE_CONFIG, 16384); - props.put(LINGER_MS_CONFIG, 1); - props.put(BUFFER_MEMORY_CONFIG, 33554432); + props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ENABLE_IDEMPOTENCE_CONFIG, "true"); props.put(TRANSACTIONAL_ID_CONFIG, "prod-1"); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); return new KafkaProducer(props); diff --git a/libraries/src/main/java/com/baeldung/kafka/Tuple.java b/libraries/src/main/java/com/baeldung/kafka/Tuple.java new file mode 100644 index 0000000000..883de4ba21 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/Tuple.java @@ -0,0 +1,24 @@ +package com.baeldung.kafka; + +public class Tuple { + + private String key; + private Integer value; + + private Tuple(String key, Integer value) { + this.key = key; + this.value = value; + } + + public static Tuple of(String key, Integer value){ + return new Tuple(key,value); + } + + public String getKey() { + return key; + } + + public Integer getValue() { + return value; + } +} diff --git a/pom.xml b/pom.xml index 66293fe31b..4ffd9ba4a4 100644 --- a/pom.xml +++ b/pom.xml @@ -408,6 +408,7 @@ libraries libraries-data + libraries-security libraries-server linkrest logging-modules/log-mdc @@ -470,7 +471,7 @@ spring-boot-persistence spring-boot-security spring-boot-mvc - spring-boot-vue + spring-boot-vue spring-boot-logging-log4j2 spring-cloud-data-flow spring-cloud @@ -606,7 +607,7 @@ jta java-websocket - + activejdbc apache-bval @@ -634,7 +635,7 @@ spring-boot-autoconfiguration spring-boot-custom-starter - + spring-boot-jasypt spring-data-rest-querydsl @@ -651,11 +652,11 @@ stripe - + Twitter4J wicket xstream cas/cas-secured-app - + cas/cas-server @@ -674,7 +675,7 @@ spring-boot-custom-starter/greeter spring-boot-h2/spring-boot-h2-database - spring-boot-h2/spring-boot-h2-remote-app + @@ -991,7 +992,7 @@ spring-boot-custom-starter/greeter spring-boot-h2/spring-boot-h2-database - spring-boot-h2/spring-boot-h2-remote-app + diff --git a/spring-4/pom.xml b/spring-4/pom.xml index cf10f64aa2..78939bba95 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -71,10 +71,8 @@ - UTF-8 1.0.1 1.16.18 - 1.8 1.4.197 diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java index 8d7860ccdc..76b697c1aa 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java @@ -39,7 +39,7 @@ public class EmployeeFunctionalConfig { } @Bean - RouterFunction updateEmployee() { + RouterFunction updateEmployeeRoute() { return route(POST("/employees/update"), req -> req.body(toMono(Employee.class)) .doOnNext(employeeRepository()::updateEmployee) diff --git a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java index 1197820066..6e73e8072c 100644 --- a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java @@ -1,13 +1,37 @@ package com.baeldung.reactive.functional; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class EmployeeSpringFunctionalIntegrationTest { - private static EmployeeFunctionalConfig config = new EmployeeFunctionalConfig(); + @Autowired + private EmployeeFunctionalConfig config; + + @MockBean + private EmployeeRepository employeeRepository; @Test public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { @@ -15,7 +39,9 @@ public class EmployeeSpringFunctionalIntegrationTest { .bindToRouterFunction(config.getEmployeeByIdRoute()) .build(); - Employee expected = new Employee("1", "Employee 1"); + Employee employee = new Employee("1", "Employee 1"); + + given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); client.get() .uri("/employees/1") @@ -23,6 +49,50 @@ public class EmployeeSpringFunctionalIntegrationTest { .expectStatus() .isOk() .expectBody(Employee.class) - .isEqualTo(expected); + .isEqualTo(employee); + } + + @Test + public void whenGetAllEmployees_thenCorrectEmployees() { + WebTestClient client = WebTestClient + .bindToRouterFunction(config.getAllEmployeesRoute()) + .build(); + + List employeeList = new ArrayList<>(); + + Employee employee1 = new Employee("1", "Employee 1"); + Employee employee2 = new Employee("2", "Employee 2"); + + employeeList.add(employee1); + employeeList.add(employee2); + + Flux employeeFlux = Flux.fromIterable(employeeList); + given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); + + client.get() + .uri("/employees") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Employee.class) + .isEqualTo(employeeList); + } + + @Test + public void whenUpdateEmployee_thenEmployeeUpdated() { + WebTestClient client = WebTestClient + .bindToRouterFunction(config.updateEmployeeRoute()) + .build(); + + Employee employee = new Employee("1", "Employee 1 Updated"); + + client.post() + .uri("/employees/update") + .body(Mono.just(employee), Employee.class) + .exchange() + .expectStatus() + .isOk(); + + verify(employeeRepository).updateEmployee(employee); } } diff --git a/spring-boot-h2/spring-boot-h2-database/pom.xml b/spring-boot-h2/spring-boot-h2-database/pom.xml index 4b660334da..94f2293c34 100644 --- a/spring-boot-h2/spring-boot-h2-database/pom.xml +++ b/spring-boot-h2/spring-boot-h2-database/pom.xml @@ -22,6 +22,8 @@ UTF-8 UTF-8 1.8 + + com.mycorp.starter.HelloWorldApplication diff --git a/spring-boot-h2/spring-boot-h2-remote-app/src/main/java/com/baeldung/h2db/demo/ClientSpringBootApp.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java similarity index 85% rename from spring-boot-h2/spring-boot-h2-remote-app/src/main/java/com/baeldung/h2db/demo/ClientSpringBootApp.java rename to spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java index 39e52afd2c..7402312e1c 100644 --- a/spring-boot-h2/spring-boot-h2-remote-app/src/main/java/com/baeldung/h2db/demo/ClientSpringBootApp.java +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java @@ -1,4 +1,4 @@ -package com.baeldung.h2db.demo; +package com.baeldung.h2db.demo.client; import java.sql.ResultSet; import java.sql.SQLException; @@ -7,16 +7,20 @@ import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; @SpringBootApplication +@ComponentScan("com.baeldung.h2db.demo.client") public class ClientSpringBootApp { @Autowired private JdbcTemplate jdbcTemplate; public static void main(String[] args) { + System.setProperty("spring.datasource.url","jdbc:h2:tcp://localhost:9091/mem:mydb"); SpringApplication.run(ClientSpringBootApp.class, args); } @@ -46,4 +50,4 @@ public class ClientSpringBootApp { } }); } -} \ No newline at end of file +} diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/SpringBootApp.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java similarity index 88% rename from spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/SpringBootApp.java rename to spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java index 1fe080ec22..e75b42a934 100644 --- a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/SpringBootApp.java +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java @@ -1,4 +1,4 @@ -package com.baeldung.h2db.demo; +package com.baeldung.h2db.demo.server; import java.sql.ResultSet; import java.sql.SQLException; @@ -9,10 +9,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; @SpringBootApplication +@ComponentScan("com.baeldung.h2db.demo.server") public class SpringBootApp { @Autowired @@ -24,8 +26,7 @@ public class SpringBootApp { @PostConstruct private void initDb() { - System.out.println(String.format( - "****** Creating table: %s, and Inserting test data ******", "Employees")); + System.out.println(String.format("****** Creating table: %s, and Inserting test data ******", "Employees")); String sqlStatements[] = { "drop table employees if exists", @@ -57,4 +58,4 @@ public class SpringBootApp { public Server inMemoryH2DatabaseServer() throws SQLException { return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9091"); } -} \ No newline at end of file +} diff --git a/spring-boot-h2/spring-boot-h2-remote-app/.gitignore b/spring-boot-h2/spring-boot-h2-remote-app/.gitignore deleted file mode 100644 index 82eca336e3..0000000000 --- a/spring-boot-h2/spring-boot-h2-remote-app/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/build/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-remote-app/pom.xml b/spring-boot-h2/spring-boot-h2-remote-app/pom.xml deleted file mode 100644 index 8eb59d2098..0000000000 --- a/spring-boot-h2/spring-boot-h2-remote-app/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - 4.0.0 - - com.baeldung.h2db - spring-boot-h2-remote-app - 0.0.1-SNAPSHOT - jar - - Demo Spring Boot applications that access H2 in memory database created - in another Spring Boot application - - - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - com.h2database - h2 - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - diff --git a/spring-boot-h2/spring-boot-h2-remote-app/src/main/resources/application.properties b/spring-boot-h2/spring-boot-h2-remote-app/src/main/resources/application.properties deleted file mode 100644 index 6c3446f03a..0000000000 --- a/spring-boot-h2/spring-boot-h2-remote-app/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -spring.datasource.url=jdbc:h2:tcp://localhost:9091/mem:mydb -spring.datasource.driverClassName=org.h2.Driver -spring.datasource.username=sa -spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/spring-boot-jasypt/pom.xml b/spring-boot-jasypt/pom.xml index 212f524da6..de0df92678 100644 --- a/spring-boot-jasypt/pom.xml +++ b/spring-boot-jasypt/pom.xml @@ -5,7 +5,6 @@ com.example.jasypt spring-boot-jasypt - 0.0.1-SNAPSHOT jar spring-boot-jasypt Demo project for Spring Boot @@ -52,9 +51,6 @@ - UTF-8 - UTF-8 - 1.8 2.0.0 diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java similarity index 94% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java rename to spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java index 58c2dc7bb2..c24cfe6efa 100644 --- a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.jasypt.Main; @RunWith(SpringRunner.class) @SpringBootTest(classes = {Main.class}) -public class CustomJasyptTest { +public class CustomJasyptIntegrationTest { @Autowired ApplicationContext appCtx; diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java similarity index 95% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java rename to spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java index f9b66b5044..e8dda73b4a 100644 --- a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java @@ -13,7 +13,7 @@ import com.baeldung.jasypt.simple.PropertyServiceForJasyptSimple; @RunWith(SpringRunner.class) @SpringBootTest -public class JasyptSimpleTest { +public class JasyptSimpleIntegrationTest { @Autowired ApplicationContext appCtx; diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java similarity index 95% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java rename to spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java index d246c21036..5f5d409ab9 100644 --- a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.jasypt.starter.PropertyServiceForJasyptStarter; @RunWith(SpringRunner.class) @SpringBootTest -public class JasyptWithStarterTest { +public class JasyptWithStarterIntegrationTest { @Autowired ApplicationContext appCtx; diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml index c4f9b12676..c3bad74352 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml @@ -1,15 +1,13 @@ 4.0.0 - com.baeldung - 0.0.1-SNAPSHOT disabling-console-jul - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - + + com.baeldung + disabling-console-logging + 0.0.1-SNAPSHOT + @@ -45,9 +43,4 @@ - - UTF-8 - UTF-8 - 1.8 - \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml index 97d10c574a..f9b34ec7d9 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml @@ -1,49 +1,42 @@ - 4.0.0 - com.baeldung - 0.0.1-SNAPSHOT - disabling-console-log4j2 - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + disabling-console-log4j2 - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-log4j2 - - + + com.baeldung + disabling-console-logging + 0.0.1-SNAPSHOT + - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + - - UTF-8 - UTF-8 - 1.8 - + + + + org.springframework.boot + spring-boot-maven-plugin + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/pom.xml index bc248e49b2..39a4a40f12 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/pom.xml +++ b/spring-boot-logging-log4j2/disabling-console-logging/pom.xml @@ -1,8 +1,6 @@ 4.0.0 - 0.0.1-SNAPSHOT - com.baeldung disabling-console-logging pom Projects for Disabling Spring Boot Console Logging tutorials diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index ee4d07c3e8..7caf1e8690 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-boot-logging-log4j2 - 0.0.1-SNAPSHOT pom Projects for Spring Boot Logging tutorials @@ -43,10 +41,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml index 1d4c8867fb..571794167e 100644 --- a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml +++ b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-boot-logging-log4j2-app - 0.0.1-SNAPSHOT jar Demo project for Spring Boot Logging with Log4J2 diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index 9ca187db5d..06712e4791 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - com.baeldung spring-boot-mvc - 0.0.1-SNAPSHOT jar spring-boot-mvc - Demo project for Spring Boot + Module For Spring Boot MVC parent-boot-2 @@ -21,6 +19,32 @@ org.springframework.boot spring-boot-starter-web + + + com.sun.faces + jsf-api + 2.2.9 + + + org.apache.tomcat.embed + tomcat-embed-jasper + + + javax.faces + javax.faces-api + 2.1 + + + javax.servlet + jstl + 1.2 + + + com.sun.faces + jsf-impl + 2.2.8-02 + + org.springframework.boot @@ -55,9 +79,6 @@ - UTF-8 - UTF-8 - 1.8 1.10.0 com.baeldung.springbootmvc.SpringBootMvcApplication diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanA.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java similarity index 73% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanA.java rename to spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java index 21d7007917..030216b747 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanA.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java @@ -1,4 +1,4 @@ -package com.baeldung.springbootmvc.nosuchbeandefinitionexception; +package com.baeldung.nosuchbeandefinitionexception; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java new file mode 100644 index 0000000000..f0cc263504 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.nosuchbeandefinitionexception; + +public class BeanB { + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java similarity index 82% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java rename to spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java index 01d19437c5..8709cf85ac 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java @@ -1,4 +1,4 @@ -package com.baeldung.springbootmvc.nosuchbeandefinitionexception; +package com.baeldung.nosuchbeandefinitionexception; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java new file mode 100644 index 0000000000..5b4250d5e3 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java @@ -0,0 +1,31 @@ +package com.baeldung.springbootmvc.jsfapplication; + +import javax.faces.webapp.FacesServlet; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +import com.baeldung.springbootmvc.jsfapplication.controller.JsfController; +import com.baeldung.springbootmvc.jsfapplication.model.TodoDao; +import com.baeldung.springbootmvc.jsfapplication.service.TodoService; + +@SpringBootApplication +@ComponentScan(basePackageClasses = { JsfController.class, TodoDao.class, TodoService.class }) +public class JsfApplication extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(JsfApplication.class, args); + } + + @Bean + public ServletRegistrationBean servletRegistrationBean() { + FacesServlet servlet = new FacesServlet(); + ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.jsf"); + return servletRegistrationBean; + } + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java new file mode 100644 index 0000000000..a9d21175c7 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java @@ -0,0 +1,19 @@ +package com.baeldung.springbootmvc.jsfapplication.controller; + +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Scope(value = "session") +@Component(value = "jsfController") +public class JsfController { + + public String loadTodoPage() { + checkPermission(); + return "/todo.xhtml"; + } + + private void checkPermission() { + // Details omitted + } + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java new file mode 100644 index 0000000000..0b97c5a78e --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java @@ -0,0 +1,17 @@ +package com.baeldung.springbootmvc.jsfapplication.model; + +import java.util.Collection; +import java.util.Optional; + +public interface Dao { + + Optional get(int id); + + Collection getAll(); + + int save(T t); + + void update(T t); + + void delete(T t); +} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java new file mode 100644 index 0000000000..7aa8480f43 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java @@ -0,0 +1,32 @@ +package com.baeldung.springbootmvc.jsfapplication.model; + +public class Todo { + + private int id; + private String message; + private int priority; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java new file mode 100644 index 0000000000..96d44474af --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java @@ -0,0 +1,48 @@ +package com.baeldung.springbootmvc.jsfapplication.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Component; + +@Component +public class TodoDao implements Dao { + + private List todoList = new ArrayList<>(); + + @Override + public Optional get(int id) { + return Optional.ofNullable(todoList.get(id)); + } + + @Override + public Collection getAll() { + return todoList.stream() + .filter(Objects::nonNull) + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); + } + + @Override + public int save(Todo todo) { + todoList.add(todo); + int index = todoList.size() - 1; + todo.setId(index); + return index; + } + + @Override + public void update(Todo todo) { + todoList.set(todo.getId(), todo); + } + + @Override + public void delete(Todo todo) { + todoList.set(todo.getId(), null); + } + +} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java new file mode 100644 index 0000000000..89af3c66b9 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java @@ -0,0 +1,50 @@ +package com.baeldung.springbootmvc.jsfapplication.service; + +import java.util.Collection; +import java.util.Comparator; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import com.baeldung.springbootmvc.jsfapplication.model.Dao; +import com.baeldung.springbootmvc.jsfapplication.model.Todo; + +@Scope(value = "session") +@Component(value = "todoService") +public class TodoService { + + @Autowired + private Dao todoDao; + private Todo todo = new Todo(); + + public void save() { + todoDao.save(todo); + todo = new Todo(); + } + + public Collection getAllTodo() { + return todoDao.getAll(); + } + + public Collection getAllTodoSortedByPriority() { + return todoDao.getAll() + .stream() + .sorted(Comparator.comparingInt(Todo::getId)) + .collect(Collectors.toList()); + } + + public int saveTodo(Todo todo) { + validate(todo); + return todoDao.save(todo); + } + + private void validate(Todo todo) { + // Details omitted + } + + public Todo getTodo() { + return todo; + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanB.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanB.java deleted file mode 100644 index 3dd72aacc6..0000000000 --- a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/nosuchbeandefinitionexception/BeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.springbootmvc.nosuchbeandefinitionexception; - -public class BeanB { - -} diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml b/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml new file mode 100644 index 0000000000..9e31a2e09d --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml @@ -0,0 +1,9 @@ + + + + org.springframework.web.jsf.el.SpringBeanFacesELResolver + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml b/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e0cd4d8850 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + + Faces Servlet + javax.faces.webapp.FacesServlet + 1 + + + Faces Servlet + *.jsf + + + com.sun.faces.forceLoadConfiguration + true + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/index.xhtml b/spring-boot-mvc/src/main/webapp/index.xhtml new file mode 100644 index 0000000000..40042b812c --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/index.xhtml @@ -0,0 +1,20 @@ + + + + + TO-DO application + + + + Welcome in the TO-DO application! + + This is a static message rendered from xhtml. + + + + + + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/todo.xhtml b/spring-boot-mvc/src/main/webapp/todo.xhtml new file mode 100644 index 0000000000..426e101908 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/todo.xhtml @@ -0,0 +1,38 @@ + + + + + TO-DO application + + + + + List of TO-DO items + + + + Message + #{item.message} + + + Priority + #{item.priority} + + + + + + Add new to-do item: + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 376d8099ed..d0095e9a8a 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -35,6 +35,7 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault + spring-cloud-security diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml b/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml new file mode 100644 index 0000000000..3ffbf8f619 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + dynamodb-config + jar + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + com.amazonaws + aws-java-sdk-dynamodb + ${aws.sdk.dynamo.version} + + + com.github.derjust + spring-data-dynamodb + ${spring.dynamo.version} + + + com.netflix.archaius + archaius-aws + ${archaius.version} + + + org.projectlombok + lombok + provided + + + + + 1.11.407 + 5.0.3 + 0.7.6 + + diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java new file mode 100644 index 0000000000..ee08f2b1fb --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.archaius.dynamosources; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DynamoSourcesApplication { + + public static void main(String[] args) { + SpringApplication.run(DynamoSourcesApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java new file mode 100644 index 0000000000..7b533e8021 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.config; + +import java.util.Arrays; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; +import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; +import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; +import com.amazonaws.services.dynamodbv2.util.TableUtils; +import com.baeldung.spring.cloud.archaius.dynamosources.dynamodb.ArchaiusProperties; +import com.baeldung.spring.cloud.archaius.dynamosources.dynamodb.ArchaiusPropertiesRepository; +import com.netflix.config.DynamicConfiguration; +import com.netflix.config.FixedDelayPollingScheduler; +import com.netflix.config.PolledConfigurationSource; +import com.netflix.config.sources.DynamoDbConfigurationSource; + +@Configuration +public class ApplicationPropertiesConfigurations { + + @Autowired + AmazonDynamoDB amazonDynamoDb; + + @Autowired + private ArchaiusPropertiesRepository repository; + + @Bean + public AbstractConfiguration addApplicationPropertiesSource() { + // Normally, the DB Table would be already created and populated. + // In this case, we'll do it just before creating the archaius config source that uses it + initDatabase(); + PolledConfigurationSource source = new DynamoDbConfigurationSource(amazonDynamoDb); + return new DynamicConfiguration(source, new FixedDelayPollingScheduler()); + } + + private void initDatabase() { + // Create the table + DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDb); + CreateTableRequest tableRequest = mapper.generateCreateTableRequest(ArchaiusProperties.class); + tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L)); + TableUtils.createTableIfNotExists(amazonDynamoDb, tableRequest); + + // Populate the table + ArchaiusProperties property = new ArchaiusProperties("baeldung.archaius.properties.one", "one FROM:dynamoDB"); + ArchaiusProperties property3 = new ArchaiusProperties("baeldung.archaius.properties.three", "three FROM:dynamoDB"); + repository.saveAll(Arrays.asList(property, property3)); + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java new file mode 100644 index 0000000000..8f12051a7f --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.config; + +import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.amazonaws.auth.AWSCredentialsProvider; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; + +@Configuration +@EnableDynamoDBRepositories(basePackages = "com.baeldung.spring.cloud.archaius.dynamosources.dynamodb") +public class DynamoDbConfiguration { + + @Value("${amazon.dynamodb.endpoint}") + private String amazonDynamoDBEndpoint; + + @Value("${aws.accessKeyId}") + private String amazonDynamoDBAccessKeyId; + + @Value("${aws.secretKey}") + private String amazonDynamoDBSecretKey; + + @Bean + public AmazonDynamoDB amazonDynamoDB() { + AmazonDynamoDB amazonDynamoDB = AmazonDynamoDBClientBuilder.standard() + .withCredentials(amazonAWSCredentials()) + .withEndpointConfiguration(setupEndpointConfiguration()) + .build(); + + return amazonDynamoDB; + } + + private AWSCredentialsProvider amazonAWSCredentials() { + return new AWSStaticCredentialsProvider(new BasicAWSCredentials(amazonDynamoDBAccessKeyId, amazonDynamoDBSecretKey)); + } + + private EndpointConfiguration setupEndpointConfiguration() { + return new EndpointConfiguration(amazonDynamoDBEndpoint, Regions.DEFAULT_REGION.getName()); + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..2ac5055fe3 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java new file mode 100644 index 0000000000..016f8433cf --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.dynamodb; + +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +@DynamoDBTable(tableName = "archaiusProperties") +public class ArchaiusProperties { + + @DynamoDBHashKey + @DynamoDBAttribute + private String key; + + @DynamoDBAttribute + private String value; +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java new file mode 100644 index 0000000000..fbcc953261 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.dynamodb; + +import org.springframework.data.repository.CrudRepository; + +public interface ArchaiusPropertiesRepository extends CrudRepository { + +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties new file mode 100644 index 0000000000..3823d2685f --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties @@ -0,0 +1,6 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties +amazon.dynamodb.endpoint=http://localhost:8000/ +aws.accessKeyId=key +aws.secretKey=key2 diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java new file mode 100644 index 0000000000..3802cb99cd --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.cloud.archaius.dynamosources; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusDynamoDbLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:dynamoDB"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:dynamoDB"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml b/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml new file mode 100644 index 0000000000..bb283576d8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + jdbc-config + jar + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java new file mode 100644 index 0000000000..ee7beec87b --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class JdbcSourcesApplication { + + public static void main(String[] args) { + SpringApplication.run(JdbcSourcesApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java new file mode 100644 index 0000000000..f3eed0c2b5 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig.config; + +import javax.sql.DataSource; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.netflix.config.DynamicConfiguration; +import com.netflix.config.FixedDelayPollingScheduler; +import com.netflix.config.PolledConfigurationSource; +import com.netflix.config.sources.JDBCConfigurationSource; + +@Configuration +public class ApplicationPropertiesConfigurations { + + @Autowired + DataSource h2DataSource; + + @Bean + public AbstractConfiguration addApplicationPropertiesSource() { + PolledConfigurationSource source = new JDBCConfigurationSource(h2DataSource, "select distinct key, value from properties", "key", "value"); + return new DynamicConfiguration(source, new FixedDelayPollingScheduler()); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..a793f39b29 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java new file mode 100644 index 0000000000..cc2783b506 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig.jdbc; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Properties { + + @Id + private String key; + + @SuppressWarnings("unused") + private String value; +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties new file mode 100644 index 0000000000..eca873f897 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties +spring.h2.console.enabled=true diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql new file mode 100644 index 0000000000..eb80126d48 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql @@ -0,0 +1,5 @@ +insert into properties +values('baeldung.archaius.properties.one', 'one FROM:jdbc_source'); + +insert into properties +values('baeldung.archaius.properties.three', 'three FROM:jdbc_source'); \ No newline at end of file diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java new file mode 100644 index 0000000000..91d5f5754e --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusJDBCSourceLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:jdbc_source"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:jdbc_source"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/pom.xml b/spring-cloud/spring-cloud-archaius/pom.xml index cd102f86cd..fd3e34e463 100644 --- a/spring-cloud/spring-cloud-archaius/pom.xml +++ b/spring-cloud/spring-cloud-archaius/pom.xml @@ -21,6 +21,9 @@ basic-config additional-sources-simple extra-configs + jdbc-config + dynamodb-config + zookeeper-config diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml new file mode 100644 index 0000000000..8f8ec99ad8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + zookeeper-config + jar + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-zookeeper-config + ${cloud.zookeeper.version} + + + org.apache.zookeeper + zookeeper + + + + + org.apache.zookeeper + zookeeper + ${zookeeper.version} + + + org.slf4j + slf4j-log4j12 + + + + + + + 2.0.0.RELEASE + 3.4.13 + + diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java new file mode 100644 index 0000000000..12119e3e29 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ZookeeperConfigApplication { + + public static void main(String[] args) { + SpringApplication.run(ZookeeperConfigApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java new file mode 100644 index 0000000000..59ef10aaf7 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java @@ -0,0 +1,58 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig.config; + +import org.apache.curator.framework.CuratorFramework; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +/** + * + * Ideally, we wouldn't need to initialize the zookeeper config values. + * Here we do it to verify that configurations are being retrieved. + * + */ +@Component +public class ZookeeperConfigsInitializer { + + private static final String CONFIG_BASE_NODE_PATH = "/config"; + private static final String APPLICATION_BASE_NODE_PATH = CONFIG_BASE_NODE_PATH + "/application"; + + @Autowired + CuratorFramework client; + + @EventListener + public void appReady(ApplicationReadyEvent event) throws Exception { + String pathOne = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.one"; + String valueOne = "one FROM:zookeeper"; + String pathThree = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.three"; + String valueThree = "three FROM:zookeeper"; + createBaseNodes(); + setValue(pathOne, valueOne); + setValue(pathThree, valueThree); + } + + private void setValue(String path, String value) throws Exception { + if (client.checkExists() + .forPath(path) == null) { + client.create() + .forPath(path, value.getBytes()); + } else { + client.setData() + .forPath(path, value.getBytes()); + } + } + + private void createBaseNodes() throws Exception { + if (client.checkExists() + .forPath(CONFIG_BASE_NODE_PATH) == null) { + client.create() + .forPath(CONFIG_BASE_NODE_PATH); + } + if (client.checkExists() + .forPath(APPLICATION_BASE_NODE_PATH) == null) { + client.create() + .forPath(APPLICATION_BASE_NODE_PATH); + } + } +} diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..c8a5e53ee4 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java @@ -0,0 +1,51 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + @Value("${baeldung.archaius.properties.one:not found!}") + private String propertyOneWithValue; + + @Value("${baeldung.archaius.properties.two:not found!}") + private String propertyTwoWithValue; + + @Value("${baeldung.archaius.properties.three:not found!}") + private String propertyThreeWithValue; + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + return properties; + } + + @GetMapping("/properties-from-value") + public Map getPropertiesFromValue() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithValue); + properties.put("baeldung.archaius.properties.two", propertyTwoWithValue); + properties.put("baeldung.archaius.properties.three", propertyThreeWithValue); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties new file mode 100644 index 0000000000..91ad18a932 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties +spring.application.name=zookeeper-config diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java new file mode 100644 index 0000000000..ff4358cb8f --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusZookeeperLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:zookeeper"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:zookeeper"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-functions/README.MD b/spring-cloud/spring-cloud-functions/README.MD new file mode 100644 index 0000000000..c766dd1dc6 --- /dev/null +++ b/spring-cloud/spring-cloud-functions/README.MD @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Serverless Functions with Spring Cloud Function](https://www.baeldung.com/spring-cloud-function) diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml index e3c17329d0..8b2b0ad385 100644 --- a/spring-cloud/spring-cloud-functions/pom.xml +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -1,19 +1,94 @@ - + 4.0.0 - spring-cloud-functions - pom + + com.baeldung.spring + cloudfunction-aws + 0.0.1-SNAPSHOT + jar + + cloudfunction-aws + Demo project for Spring Cloud Function - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + - - spring-cloud-function-aws - - - \ No newline at end of file + + UTF-8 + UTF-8 + 1.8 + 1.0.1.RELEASE + 2.0.2 + + + + + org.springframework.cloud + spring-cloud-function-adapter-aws + ${spring-cloud-function.version} + + + + + org.springframework.cloud + spring-cloud-starter-function-web + 1.0.1.RELEASE + + + com.amazonaws + aws-lambda-java-events + ${aws-lambda-events.version} + provided + + + com.amazonaws + aws-lambda-java-core + 1.1.0 + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.springframework.boot.experimental + spring-boot-thin-layout + 1.0.10.RELEASE + + + + + org.apache.maven.plugins + maven-shade-plugin + + false + true + aws + + + + + + diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/pom.xml b/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/pom.xml deleted file mode 100644 index 8b2b0ad385..0000000000 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/pom.xml +++ /dev/null @@ -1,94 +0,0 @@ - - - 4.0.0 - - com.baeldung.spring - cloudfunction-aws - 0.0.1-SNAPSHOT - jar - - cloudfunction-aws - Demo project for Spring Cloud Function - - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - 1.0.1.RELEASE - 2.0.2 - - - - - org.springframework.cloud - spring-cloud-function-adapter-aws - ${spring-cloud-function.version} - - - - - org.springframework.cloud - spring-cloud-starter-function-web - 1.0.1.RELEASE - - - com.amazonaws - aws-lambda-java-events - ${aws-lambda-events.version} - provided - - - com.amazonaws - aws-lambda-java-core - 1.1.0 - provided - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - true - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.springframework.boot.experimental - spring-boot-thin-layout - 1.0.10.RELEASE - - - - - org.apache.maven.plugins - maven-shade-plugin - - false - true - aws - - - - - - diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/CloudFunctionAwsApplication.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java similarity index 92% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/CloudFunctionAwsApplication.java rename to spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java index cc8f11beca..34e97d3b6c 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/CloudFunctionAwsApplication.java +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloudfunction; +package com.baeldung.spring.cloudfunction.aws; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/StringReverseHandler.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java similarity index 78% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/StringReverseHandler.java rename to spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java index d103bc98d9..52514dcd12 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/StringReverseHandler.java +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloudfunction; +package com.baeldung.spring.cloudfunction.aws; import org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler; diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/functions/Greeter.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java similarity index 80% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/functions/Greeter.java rename to spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java index 124aefe56e..c443b98c18 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/java/com/baeldung/spring/cloudfunction/functions/Greeter.java +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloudfunction.functions; +package com.baeldung.spring.cloudfunction.functions.aws; import java.util.function.Function; diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/resources/application.properties b/spring-cloud/spring-cloud-functions/src/main/resources/application.properties similarity index 76% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/resources/application.properties rename to spring-cloud/spring-cloud-functions/src/main/resources/application.properties index 14426a848c..b445bfa4ed 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-functions/src/main/resources/application.properties @@ -1 +1 @@ -spring.cloud.function.scan.packages: com.baeldung.spring.cloudfunction.functions \ No newline at end of file +spring.cloud.function.scan.packages: com.baeldung.spring.cloudfunction.functions.aws \ No newline at end of file diff --git a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/test/java/com/baeldung/spring/cloudfunction/CloudFunctionApplicationTests.java b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java similarity index 96% rename from spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/test/java/com/baeldung/spring/cloudfunction/CloudFunctionApplicationTests.java rename to spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java index 01199475fb..6039debe3f 100644 --- a/spring-cloud/spring-cloud-functions/spring-cloud-function-aws/src/test/java/com/baeldung/spring/cloudfunction/CloudFunctionApplicationTests.java +++ b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloudfunction; +package com.baeldung.spring.cloudfunction.aws; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-cloud/spring-cloud-security/README.md b/spring-cloud/spring-cloud-security/README.md deleted file mode 100644 index 39af52c077..0000000000 --- a/spring-cloud/spring-cloud-security/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# README # - -This README would normally document whatever steps are necessary to get your application up and running. - -### What is this repository for? ### - -* Quick summary -* Version -* [Learn Markdown](https://bitbucket.org/tutorials/markdowndemo) - -### How do I get set up? ### - -* Summary of set up -* Configuration -* Dependencies -* Database configuration -* How to run tests -* Deployment instructions - -### Contribution guidelines ### - -* Writing tests -* Code review -* Other guidelines - -### Who do I talk to? ### - -* Repo owner or admin -* Other community or team contact \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index f2d6308374..340c276c2d 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -2,18 +2,15 @@ 4.0.0 - com.baeldung auth-client - 0.0.1-SNAPSHOT jar auth-client - Demo project for Spring Boot - + Spring Cloud Security APP Client Module + - parent-boot-1 + spring-cloud-security com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + 1.0.0-SNAPSHOT @@ -88,9 +85,6 @@ - UTF-8 - UTF-8 - 1.8 2.1.0 Dalston.SR4 diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java similarity index 87% rename from spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java rename to spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java index ca89575ee0..37cff095db 100644 --- a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java @@ -9,7 +9,7 @@ import com.baeldung.CloudSite; @RunWith(SpringRunner.class) @SpringBootTest(classes = CloudSite.class) -public class Springoath2ApplicationTests { +public class Springoath2ApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index 0115259108..09474b2a4d 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -3,21 +3,18 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung auth-resource - 0.0.1-SNAPSHOT jar auth-resource - Demo project for Spring Boot + Spring Cloud Security APP Resource Module - parent-boot-1 + spring-cloud-security com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + 1.0.0-SNAPSHOT - + org.springframework.security.oauth @@ -60,9 +57,6 @@ - UTF-8 - UTF-8 - 1.8 Edgware.RELEASE diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationTests.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationIntegrationTest.java similarity index 85% rename from spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationTests.java rename to spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationIntegrationTest.java index e0fe7006d9..3caa06ba4d 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationTests.java +++ b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class PersonserviceApplicationTests { +public class PersonserviceApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-security/auth-server/pom.xml b/spring-cloud/spring-cloud-security/auth-server/pom.xml index b4367935e3..92f92808f6 100644 --- a/spring-cloud/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-server/pom.xml @@ -2,15 +2,13 @@ 4.0.0 - com.baeldung auth-server - 0.0.1-SNAPSHOT - + Spring Cloud Security APP Server Module + - parent-boot-1 + spring-cloud-security com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-security/pom.xml b/spring-cloud/spring-cloud-security/pom.xml new file mode 100644 index 0000000000..1cf8751548 --- /dev/null +++ b/spring-cloud/spring-cloud-security/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + spring-cloud-security + pom + 1.0.0-SNAPSHOT + spring-cloud-security + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 + + + + auth-client + auth-resource + auth-server + + + diff --git a/spring-core/src/main/java/com/baeldung/definition/Config.java b/spring-core/src/main/java/com/baeldung/definition/Config.java new file mode 100644 index 0000000000..126e6259ca --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/Config.java @@ -0,0 +1,16 @@ +package com.baeldung.definition; + +import com.baeldung.definition.domain.Address; +import com.baeldung.definition.domain.Company; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackageClasses = Company.class) +public class Config { + @Bean + public Address getAddress() { + return new Address("High Street", 1000); + } +} diff --git a/spring-core/src/main/java/com/baeldung/definition/domain/Address.java b/spring-core/src/main/java/com/baeldung/definition/domain/Address.java new file mode 100644 index 0000000000..91be18398e --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/domain/Address.java @@ -0,0 +1,14 @@ +package com.baeldung.definition.domain; + +import lombok.Data; + +@Data +public class Address { + private String street; + private int number; + + public Address(String street, int number) { + this.street = street; + this.number = number; + } +} diff --git a/spring-core/src/main/java/com/baeldung/definition/domain/Company.java b/spring-core/src/main/java/com/baeldung/definition/domain/Company.java new file mode 100644 index 0000000000..eabde8afdf --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/domain/Company.java @@ -0,0 +1,14 @@ +package com.baeldung.definition.domain; + +import lombok.Data; +import org.springframework.stereotype.Component; + +@Data +@Component +public class Company { + private Address address; + + public Company(Address address) { + this.address = address; + } +} diff --git a/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java b/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java new file mode 100644 index 0000000000..0057611308 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java @@ -0,0 +1,18 @@ +package com.baeldung.definition; + +import com.baeldung.definition.domain.Company; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.Assert.assertEquals; + +public class SpringBeanIntegrationTest { + @Test + public void whenUsingIoC_thenDependenciesAreInjected() { + ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); + Company company = context.getBean("company", Company.class); + assertEquals("High Street", company.getAddress().getStreet()); + assertEquals(1000, company.getAddress().getNumber()); + } +} diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml index 9f6eb0d703..3cbbf63d94 100644 --- a/spring-rest-embedded-tomcat/pom.xml +++ b/spring-rest-embedded-tomcat/pom.xml @@ -3,7 +3,6 @@ 4.0.0 org.baeldung.embedded spring-rest-embedded-tomcat - 0.0.1-SNAPSHOT spring-rest-embedded-tomcat war @@ -61,33 +60,8 @@ - - spring-rest-embedded-tomcat - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - - 2.9.2 - 1.8 - 1.8 4.0.0 9.0.1 4.5.3 diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml index 2f7d1c8933..7a604946b6 100644 --- a/spring-rest-shell/pom.xml +++ b/spring-rest-shell/pom.xml @@ -2,9 +2,7 @@ 4.0.0 - com.baeldung spring-rest-shell - 0.0.1-SNAPSHOT jar spring-rest-shell A simple project to demonstrate Spring REST Shell features. @@ -48,10 +46,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/spring-security-mvc-socket/README.md b/spring-security-mvc-socket/README.md index 828d9a3448..3daf9199e6 100644 --- a/spring-security-mvc-socket/README.md +++ b/spring-security-mvc-socket/README.md @@ -1,3 +1,10 @@ +To build the project, run the command: mvn clean install. This will build a war file in the target folder that you can deploye on a server like Tomcat. + +Alternatively, run the project from an IDE. + +To login, use credentials from the data.sql file in src/main/resource, eg: user/password. + + ### Relevant Articles: - [Intro to Security and WebSockets](http://www.baeldung.com/spring-security-websockets) -- [Spring WebSockets: Specific User Chat](http://www.baeldung.com/spring-websocket-specific-user-chat) \ No newline at end of file +- [Spring WebSockets: Specific User Chat](https://www.baeldung.com/spring-websockets-send-message-to-user) diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index b7559753b5..ade24d8f7b 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -151,7 +151,7 @@ - + org.apache.tomcat.maven @@ -171,7 +171,6 @@ - spring-security-mvc-socket diff --git a/spring-security-openid/pom.xml b/spring-security-openid/pom.xml index a2c0b6b119..4343996e02 100644 --- a/spring-security-openid/pom.xml +++ b/spring-security-openid/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-security-openid - 0.0.1-SNAPSHOT war spring-security-openid Spring OpenID sample project diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 5bde78db7e..57ce5ddb92 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -300,7 +300,7 @@ 2.9.0 - 2.7.0 + 2.9.2 2.6 diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index d14dcc3176..8e551d850f 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-swagger-codegen 0.0.1-SNAPSHOT pom diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index 0f1cfa27ac..06a92ffae7 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -38,23 +38,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - org.apache.maven.plugins diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml index 281ed59857..0fb5cf8e75 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -1,11 +1,8 @@ 4.0.0 - - com.baeldung spring-swagger-codegen-app - 0.0.1-SNAPSHOT - + com.baeldung spring-swagger-codegen @@ -37,7 +34,6 @@ - 1.8 0.0.1-SNAPSHOT 1.5.10.RELEASE diff --git a/spring-vertx/pom.xml b/spring-vertx/pom.xml index 69a043ed01..790eeff128 100644 --- a/spring-vertx/pom.xml +++ b/spring-vertx/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-vertx - 0.0.1-SNAPSHOT jar Spring Vertx A demo project with vertx spring integration @@ -57,31 +55,10 @@ org.springframework.boot spring-boot-maven-plugin - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - UTF-8 - UTF-8 - 1.8 3.4.1 diff --git a/testing-modules/spring-context-testing/pom.xml b/testing-modules/spring-context-testing/pom.xml deleted file mode 100644 index 148192d6c5..0000000000 --- a/testing-modules/spring-context-testing/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - 4.0.0 - com.baeldung - spring-context-testing - 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-starter - ${spring.boot.starter.version} - - - org.springframework.boot - spring-boot-starter-test - test - ${spring.boot.starter.version} - - - - - 2.0.4.RELEASE - - diff --git a/testing-modules/spring-context-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java b/testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java similarity index 100% rename from testing-modules/spring-context-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java rename to testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java diff --git a/testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java similarity index 100% rename from testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java diff --git a/testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java similarity index 100% rename from testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java diff --git a/testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java similarity index 100% rename from testing-modules/spring-context-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java diff --git a/testing-modules/spring-context-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties b/testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties similarity index 100% rename from testing-modules/spring-context-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties rename to testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties diff --git a/testing-modules/spring-context-testing/src/test/resources/other-location.properties b/testing-modules/spring-testing/src/test/resources/other-location.properties similarity index 100% rename from testing-modules/spring-context-testing/src/test/resources/other-location.properties rename to testing-modules/spring-testing/src/test/resources/other-location.properties diff --git a/twilio/pom.xml b/twilio/pom.xml index 8683192b5c..610cc04b60 100644 --- a/twilio/pom.xml +++ b/twilio/pom.xml @@ -2,11 +2,15 @@ 4.0.0 - - com.baeldung twilio 1.0-SNAPSHOT + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + com.twilio.sdk @@ -15,9 +19,4 @@ - - 1.8 - 1.8 - -
Welcome in the TO-DO application!
+ This is a static message rendered from xhtml. + + + +