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/README.md b/algorithms/README.md index 47ddd7028a..9b3bbcdee5 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -24,3 +24,7 @@ - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) - [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element) - [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation) +- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap) +- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points) +- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) +- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters) 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/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java b/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java new file mode 100644 index 0000000000..0deb48b6a0 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java @@ -0,0 +1,50 @@ +package com.baeldung.algorithms.mergesort; + +public class MergeSort { + + public static void main(String[] args) { + int[] a = { 5, 1, 6, 2, 3, 4 }; + mergeSort(a, a.length); + for (int i = 0; i < a.length; i++) + System.out.println(a[i]); + } + + public static void mergeSort(int[] a, int n) { + if (n < 2) + return; + int mid = n / 2; + int[] l = new int[mid]; + int[] r = new int[n - mid]; + + for (int i = 0; i < mid; i++) { + l[i] = a[i]; + } + for (int i = mid; i < n; i++) { + r[i - mid] = a[i]; + } + mergeSort(l, mid); + mergeSort(r, n - mid); + + merge(a, l, r, mid, n - mid); + } + + public static void merge(int[] a, int[] l, int[] r, int left, int right) { + + int i = 0, j = 0, k = 0; + + while (i < left && j < right) { + + if (l[i] < r[j]) + a[k++] = l[i++]; + else + a[k++] = r[j++]; + + } + + while (i < left) + a[k++] = l[i++]; + + while (j < right) + a[k++] = r[j++]; + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java new file mode 100644 index 0000000000..5cd14b7bd0 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.algorithms.mergesort; + +import org.junit.Assert; + +import org.junit.Test; + +public class MergeSortUnitTest { + + @Test + public void positiveTest() { + int[] actual = { 5, 1, 6, 2, 3, 4 }; + int[] expected = { 1, 2, 3, 4, 5, 6 }; + MergeSort.mergeSort(actual, actual.length); + Assert.assertArrayEquals(expected, actual); + } + +} diff --git a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java similarity index 81% rename from animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java rename to animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java index 8ecb1bc629..dcfd22ff87 100644 --- a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java +++ b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java @@ -7,7 +7,7 @@ import junit.framework.TestSuite; /** * Unit test for simple App. */ -public class AppTest +public class AppUnitTest extends TestCase { /** @@ -15,7 +15,7 @@ public class AppTest * * @param testName name of the test case */ - public AppTest( String testName ) + public AppUnitTest( String testName ) { super( testName ); } @@ -25,7 +25,7 @@ public class AppTest */ public static Test suite() { - return new TestSuite( AppTest.class ); + return new TestSuite( AppUnitTest.class ); } /** diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml index 3e3234ff96..ddf5844271 100644 --- a/apache-avro/pom.xml +++ b/apache-avro/pom.xml @@ -6,7 +6,7 @@ com.baeldung apache-avro 0.0.1-SNAPSHOT - Apache Avro + Apache Avro UTF-8 diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java similarity index 98% rename from apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java rename to apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java index ecd15ccbbc..992ea806c3 100644 --- a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java +++ b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java @@ -13,7 +13,7 @@ import java.util.Objects; import static org.junit.Assert.*; -public class AvroSerealizerDeSerealizerTest { +public class AvroSerealizerDeSerealizerUnitTest { AvroSerealizer serealizer; AvroDeSerealizer deSerealizer; diff --git a/apache-geode/pom.xml b/apache-geode/pom.xml new file mode 100644 index 0000000000..a3f6604ac4 --- /dev/null +++ b/apache-geode/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + com.baeldung + apache-geode + 1.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.6.0 + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + org.apache.geode + geode-core + ${geode.core} + + + junit + junit + RELEASE + + + + \ No newline at end of file diff --git a/apache-geode/src/main/java/com/baeldung/geode/Customer.java b/apache-geode/src/main/java/com/baeldung/geode/Customer.java new file mode 100644 index 0000000000..82ee5ecaeb --- /dev/null +++ b/apache-geode/src/main/java/com/baeldung/geode/Customer.java @@ -0,0 +1,78 @@ +package com.baeldung.geode; + +import java.io.Serializable; +import java.util.Objects; + +public class Customer implements Serializable { + + private static final long serialVersionUID = -7482516011038799900L; + + private CustomerKey key; + private String firstName; + private String lastName; + private Integer age; + + public Customer() { + } + + public Customer(String firstName, String lastName, int age) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + public Customer(CustomerKey key, String firstName, String lastName, int age) { + this(firstName, lastName, age); + this.key = key; + } + + // setters and getters + + public static long getSerialVersionUID() { + return serialVersionUID; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + @Override + public String toString() { + return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Customer customer = (Customer) o; + return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName, age); + } +} diff --git a/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java b/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java new file mode 100644 index 0000000000..bfa64870c0 --- /dev/null +++ b/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java @@ -0,0 +1,57 @@ +package com.baeldung.geode; + +import java.io.Serializable; + +public class CustomerKey implements Serializable { + + private static final long serialVersionUID = -3529253035303792458L; + private long id; + private String country; + + public CustomerKey(long id) { + this.id = id; + this.country = "USA"; + } + + public CustomerKey(long id, String country) { + this.id = id; + this.country = country; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + CustomerKey that = (CustomerKey) o; + + if (id != that.id) + return false; + return country != null ? country.equals(that.country) : that.country == null; + } + + @Override + public int hashCode() { + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + (country != null ? country.hashCode() : 0); + return result; + } +} diff --git a/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java b/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java new file mode 100644 index 0000000000..5ff8e53da8 --- /dev/null +++ b/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java @@ -0,0 +1,34 @@ +package com.baeldung.geode.functions; + +import com.baeldung.geode.Customer; +import com.baeldung.geode.CustomerKey; +import org.apache.geode.cache.Region; +import org.apache.geode.cache.execute.Function; +import org.apache.geode.cache.execute.FunctionContext; +import org.apache.geode.cache.execute.RegionFunctionContext; + +import java.util.Map; + +public class UpperCaseNames implements Function { + private static final long serialVersionUID = -8946294032165677602L; + + @Override + public void execute(FunctionContext context) { + RegionFunctionContext regionContext = (RegionFunctionContext) context; + Region region = regionContext.getDataSet(); + + for (Map.Entry entry : region.entrySet()) { + Customer customer = entry.getValue(); + customer.setFirstName(customer.getFirstName() + .toUpperCase()); + } + + context.getResultSender() + .lastResult(true); + } + + @Override + public String getId() { + return getClass().getName(); + } +} diff --git a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java new file mode 100644 index 0000000000..b96d2c9b6a --- /dev/null +++ b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java @@ -0,0 +1,110 @@ +package com.baeldung.geode; + +import com.baeldung.geode.functions.UpperCaseNames; +import org.apache.geode.cache.Region; +import org.apache.geode.cache.client.ClientCache; +import org.apache.geode.cache.client.ClientCacheFactory; +import org.apache.geode.cache.client.ClientRegionShortcut; +import org.apache.geode.cache.execute.Execution; +import org.apache.geode.cache.execute.FunctionService; +import org.apache.geode.cache.query.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + +public class GeodeSamplesIntegrationTest { + + ClientCache cache = null; + Region region = null; + Region queryRegion = null; + Region customerRegion = null; + + @Before + public void connect() { + this.cache = new ClientCacheFactory().addPoolLocator("localhost", 10334) + .create(); + this.region = this.cache. createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY) + .create("baeldung"); + this.customerRegion = this.cache. createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY) + .create("baeldung-customers"); + } + + @After + public void cleanup() { + this.cache.close(); + } + + @Test + public void whenSendMessageToRegion_thenMessageSavedSuccessfully() { + + this.region.put("1", "Hello"); + this.region.put("2", "Baeldung"); + + assertEquals("Hello", region.get("1")); + assertEquals("Baeldung", region.get("2")); + + } + + @Test + public void whenPutMultipleValuesAtOnce_thenValuesSavedSuccessfully() { + + Supplier> keys = () -> Stream.of("A", "B", "C", "D", "E"); + Map values = keys.get() + .collect(Collectors.toMap(Function.identity(), String::toLowerCase)); + + this.region.putAll(values); + + keys.get() + .forEach(k -> assertEquals(k.toLowerCase(), this.region.get(k))); + + } + + @Test + public void whenPutCustomKey_thenValuesSavedSuccessfully() { + CustomerKey key = new CustomerKey(123); + Customer customer = new Customer(key, "William", "Russell", 35); + + Map customerInfo = new HashMap<>(); + customerInfo.put(key, customer); + + this.customerRegion.putAll(customerInfo); + + Customer storedCustomer = this.customerRegion.get(key); + assertEquals("William", storedCustomer.getFirstName()); + assertEquals("Russell", storedCustomer.getLastName()); + + } + + @Test + public void whenFindACustomerUsingOQL_thenCorrectCustomerObject() throws NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException { + + Map data = new HashMap<>(); + data.put(new CustomerKey(1), new Customer("Gheorge", "Manuc", 36)); + data.put(new CustomerKey(2), new Customer("Allan", "McDowell", 43)); + this.customerRegion.putAll(data); + + QueryService queryService = this.cache.getQueryService(); + String query = "select * from /baeldung-customers c where c.firstName = 'Allan'"; + SelectResults queryResults = (SelectResults) queryService.newQuery(query) + .execute(); + assertEquals(1, queryResults.size()); + + } + + @Test + public void whenExecuteUppercaseNames_thenCustomerNamesAreUppercased() { + Execution execution = FunctionService.onRegion(this.customerRegion); + execution.execute(UpperCaseNames.class.getName()); + Customer customer = this.customerRegion.get(new CustomerKey(1)); + assertEquals("GHEORGE", customer.getFirstName()); + } +} 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/asciidoctor/README.md b/asciidoctor/README.md index aafd0bca17..2124907e87 100644 --- a/asciidoctor/README.md +++ b/asciidoctor/README.md @@ -1,5 +1,4 @@ ### Relevant articles -- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor) - [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book) - [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor) diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml index 15de5ac913..42ee544eb0 100644 --- a/asciidoctor/pom.xml +++ b/asciidoctor/pom.xml @@ -61,9 +61,10 @@ - 1.5.5 - 1.5.4 - 1.5.0-alpha.11 + 1.5.6 + 1.5.6 + + 1.5.0-alpha.15 1.5.0-alpha.15 diff --git a/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java b/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java similarity index 89% rename from asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java rename to asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java index 3e312eb059..c4129e6441 100644 --- a/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java +++ b/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.asciidoctor; import org.junit.Assert; import org.junit.Test; -public class AsciidoctorDemoTest { +public class AsciidoctorDemoIntegrationTest { @Test public void givenString_whenConverting_thenResultingHTMLCode() { 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/cdi-portable-extension/flyway-cdi/pom.xml b/cdi-portable-extension/flyway-cdi/pom.xml new file mode 100644 index 0000000000..9fb781aaab --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + + flyway-cdi + + + com.baeldung + cdi-portable-extension + 1.0-SNAPSHOT + + + + + javax.enterprise + cdi-api + 2.0.SP1 + + + org.flywaydb + flyway-core + 5.1.4 + + + org.apache.tomcat + tomcat-jdbc + 8.5.33 + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + diff --git a/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java new file mode 100644 index 0000000000..a5019b82c1 --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java @@ -0,0 +1,74 @@ +package com.baeldung.cdi.extension; + +import org.apache.tomcat.jdbc.pool.DataSource; +import org.flywaydb.core.Flyway; + +import javax.annotation.sql.DataSourceDefinition; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.Any; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.literal.InjectLiteral; +import javax.enterprise.inject.spi.*; +import javax.enterprise.util.AnnotationLiteral; + + +/** + * Flyway is now under CDI container like: + * + * @ApplicationScoped + * @FlywayType public class Flyway{ + * @Inject setDataSource(DataSource dataSource){ + * //... + * } + * } + */ + +public class FlywayExtension implements Extension { + + DataSourceDefinition dataSourceDefinition = null; + + public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) { + bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName()); + } + + public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType patEvent) { + AnnotatedType at = patEvent.getAnnotatedType(); + dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class); + } + + public void processAnnotatedType(@Observes ProcessAnnotatedType patEvent) { + patEvent.configureAnnotatedType() + //Add Scope + .add(ApplicationScoped.Literal.INSTANCE) + //Add Qualifier + .add(new AnnotationLiteral() { + }) + //Decorate setDataSource(DataSource dataSource){} with @Inject + .filterMethods(annotatedMethod -> { + return annotatedMethod.getParameters().size() == 1 && + annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class); + }) + .findFirst().get().add(InjectLiteral.INSTANCE); + } + + void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) { + abdEvent.addBean() + .types(javax.sql.DataSource.class, DataSource.class) + .qualifiers(new AnnotationLiteral() {}, new AnnotationLiteral() {}) + .scope(ApplicationScoped.class) + .name(DataSource.class.getName()) + .beanClass(DataSource.class) + .createWith(creationalContext -> { + DataSource instance = new DataSource(); + instance.setUrl(dataSourceDefinition.url()); + instance.setDriverClassName(dataSourceDefinition.className()); + return instance; + }); + } + + void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) { + Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral() {}).get(); + flyway.migrate(); + } +} diff --git a/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayType.java b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayType.java new file mode 100644 index 0000000000..7c3a5affa6 --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayType.java @@ -0,0 +1,14 @@ +package com.baeldung.cdi.extension; + +import javax.inject.Qualifier; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target({FIELD, METHOD, PARAMETER, TYPE}) +@Qualifier +public @interface FlywayType { +} \ No newline at end of file diff --git a/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/beans.xml b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..44959bfa99 --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension new file mode 100644 index 0000000000..a82dc47714 --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -0,0 +1,2 @@ +com.baeldung.cdi.extension.FlywayExtension + diff --git a/cdi-portable-extension/main-app/pom.xml b/cdi-portable-extension/main-app/pom.xml new file mode 100644 index 0000000000..fab9b8bf07 --- /dev/null +++ b/cdi-portable-extension/main-app/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + main-app + jar + + + com.baeldung + cdi-portable-extension + 1.0-SNAPSHOT + + + + + + javax.enterprise + cdi-api + 2.0.SP1 + + + org.jboss.weld.se + weld-se-core + 3.0.5.Final + runtime + + + + com.baeldung + flyway-cdi + 1.0-SNAPSHOT + runtime + + + + com.h2database + h2 + 1.4.197 + runtime + + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + + \ No newline at end of file diff --git a/cdi-portable-extension/main-app/src/main/java/com/baeldung/cdi/extension/MainApp.java b/cdi-portable-extension/main-app/src/main/java/com/baeldung/cdi/extension/MainApp.java new file mode 100644 index 0000000000..1f6c5b43ba --- /dev/null +++ b/cdi-portable-extension/main-app/src/main/java/com/baeldung/cdi/extension/MainApp.java @@ -0,0 +1,16 @@ +package com.baeldung.cdi.extension; + +import javax.annotation.sql.DataSourceDefinition; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.se.SeContainer; +import javax.enterprise.inject.se.SeContainerInitializer; + +@ApplicationScoped +@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb") +public class MainApp { + public static void main(String[] args) { + SeContainerInitializer initializer = SeContainerInitializer.newInstance(); + try (SeContainer container = initializer.initialize()) { + } + } +} \ No newline at end of file diff --git a/cdi-portable-extension/main-app/src/main/resources/META-INF/beans.xml b/cdi-portable-extension/main-app/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..44959bfa99 --- /dev/null +++ b/cdi-portable-extension/main-app/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/cdi-portable-extension/main-app/src/main/resources/db/migration/V1__Create_person_table.sql b/cdi-portable-extension/main-app/src/main/resources/db/migration/V1__Create_person_table.sql new file mode 100644 index 0000000000..6bddc7689e --- /dev/null +++ b/cdi-portable-extension/main-app/src/main/resources/db/migration/V1__Create_person_table.sql @@ -0,0 +1,4 @@ +create table PERSON ( + ID int not null, + NAME varchar(100) not null +); diff --git a/cdi-portable-extension/main-app/src/main/resources/db/migration/V2__Add_people.sql b/cdi-portable-extension/main-app/src/main/resources/db/migration/V2__Add_people.sql new file mode 100644 index 0000000000..d8f1d62667 --- /dev/null +++ b/cdi-portable-extension/main-app/src/main/resources/db/migration/V2__Add_people.sql @@ -0,0 +1,3 @@ +insert into PERSON (ID, NAME) values (1, 'Axel'); +insert into PERSON (ID, NAME) values (2, 'Mr. Foo'); +insert into PERSON (ID, NAME) values (3, 'Ms. Bar'); diff --git a/cdi-portable-extension/pom.xml b/cdi-portable-extension/pom.xml new file mode 100644 index 0000000000..66913de84d --- /dev/null +++ b/cdi-portable-extension/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + com.baeldung + cdi-portable-extension + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + + + + main-app + flyway-cdi + + + + + javax.enterprise + cdi-api + 2.0.SP1 + + + + \ No newline at end of file diff --git a/core-java-9/logging.sh b/core-java-9/logging.sh new file mode 100755 index 0000000000..c9b502f300 --- /dev/null +++ b/core-java-9/logging.sh @@ -0,0 +1,15 @@ +# compile logging module +# javac --module-path mods -d mods/com.baeldung.logging src/modules/com.baeldung.logging/module-info.java src/modules/com.baeldung.logging/com/baeldung/logging/*.java + +# compile logging slf4j module +javac --module-path mods -d mods/com.baeldung.logging.slf4j src/modules/com.baeldung.logging.slf4j/module-info.java src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/*.java + + +# compile logging main app module +javac --module-path mods -d mods/com.baeldung.logging.app src/modules/com.baeldung.logging.app/module-info.java src/modules/com.baeldung.logging.app/com/baeldung/logging/app/*.java + +# run logging main app +# java --module-path mods -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp + +# run looging main app using logback +java --module-path mods -Dlogback.configurationFile=mods/logback.xml -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp diff --git a/core-java-9/mods/logback.xml b/core-java-9/mods/logback.xml new file mode 100644 index 0000000000..c22c7a7130 --- /dev/null +++ b/core-java-9/mods/logback.xml @@ -0,0 +1,16 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} -- %msg%n + + + + + + + + + \ No newline at end of file diff --git a/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java b/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java new file mode 100644 index 0000000000..01f53d59e9 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java @@ -0,0 +1,13 @@ +package com.baeldung.logging.app; + +import static java.lang.System.Logger.*; + +public class MainApp { + + private static System.Logger LOGGER = System.getLogger("MainApp"); + + public static void main(String[] args) { + LOGGER.log(Level.ERROR, "error test"); + LOGGER.log(Level.INFO, "info test"); + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging.app/module-info.java b/core-java-9/src/modules/com.baeldung.logging.app/module-info.java new file mode 100644 index 0000000000..037c72b755 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.app/module-info.java @@ -0,0 +1,2 @@ +module com.baeldung.logging.app { +} \ No newline at end of file diff --git a/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java new file mode 100644 index 0000000000..df41e071fd --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java @@ -0,0 +1,99 @@ +package com.baeldung.logging.slf4j; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ResourceBundle; + +public class Slf4jLogger implements System.Logger { + + private final String name; + private final Logger logger; + + public Slf4jLogger(String name) { + this.name = name; + logger = LoggerFactory.getLogger(name); + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isLoggable(Level level) { + switch (level) { + case OFF: + return false; + case TRACE: + return logger.isTraceEnabled(); + case DEBUG: + return logger.isDebugEnabled(); + case INFO: + return logger.isInfoEnabled(); + case WARNING: + return logger.isWarnEnabled(); + case ERROR: + return logger.isErrorEnabled(); + case ALL: + default: + return true; + } + } + + @Override + public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) { + if (!isLoggable(level)) { + return; + } + + switch (level) { + case TRACE: + logger.trace(msg, thrown); + break; + case DEBUG: + logger.debug(msg, thrown); + break; + case INFO: + logger.info(msg, thrown); + break; + case WARNING: + logger.warn(msg, thrown); + break; + case ERROR: + logger.error(msg, thrown); + break; + case ALL: + default: + logger.info(msg, thrown); + } + } + + @Override + public void log(Level level, ResourceBundle bundle, String format, Object... params) { + if (!isLoggable(level)) { + return; + } + + switch (level) { + case TRACE: + logger.trace(format, params); + break; + case DEBUG: + logger.debug(format, params); + break; + case INFO: + logger.info(format, params); + break; + case WARNING: + logger.warn(format, params); + break; + case ERROR: + logger.error(format, params); + break; + case ALL: + default: + logger.info(format, params); + } + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java new file mode 100644 index 0000000000..97f7cccb92 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java @@ -0,0 +1,8 @@ +package com.baeldung.logging.slf4j; + +public class Slf4jLoggerFinder extends System.LoggerFinder { + @Override + public System.Logger getLogger(String name, Module module) { + return new Slf4jLogger(name); + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java b/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java new file mode 100644 index 0000000000..311ca22f5b --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java @@ -0,0 +1,6 @@ +module com.baeldung.logging.slf4j { + requires org.slf4j; + provides java.lang.System.LoggerFinder + with com.baeldung.logging.slf4j.Slf4jLoggerFinder; + exports com.baeldung.logging.slf4j; +} \ No newline at end of file diff --git a/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java new file mode 100644 index 0000000000..a495e6979d --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java @@ -0,0 +1,27 @@ +package com.baeldung.logging; + +import java.text.MessageFormat; +import java.util.ResourceBundle; + +public class ConsoleLogger implements System.Logger { + + @Override + public String getName() { + return "ConsoleLogger"; + } + + @Override + public boolean isLoggable(Level level) { + return true; + } + + @Override + public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) { + System.out.printf("ConsoleLogger [%s]: %s - %s%n", level, msg, thrown); + } + + @Override + public void log(Level level, ResourceBundle bundle, String format, Object... params) { + System.out.printf("ConsoleLogger [%s]: %s%n", level, MessageFormat.format(format, params)); + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java new file mode 100644 index 0000000000..b38955f199 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java @@ -0,0 +1,9 @@ +package com.baeldung.logging; + +public class CustomLoggerFinder extends System.LoggerFinder { + + @Override + public System.Logger getLogger(String name, Module module) { + return new ConsoleLogger(); + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging/module-info.java b/core-java-9/src/modules/com.baeldung.logging/module-info.java new file mode 100644 index 0000000000..4ca0af0225 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging/module-info.java @@ -0,0 +1,5 @@ +module com.baeldung.logging { + provides java.lang.System.LoggerFinder + with com.baeldung.logging.CustomLoggerFinder; + exports com.baeldung.logging; +} \ No newline at end of file diff --git a/core-java-collections/README.md b/core-java-collections/README.md index f187141712..ca275d7c09 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -48,4 +48,6 @@ - [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe) - [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [](https://www.baeldung.com/java-hashset-arraylist-contains-performance) +- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance) +- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value) +- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity) 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/map/util/MapMax.java b/core-java-collections/src/main/java/com/baeldung/map/util/MapMax.java new file mode 100644 index 0000000000..93a98ba6fd --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/map/util/MapMax.java @@ -0,0 +1,96 @@ +package com.baeldung.map.util; + +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +public class MapMax { + + public > V maxUsingIteration(Map map) { + + Map.Entry maxEntry = null; + + for (Map.Entry entry : map.entrySet()) { + + if (maxEntry == null || entry.getValue() + .compareTo(maxEntry.getValue()) > 0) { + maxEntry = entry; + } + } + + return maxEntry.getValue(); + } + + public > V maxUsingCollectionsMax(Map map) { + + Entry maxEntry = Collections.max(map.entrySet(), new Comparator>() { + public int compare(Entry e1, Entry e2) { + return e1.getValue() + .compareTo(e2.getValue()); + } + }); + + return maxEntry.getValue(); + } + + public > V maxUsingCollectionsMaxAndLambda(Map map) { + + Entry maxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue() + .compareTo(e2.getValue())); + + return maxEntry.getValue(); + } + + public > V maxUsingCollectionsMaxAndMethodReference(Map map) { + + Entry maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue)); + + return maxEntry.getValue(); + } + + public > V maxUsingStreamAndLambda(Map map) { + + Optional> maxEntry = map.entrySet() + .stream() + .max((Entry e1, Entry e2) -> e1.getValue() + .compareTo(e2.getValue())); + + return maxEntry.get() + .getValue(); + } + + public > V maxUsingStreamAndMethodReference(Map map) { + + Optional> maxEntry = map.entrySet() + .stream() + .max(Comparator.comparing(Map.Entry::getValue)); + + return maxEntry.get() + .getValue(); + } + + public static void main(String[] args) { + + Map map = new HashMap(); + + map.put(1, 3); + map.put(2, 4); + map.put(3, 5); + map.put(4, 6); + map.put(5, 7); + + MapMax mapMax = new MapMax(); + + System.out.println(mapMax.maxUsingIteration(map)); + System.out.println(mapMax.maxUsingCollectionsMax(map)); + System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map)); + System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map)); + System.out.println(mapMax.maxUsingStreamAndLambda(map)); + System.out.println(mapMax.maxUsingStreamAndMethodReference(map)); + + } + +} 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-collections/src/test/java/com/baeldung/map/util/MapMaxUnitTest.java b/core-java-collections/src/test/java/com/baeldung/map/util/MapMaxUnitTest.java new file mode 100644 index 0000000000..883265cc8b --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/map/util/MapMaxUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.map.util; + + + +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; + +public class MapMaxUnitTest { + + Map map = null; + MapMax mapMax = null; + + + @Before + public void setupTestData() { + map = new HashMap(); + map.put(23, 12); + map.put(46, 24); + map.put(27, 38); + mapMax = new MapMax(); + } + + @Test + public void givenMap_whenIterated_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingIteration(map)); + } + + @Test + public void givenMap_whenUsingCollectionsMax_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingCollectionsMax(map)); + } + + @Test + public void givenMap_whenUsingCollectionsMaxAndLambda_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndLambda(map)); + } + + @Test + public void givenMap_whenUsingCollectionsMaxAndMethodReference_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndMethodReference(map)); + } + + @Test + public void givenMap_whenUsingStreamAndLambda_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingStreamAndLambda(map)); + } + + @Test + public void givenMap_whenUsingStreamAndMethodReference_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingStreamAndMethodReference (map)); + } + + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java new file mode 100644 index 0000000000..b31a04015f --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java @@ -0,0 +1,17 @@ +package com.baeldung.concurrent.yield; + +public class ThreadYield { + public static void main(String[] args) { + Runnable r = () -> { + int counter = 0; + while (counter < 2) { + System.out.println(Thread.currentThread() + .getName()); + counter++; + Thread.yield(); + } + }; + new Thread(r).start(); + new Thread(r).start(); + } +} diff --git a/core-java-io/README.md b/core-java-io/README.md index 17c93d9739..58e331b6fc 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -31,3 +31,4 @@ - [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink) - [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) +- [ Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist) 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..e781489808 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; @@ -17,6 +18,7 @@ import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; @@ -49,7 +51,7 @@ public class FileOperationsManualTest { @Test public void givenFileName_whenUsingJarFile_thenFileData() throws IOException { - String expectedData = "BSD License"; + String expectedData = "MIT License"; Class clazz = Matchers.class; InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); @@ -78,7 +80,7 @@ public class FileOperationsManualTest { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("fileTest.txt").getFile()); - String data = FileUtils.readFileToString(file); + String data = FileUtils.readFileToString(file, "UTF-8"); assertEquals(expectedData, data.trim()); } @@ -101,12 +103,11 @@ public class FileOperationsManualTest { Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); - StringBuilder data = new StringBuilder(); Stream lines = Files.lines(path); - lines.forEach(line -> data.append(line).append("\n")); + String data = lines.collect(Collectors.joining("\n")); lines.close(); - assertEquals(expectedData, data.toString().trim()); + assertEquals(expectedData, data.trim()); } private String readFromInputStream(InputStream inputStream) throws IOException { @@ -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-io/src/test/resources/fileTest.txt b/core-java-io/src/test/resources/fileTest.txt new file mode 100644 index 0000000000..ce4bea208b --- /dev/null +++ b/core-java-io/src/test/resources/fileTest.txt @@ -0,0 +1 @@ +Hello World from fileTest.txt!!! \ No newline at end of file diff --git a/core-java/README.md b/core-java/README.md index ade7f46504..fbfcb1117c 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -151,3 +151,4 @@ - [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist) - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) - [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) +- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic) diff --git a/core-java/src/main/java/com/baeldung/decimalformat/DoubletoString.java b/core-java/src/main/java/com/baeldung/decimalformat/DoubletoString.java deleted file mode 100644 index 87d10a3548..0000000000 --- a/core-java/src/main/java/com/baeldung/decimalformat/DoubletoString.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.decimalformat; - - import java.math.RoundingMode; - import java.text.DecimalFormat; - import java.text.NumberFormat; - import java.util.Locale; - - public class DoubletoString { - - public static void main(String[] args) { - - double doubleValue = 345.56; - - System.out.println(String.valueOf((int) doubleValue)); - - System.out.println(String.format("%.0f", doubleValue)); - - doubleValue = Math.floor(doubleValue); - DecimalFormat df = new DecimalFormat("#"); - df.setRoundingMode(RoundingMode.FLOOR); - System.out.println(df.format(doubleValue)); - - Locale enlocale = new Locale("en", "US"); - String pattern = "###,##"; - df = (DecimalFormat) NumberFormat.getNumberInstance(enlocale); - df.applyPattern(pattern); - String format = df.format(doubleValue); - System.out.println(format); - - Locale dalocale = new Locale("da", "DK"); - df = (DecimalFormat) NumberFormat.getNumberInstance(dalocale); - df.applyPattern(pattern); - System.out.println(df.format(doubleValue)); - - - } - - } 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/memoryleaks/equalshashcode/Person.java b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java new file mode 100755 index 0000000000..e16d1ae6da --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java @@ -0,0 +1,9 @@ +package com.baeldung.memoryleaks.equalshashcode; + +public class Person { + public String name; + + public Person(String name) { + this.name = name; + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java new file mode 100755 index 0000000000..3af70dd1eb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java @@ -0,0 +1,25 @@ +package com.baeldung.memoryleaks.equalshashcode; + +public class PersonOptimized { + public String name; + + public PersonOptimized(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof PersonOptimized)) { + return false; + } + PersonOptimized person = (PersonOptimized) o; + return person.name.equals(name); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + name.hashCode(); + return result; + }} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java new file mode 100755 index 0000000000..ce77d883f6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java @@ -0,0 +1,32 @@ +package com.baeldung.memoryleaks.finalize; + +import java.nio.charset.Charset; +import java.util.Random; + +public class BulkyObject { + private String data[]; + + public BulkyObject() { + data = new String[1000000]; + + for(int i=0; i<1000000; i++) { + data[i] = getRandomString(); + } + } + + private String getRandomString() { + byte[] array = new byte[1000]; + new Random().nextBytes(array); + return new String(array, Charset.forName("UTF-8")); + } + + @Override + public void finalize() { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Finalizer called"); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java new file mode 100644 index 0000000000..dc1302432e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java @@ -0,0 +1,22 @@ +package com.baeldung.memoryleaks.finalize; + +import java.nio.charset.Charset; +import java.util.Random; + +public class BulkyObjectOptimized { + private String data[]; + + public BulkyObjectOptimized() { + data = new String[1000000]; + + for(int i=0; i<1000000; i++) { + data[i] = getRandomString(); + } + } + + private String getRandomString() { + byte[] array = new byte[1000]; + new Random().nextBytes(array); + return new String(array, Charset.forName("UTF-8")); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java new file mode 100755 index 0000000000..bbd5310182 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java @@ -0,0 +1,22 @@ +package com.baeldung.memoryleaks.innerclass; + +import java.nio.charset.Charset; +import java.util.Random; + +public class BulkyObject { + private String data[]; + + public BulkyObject() { + data = new String[1000000]; + + for(int i=0; i<1000000; i++) { + data[i] = getRandomString(); + } + } + + private String getRandomString() { + byte[] array = new byte[1000]; + new Random().nextBytes(array); + return new String(array, Charset.forName("UTF-8")); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java new file mode 100755 index 0000000000..06f928bc4a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java @@ -0,0 +1,17 @@ +package com.baeldung.memoryleaks.innerclass; + +public class InnerClassDriver { + public static InnerClassWrapper.SimpleInnerClass getSimpleInnerClassObj() { + return new InnerClassWrapper().new SimpleInnerClass(); + } + + public static void main2(String[] args) { + InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = getSimpleInnerClassObj(); + System.out.println("Debug point"); + } + + public static void main(String[] args) { + StaticNestedClassWrapper.StaticNestedClass simpleInnerClassObj = new StaticNestedClassWrapper.StaticNestedClass(); + System.out.println("Debug point"); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java new file mode 100755 index 0000000000..25fecf9bb3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java @@ -0,0 +1,10 @@ +package com.baeldung.memoryleaks.innerclass; + + +public class InnerClassWrapper { + private BulkyObject bulkyObject = new BulkyObject(); + + public class SimpleInnerClass { + + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java new file mode 100755 index 0000000000..d1729d78a3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java @@ -0,0 +1,10 @@ +package com.baeldung.memoryleaks.innerclass; + + +public class StaticNestedClassWrapper { + private BulkyObject bulkyObject = new BulkyObject(); + + public static class StaticNestedClass { + + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java new file mode 100644 index 0000000000..cbba8f849d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java @@ -0,0 +1,17 @@ +package com.baeldung.memoryleaks.internedstrings; + +public class InternedString { + private static final String FILEPATH = "C:\\bigstring.txt"; + + public void readString() { + String s1 = ReadStringFromFileUtil.read(FILEPATH).intern(); + String s2 = ReadStringFromFileUtil.read(FILEPATH).intern(); + + if (s1 == s2) { + System.out.println("Both the strings objects are same"); + } + else { + System.out.println("Both the strings objects are different"); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java new file mode 100644 index 0000000000..2b7d72accc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java @@ -0,0 +1,34 @@ +package com.baeldung.memoryleaks.internedstrings; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class ReadStringFromFileUtil { + + public static String read(String fileName) { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(fileName)); + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + return sb.toString(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } + +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java new file mode 100644 index 0000000000..e48e448d18 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java @@ -0,0 +1,17 @@ +package com.baeldung.memoryleaks.internedstrings; + +public class StringObject { + private static final String FILEPATH = "C:\\bigstring.txt"; + + public void readString() { + String s1 = ReadStringFromFileUtil.read(FILEPATH); + String s2 = ReadStringFromFileUtil.read(FILEPATH); + + if (s1 == s2) { + System.out.println("Both the strings objects are same"); + } + else { + System.out.println("Both the strings objects are different"); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java new file mode 100644 index 0000000000..f2b220e76d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java @@ -0,0 +1,21 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +public class NonStaticFieldsDemo { + public List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + public static void main(String[] args) { + System.out.println("Debug Point 1"); + new NonStaticFieldsDemo().populateList(); + System.out.println("Debug Point 3"); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java new file mode 100644 index 0000000000..17cebc2843 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java @@ -0,0 +1,21 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +public class StaticFieldsDemo { + public static List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + public static void main(String[] args) { + System.out.println("Debug Point 1"); + new StaticFieldsDemo().populateList(); + System.out.println("Debug Point 3"); + } +} \ No newline at end of file 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 new file mode 100644 index 0000000000..fb92eb8d0d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java @@ -0,0 +1,13 @@ +package com.baeldung.zoneddatetime; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +public class OffsetDateTimeExample { + + 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 new file mode 100644 index 0000000000..58e2d4d5ad --- /dev/null +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java @@ -0,0 +1,13 @@ +package com.baeldung.zoneddatetime; + +import java.time.OffsetTime; +import java.time.ZoneOffset; + +public class OffsetTimeExample { + + public OffsetTime getCurrentTimeByZoneOffset(String offset) { + ZoneOffset zoneOffSet = ZoneOffset.of(offset); + OffsetTime time = OffsetTime.now(zoneOffSet); + return time; + } +} diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java new file mode 100644 index 0000000000..b54b8c5225 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java @@ -0,0 +1,21 @@ +package com.baeldung.zoneddatetime; + +import java.time.ZoneId; +import java.time.ZonedDateTime; + +public class ZoneDateTimeExample { + + public ZonedDateTime getCurrentTimeByZoneId(String region) { + ZoneId zone = ZoneId.of(region); + ZonedDateTime date = ZonedDateTime.now(zone); + return date; + } + + public ZonedDateTime convertZonedDateTime(ZonedDateTime sourceDate, String destZone) { + + ZoneId destZoneId = ZoneId.of(destZone); + ZonedDateTime destDate = sourceDate.withZoneSameInstant(destZoneId); + + return destDate; + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java new file mode 100644 index 0000000000..3fa1db18d2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.memoryleaks.equalshashcode; + +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Ignore; +import org.junit.Test; + +public class PersonMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() { + Map map = new HashMap(); + for(int i=0; i<10000000; i++) { + map.put(new Person("jon"), 1); + } + assertTrue(map.size() > 1); + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenMap_whenEqualsAndHashCodeOverridden_thenNoMemoryLeak() { + Map map = new HashMap(); + for(int i=0; i<10000; i++) { + map.put(new PersonOptimized("jon"), 1); + } + assertTrue(map.size() == 1); + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java new file mode 100644 index 0000000000..b6d81a8968 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.memoryleaks.finalize; + +import org.junit.Ignore; +import org.junit.Test; + +public class FinalizeMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenObjectWithFinalizer_whenCreatingAndDestroyingThisObject_thenMemoryLeak() { + BulkyObject[] stock = new BulkyObject[100000]; + + for(int i=0; i<100000; i++) { + stock[i] = new BulkyObject(); + } + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenObjectWithoutFinalizer_whenCreatingAndDestroyingThisObject_thenNoMemoryLeak() { + BulkyObjectOptimized[] stock = new BulkyObjectOptimized[100000]; + + for(int i=0; i<100000; i++) { + stock[i] = new BulkyObjectOptimized(); + } + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java new file mode 100644 index 0000000000..0854e4a38a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.memoryleaks.innerclass; + +import org.junit.Ignore; +import org.junit.Test; + +public class StaticInnerClassMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenUsingInnerClass_whenInitializingInnerClass_thenInnerClassHoldsReferenceOfOuterObject() { + InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = new InnerClassWrapper().new SimpleInnerClass(); + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenUsingStaticNestedClass_whenInitializingInnerClass_thenStaticNestedClassDoesntReferenceOuterObject() { + StaticNestedClassWrapper.StaticNestedClass staticNestedClassObj = new StaticNestedClassWrapper.StaticNestedClass(); + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java new file mode 100644 index 0000000000..6d363e0bdc --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.memoryleaks.internedstrings; + +import org.junit.Ignore; +import org.junit.Test; + +public class StringInternMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenJava6OrBelow_whenInterningLargeStrings_thenPermgenIncreases() { + new InternedString().readString(); + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenJava6OrBelow_whenNotInterningLargeStrings_thenPermgenDoesntIncrease() { + new StringObject().readString(); + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java new file mode 100644 index 0000000000..e64fdb73e0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +public class NonStaticFieldsMemoryLeakUnitTest { + public List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenNonStaticLargeList_whenPopulatingList_thenListGarbageCollected() { + System.out.println("Debug Point 1"); + new NonStaticFieldsMemoryLeakUnitTest().populateList(); + System.out.println("Debug Point 3"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java new file mode 100644 index 0000000000..1765f0cf0d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +public class StaticFieldsMemoryLeakUnitTest { + public static List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenStaticLargeList_whenPopulatingList_thenListIsNotGarbageCollected() { + System.out.println("Debug Point 1"); + new StaticFieldsDemo().populateList(); + System.out.println("Debug Point 3"); + } +} 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/removingdecimals/RemovingDecimalsManualTest.java b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java new file mode 100644 index 0000000000..8dbfcaf5e7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java @@ -0,0 +1,100 @@ +package com.baeldung.removingdecimals; + +import org.junit.Test; +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.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.concurrent.TimeUnit; + +/** + * This benchmark compares some of the approaches to formatting a floating-point + * value into a {@link String} while removing the decimal part. + * + * To run, simply run the {@link RemovingDecimalsManualTest#runBenchmarks()} test + * at the end of this class. + * + * The benchmark takes about 15 minutes to run. Since it is using {@link Mode#Throughput}, + * higher numbers mean better performance. + */ +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 20) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@State(Scope.Benchmark) +public class RemovingDecimalsManualTest { + @Param(value = {"345.56", "345345345.56", "345345345345345345.56"}) double doubleValue; + + NumberFormat nf; + DecimalFormat df; + + @Setup + public void readyFormatters() { + nf = NumberFormat.getInstance(); + nf.setMaximumFractionDigits(0); + df = new DecimalFormat("#,###"); + } + + @Benchmark + public String whenCastToInt_thenValueIsTruncated() { + return String.valueOf((int) doubleValue); + } + + @Benchmark + public String whenUsingStringFormat_thenValueIsRounded() { + return String.format("%.0f", doubleValue); + } + + @Benchmark + public String whenUsingNumberFormat_thenValueIsRounded() { + nf.setRoundingMode(RoundingMode.HALF_UP); + return nf.format(doubleValue); + } + + @Benchmark + public String whenUsingNumberFormatWithFloor_thenValueIsTruncated() { + nf.setRoundingMode(RoundingMode.FLOOR); + return nf.format(doubleValue); + } + + @Benchmark + public String whenUsingDecimalFormat_thenValueIsRounded() { + df.setRoundingMode(RoundingMode.HALF_UP); + return df.format(doubleValue); + } + + @Benchmark + public String whenUsingDecimalFormatWithFloor_thenValueIsTruncated() { + df.setRoundingMode(RoundingMode.FLOOR); + return df.format(doubleValue); + } + + @Benchmark + public String whenUsingBigDecimalDoubleValue_thenValueIsTruncated() { + BigDecimal big = new BigDecimal(doubleValue); + big = big.setScale(0, RoundingMode.FLOOR); + return big.toString(); + } + + @Benchmark + public String whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() { + BigDecimal big = new BigDecimal(doubleValue); + big = big.setScale(0, RoundingMode.HALF_UP); + return big.toString(); + } + + @Test + public void runBenchmarks() throws Exception { + Options options = new OptionsBuilder() + .include(this.getClass().getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true).shouldDoGC(true) + .jvmArgs("-server").build(); + + new Runner(options).run(); + } +} diff --git a/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java new file mode 100644 index 0000000000..2f634b553b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java @@ -0,0 +1,95 @@ +package com.baeldung.removingdecimals; + +import org.junit.Test; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.text.NumberFormat; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +/** + * Tests that demonstrate some different approaches for formatting a + * floating-point value into a {@link String} while removing the decimal part. + */ +public class RemovingDecimalsUnitTest { + private final double doubleValue = 345.56; + + @Test + public void whenCastToInt_thenValueIsTruncated() { + String truncated = String.valueOf((int) doubleValue); + assertEquals("345", truncated); + } + + @Test + public void givenALargeDouble_whenCastToInt_thenValueIsNotTruncated() { + double outOfIntRange = 6_000_000_000.56; + String truncationAttempt = String.valueOf((int) outOfIntRange); + assertNotEquals("6000000000", truncationAttempt); + } + + @Test + public void whenUsingStringFormat_thenValueIsRounded() { + String rounded = String.format("%.0f", doubleValue); + assertEquals("346", rounded); + } + + @Test + public void givenALargeDouble_whenUsingStringFormat_thenValueIsStillRounded() { + double outOfIntRange = 6_000_000_000.56; + String rounded = String.format("%.0f", outOfIntRange); + assertEquals("6000000001", rounded); + } + + @Test + public void whenUsingNumberFormat_thenValueIsRounded() { + NumberFormat nf = NumberFormat.getInstance(); + nf.setMaximumFractionDigits(0); + nf.setRoundingMode(RoundingMode.HALF_UP); + String rounded = nf.format(doubleValue); + assertEquals("346", rounded); + } + + @Test + public void whenUsingNumberFormatWithFloor_thenValueIsTruncated() { + NumberFormat nf = NumberFormat.getInstance(); + nf.setMaximumFractionDigits(0); + nf.setRoundingMode(RoundingMode.FLOOR); + String truncated = nf.format(doubleValue); + assertEquals("345", truncated); + } + + @Test + public void whenUsingDecimalFormat_thenValueIsRounded() { + DecimalFormat df = new DecimalFormat("#,###"); + df.setRoundingMode(RoundingMode.HALF_UP); + String rounded = df.format(doubleValue); + assertEquals("346", rounded); + } + + @Test + public void whenUsingDecimalFormatWithFloor_thenValueIsTruncated() { + DecimalFormat df = new DecimalFormat("#,###"); + df.setRoundingMode(RoundingMode.FLOOR); + String truncated = df.format(doubleValue); + assertEquals("345", truncated); + } + + @Test + public void whenUsingBigDecimalDoubleValue_thenValueIsTruncated() { + BigDecimal big = new BigDecimal(doubleValue); + big = big.setScale(0, RoundingMode.FLOOR); + String truncated = big.toString(); + assertEquals("345", truncated); + } + + @Test + public void whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() { + BigDecimal big = new BigDecimal(doubleValue); + big = big.setScale(0, RoundingMode.HALF_UP); + String truncated = big.toString(); + assertEquals("346", truncated); + } +} 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/ternaryoperator/TernaryOperatorUnitTest.java b/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java new file mode 100644 index 0000000000..6b292ad8ab --- /dev/null +++ b/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.ternaryoperator; + +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class TernaryOperatorUnitTest { + + @Test + public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() { + int number = 10; + String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10"; + + assertThat(msg).isEqualTo("Number is less than or equal to 10"); + } + + @Test + public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() { + int exp1 = 0, exp2 = 0; + int result = 12 > 10 ? ++exp1 : ++exp2; + + assertThat(exp1).isEqualTo(1); + assertThat(exp2).isEqualTo(0); + assertThat(result).isEqualTo(1); + } + + @Test + public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() { + int exp1 = 0, exp2 = 0; + int result = 8 > 10 ? ++exp1 : ++exp2; + + assertThat(exp1).isEqualTo(0); + assertThat(exp2).isEqualTo(1); + assertThat(result).isEqualTo(1); + } + + @Test + public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() { + int number = 6; + String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5"; + + assertThat(msg).isEqualTo("Number is greater than 5"); + } +} diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java new file mode 100644 index 0000000000..a08d3737cd --- /dev/null +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.zoneddatetime; + +import static org.junit.Assert.assertTrue; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +import org.junit.Test; + +public class OffsetDateTimeExampleUnitTest { + + OffsetDateTimeExample offsetDateTimeExample = new OffsetDateTimeExample(); + + @Test + public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() { + String offset = "+02:00"; + OffsetDateTime time = offsetDateTimeExample.getCurrentTimeByZoneOffset(offset); + + assertTrue(time.getOffset() + .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 new file mode 100644 index 0000000000..488f934179 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.zoneddatetime; + +import static org.junit.Assert.assertTrue; + +import java.time.OffsetTime; +import java.time.ZoneOffset; + +import org.junit.Test; + +public class OffsetTimeExampleUnitTest { + + OffsetTimeExample offsetTimeExample = new OffsetTimeExample(); + + @Test + public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() { + String offset = "+02:00"; + OffsetTime time = offsetTimeExample.getCurrentTimeByZoneOffset(offset); + + assertTrue(time.getOffset() + .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 new file mode 100644 index 0000000000..e78ff3e3fd --- /dev/null +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.zoneddatetime; + +import static org.junit.Assert.assertTrue; + +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Test; + +public class ZoneDateTimeExampleUnitTest { + + ZoneDateTimeExample zoneDateTimeExample = new ZoneDateTimeExample(); + + @Test + 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); + } +} diff --git a/core-kotlin/README.md b/core-kotlin/README.md index f63451bc02..7d8d5213d1 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -33,4 +33,7 @@ - [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging) - [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors) - [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) -- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes) \ No newline at end of file +- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes) +- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor) +- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) +- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt rename to core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StringConcatenationTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StringConcatenationTest.kt new file mode 100644 index 0000000000..9c371614a4 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StringConcatenationTest.kt @@ -0,0 +1,48 @@ +package com.baeldung.kotlin + +import org.junit.Test +import kotlin.test.assertEquals + +class StringConcatenationTest { + + @Test + fun givenTwoStrings_concatenateWithTemplates_thenEquals() { + val a = "Hello" + val b = "Baeldung" + val c = "$a $b" + + assertEquals("Hello Baeldung", c) + } + + @Test + fun givenTwoStrings_concatenateWithPlusOperator_thenEquals() { + val a = "Hello" + val b = "Baeldung" + val c = a + " " + b + + assertEquals("Hello Baeldung", c) + } + + @Test + fun givenTwoStrings_concatenateWithStringBuilder_thenEquals() { + val a = "Hello" + val b = "Baeldung" + + val builder = StringBuilder() + builder.append(a).append(" ").append(b) + + val c = builder.toString() + + assertEquals("Hello Baeldung", c) + } + + @Test + fun givenTwoStrings_concatenateWithPlusMethod_thenEquals() { + val a = "Hello" + val b = "Baeldung" + val c = a.plus(" ").plus(b) + + assertEquals("Hello Baeldung", c) + } + +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt new file mode 100644 index 0000000000..bdf44d3b49 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt @@ -0,0 +1,30 @@ +package com.baeldung.kotlin.gson + +import com.google.gson.Gson + +import org.junit.Assert +import org.junit.Test + +class GsonUnitTest { + + var gson = Gson() + + @Test + fun givenObject_thenGetJSONString() { + var jsonString = gson.toJson(TestModel(1,"Test")) + Assert.assertEquals(jsonString, "{\"id\":1,\"description\":\"Test\"}") + } + + @Test + fun givenJSONString_thenGetObject() { + var jsonString = "{\"id\":1,\"description\":\"Test\"}"; + var testModel = gson.fromJson(jsonString, TestModel::class.java) + Assert.assertEquals(testModel.id, 1) + Assert.assertEquals(testModel.description, "Test") + } + + data class TestModel( + val id: Int, + val description: String + ) +} \ No newline at end of file diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml index fffbbdb1da..dac2fefb84 100755 --- a/ejb/ejb-remote/pom.xml +++ b/ejb/ejb-remote/pom.xml @@ -15,7 +15,6 @@ javax javaee-api - ${javaee-api.version} provided diff --git a/ejb/ejb-session-beans/pom.xml b/ejb/ejb-session-beans/pom.xml index 14ab0790e7..da76169729 100644 --- a/ejb/ejb-session-beans/pom.xml +++ b/ejb/ejb-session-beans/pom.xml @@ -24,7 +24,6 @@ javax javaee-api - ${javaee-api.version} provided diff --git a/flyway/pom.xml b/flyway/pom.xml index b1cc58af3d..353bbfb1ec 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -65,6 +65,7 @@ 5.0.2 5.0.2 + 1.4.195 diff --git a/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java similarity index 98% rename from flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java rename to flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java index 5e96fff64d..bf30ce604d 100644 --- a/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java +++ b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java @@ -16,7 +16,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) @ContextConfiguration(classes = FlywayCallbackTestConfig.class) -public class FlywayApplicationTest { +public class FlywayApplicationUnitTest { private Log log = LogFactory.getLog(getClass()); diff --git a/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java b/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceUnitTest.java similarity index 98% rename from guest/log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java rename to guest/log4j2-example/src/test/java/com/stackify/services/MyServiceUnitTest.java index 49e367e45b..bd08225be4 100644 --- a/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java +++ b/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceUnitTest.java @@ -18,9 +18,9 @@ import org.junit.Test; import com.stackify.models.User; import com.stackify.services.MyService; -public class MyServiceTest { +public class MyServiceUnitTest { - private static final Logger logger = LogManager.getLogger(MyServiceTest.class); + private static final Logger logger = LogManager.getLogger(MyServiceUnitTest.class); @Test public void testService() { diff --git a/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceUnitTest.java similarity index 98% rename from guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java rename to guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceUnitTest.java index 187b27e1df..a3051f7087 100644 --- a/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java +++ b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceUnitTest.java @@ -9,7 +9,7 @@ import com.stackify.models.Employee; import ch.qos.logback.classic.Level; -public class EmployeeServiceTest { +public class EmployeeServiceUnitTest { private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); private EmployeeService employeeService = new EmployeeService(); diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml index 42543b5be0..c0ef451605 100644 --- a/guest/spring-mvc/pom.xml +++ b/guest/spring-mvc/pom.xml @@ -12,7 +12,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M5 + 2.0.0.RELEASE diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml index baca3bce85..8be42ba32b 100644 --- a/guest/spring-security/pom.xml +++ b/guest/spring-security/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M6 + 2.0.0.RELEASE diff --git a/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java b/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceLiveTest.java similarity index 95% rename from guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java rename to guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceLiveTest.java index 064951fbbe..be3992b7f7 100644 --- a/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java +++ b/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceLiveTest.java @@ -6,7 +6,7 @@ import io.restassured.RestAssured; import static io.restassured.RestAssured.*; import static org.hamcrest.CoreMatchers.*; -public class UserServiceTest { +public class UserServiceLiveTest { @Test public void whenAddUser_thenGetUserOk() { RestAssured.baseURI = "http://localhost:8080/rest-server"; diff --git a/hibernate5/README.md b/hibernate5/README.md index 8f2f8eb469..b67ab7115f 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -14,3 +14,4 @@ - [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) - [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking) - [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle) +- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 23d7d2e201..2212e736ab 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,5 +1,11 @@ package com.baeldung.hibernate; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import com.baeldung.hibernate.entities.DeptEmployee; import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; import com.baeldung.hibernate.pessimisticlocking.Individual; @@ -16,10 +22,30 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.util.Properties; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Person; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.baeldung.hibernate.pojo.Product; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; public class HibernateUtil { private static SessionFactory sessionFactory; @@ -72,6 +98,8 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java b/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + 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; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..7a51009b62 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,65 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.*; + +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String designation; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getDesignation() { + return designation; + } + + public void setDesignation(String designation) { + this.designation = designation; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java new file mode 100644 index 0000000000..607269a267 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +public class Result { + private String employeeName; + + private String departmentName; + + public Result(String employeeName, String departmentName) { + this.employeeName = employeeName; + this.departmentName = departmentName; + } + + public Result() { + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public String getDepartmentName() { + return departmentName; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java new file mode 100644 index 0000000000..29ae55b773 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java @@ -0,0 +1,77 @@ +package com.baeldung.hibernate; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.List; + +import com.baeldung.hibernate.entities.DeptEmployee; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.query.Query; +import org.hibernate.transform.Transformers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.baeldung.hibernate.entities.Department; +import com.baeldung.hibernate.pojo.Result; + +public class CustomClassIntegrationTest { + + private Session session; + + private Transaction transaction; + + @BeforeEach + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + session.createNativeQuery("delete from manager").executeUpdate(); + session.createNativeQuery("delete from department").executeUpdate(); + Department department = new Department("Sales"); + DeptEmployee employee = new DeptEmployee("John Smith", "001", department); + session.persist(department); + session.persist(employee); + transaction.commit(); + transaction = session.beginTransaction(); + } + + @Test + public void whenAllManagersAreSelected_ThenObjectGraphIsReturned() { + Query query = session.createQuery("from com.baeldung.hibernate.entities.DeptEmployee"); + List deptEmployees = query.list(); + DeptEmployee deptEmployee = deptEmployees.get(0); + assertEquals("John Smith", deptEmployee.getName()); + assertEquals("Sales", deptEmployee.getDepartment().getName()); + } + + @Test + public void whenIndividualPropertiesAreSelected_ThenObjectArrayIsReturned() { + Query query = session.createQuery("select m.name, m.department.name from com.baeldung.hibernate.entities.DeptEmployee m"); + List managers = query.list(); + Object[] manager = (Object[]) managers.get(0); + assertEquals("John Smith", manager[0]); + assertEquals("Sales", manager[1]); + } + + @Test + public void whenResultConstructorInSelect_ThenListOfResultIsReturned() { + Query query = session.createQuery("select new com.baeldung.hibernate.pojo.Result(m.name, m.department.name) " + + "from DeptEmployee m"); + List results = query.list(); + Result result = results.get(0); + assertEquals("John Smith", result.getEmployeeName()); + assertEquals("Sales", result.getDepartmentName()); + } + + @Test + public void whenResultTransformerOnQuery_ThenListOfResultIsReturned() { + Query query = session.createQuery("select m.name as employeeName, m.department.name as departmentName " + + "from com.baeldung.hibernate.entities.DeptEmployee m"); + query.setResultTransformer(Transformers.aliasToBean(Result.class)); + List results = query.list(); + Result result = results.get(0); + assertEquals("John Smith", result.getEmployeeName()); + assertEquals("Sales", result.getDepartmentName()); + } +} diff --git a/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java b/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java new file mode 100644 index 0000000000..c031c97dec --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java @@ -0,0 +1,32 @@ +package com.baeldung.date; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.Period; +import java.util.Date; +import org.joda.time.Years; + +public class AgeCalculator { + + public int calculateAge(LocalDate birthDate, LocalDate currentDate) { + // validate inputs ... + return Period.between(birthDate, currentDate) + .getYears(); + } + + public int calculateAgeWithJodaTime(org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) { + // validate inputs ... + Years age = Years.yearsBetween(birthDate, currentDate); + return age.getYears(); + } + + public int calculateAgeWithJava7(Date birthDate, Date currentDate) { + // validate inputs ... + DateFormat formatter = new SimpleDateFormat("yyyyMMdd"); + int d1 = Integer.parseInt(formatter.format(birthDate)); + int d2 = Integer.parseInt(formatter.format(currentDate)); + int age = (d2 - d1) / 10000; + return age; + } +} \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java b/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java new file mode 100644 index 0000000000..dcd261337c --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.date; + +import static org.junit.Assert.assertEquals; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Date; +import org.junit.jupiter.api.Test; + +public class AgeCalculatorUnitTest { + AgeCalculator ageCalculator = new AgeCalculator(); + + @Test + public void givenLocalDate_whenCalculateAge_thenOk() { + assertEquals(10, ageCalculator.calculateAge(LocalDate.of(2008, 5, 20), LocalDate.of(2018, 9, 20))); + } + + @Test + public void givenJodaTime_whenCalculateAge_thenOk() { + assertEquals(10, ageCalculator.calculateAgeWithJodaTime(new org.joda.time.LocalDate(2008, 5, 20), new org.joda.time.LocalDate(2018, 9, 20))); + } + + @Test + public void givenDate_whenCalculateAge_thenOk() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); + Date birthDate = sdf.parse("2008-05-20"); + Date currentDate = sdf.parse("2018-09-20"); + assertEquals(10, ageCalculator.calculateAgeWithJava7(birthDate, currentDate)); + } + +} \ No newline at end of file diff --git a/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java b/java-difference-date/src/test/java/com/baeldung/DateDiffUnitTest.java similarity index 98% rename from java-difference-date/src/test/java/com/baeldung/DateDiffTest.java rename to java-difference-date/src/test/java/com/baeldung/DateDiffUnitTest.java index 4203f7ef38..2c5323be6f 100644 --- a/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java +++ b/java-difference-date/src/test/java/com/baeldung/DateDiffUnitTest.java @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; -public class DateDiffTest { +public class DateDiffUnitTest { @Test public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml index 5490cd40f7..3d235e10a8 100644 --- a/java-ee-8-security-api/pom.xml +++ b/java-ee-8-security-api/pom.xml @@ -3,11 +3,16 @@ 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 java-ee-8-security-api 1.0-SNAPSHOT pom + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + @@ -53,10 +58,6 @@ - 1.8 - 1.8 - UTF-8 - 9080 9443 diff --git a/java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java b/java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java new file mode 100644 index 0000000000..e74de2cc67 --- /dev/null +++ b/java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java @@ -0,0 +1,21 @@ +package com.baeldung.percentage; + +import java.util.Scanner; + +public class PercentageCalculator { + + public double calculatePercentage(double obtained,double total){ + return obtained*100/total; + } + + public static void main(String[] args) { + PercentageCalculator pc = new PercentageCalculator(); + Scanner in = new Scanner(System.in); + System.out.println("Enter obtained marks:"); + double obtained = in.nextDouble(); + System.out.println("Enter total marks:"); + double total =in.nextDouble(); + System.out.println("Percentage obtained :"+pc.calculatePercentage(obtained,total)); + } + +} diff --git a/java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java b/java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java new file mode 100644 index 0000000000..202d4f8112 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.percentage; + +import org.junit.Assert; +import org.junit.Test; + +public class PercentageCalculatorUnitTest { + private PercentageCalculator pc = new PercentageCalculator(); + + @Test + public void whenPass2Integers_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected", + 50.0,pc.calculatePercentage(50,100),0.1); + } + + @Test + public void whenPassObtainedMarksAsDouble_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected",5.05, + pc.calculatePercentage(50.5,1000),0.1); + } + + @Test + public void whenPassTotalMarksAsDouble_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected",19.6, + pc.calculatePercentage(5,25.5),0.1); + } + + @Test + public void whenPass2DoubleNumbers_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected",20, + pc.calculatePercentage(5.5,27.5),0.1); + } + +} 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/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java similarity index 98% rename from core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java index 9f002c89a2..c5aa9a1651 100644 --- a/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.collection; +package com.baeldung.stream; import java.util.ArrayList; import java.util.List; diff --git a/java-strings/README.md b/java-strings/README.md index 233d986d98..249f1a351a 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -27,3 +27,6 @@ - [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) - [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) - [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string) +- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string) +- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) +- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) 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/JoinerSplitter.java b/java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java index 085be66801..cdbba1ef53 100644 --- a/java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java +++ b/java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java @@ -2,6 +2,7 @@ package com.baeldung.string; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -32,5 +33,12 @@ public class JoinerSplitter { .mapToObj(item -> (char) item) .collect(Collectors.toList()); } + + public static Map arrayToMap(String[] arrayOfString) { + return Arrays.asList(arrayOfString) + .stream() + .map(str -> str.split(":")) + .collect(Collectors.toMap(str -> str[0], str -> str[1])); + } } 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..3b0c32991c --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/StringPerformance.java @@ -0,0 +1,196 @@ +package com.baeldung.string; + +import com.google.common.base.Splitter; +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.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Measurement(batchSize = 100000, iterations = 10) +@Warmup(batchSize = 100000, iterations = 10) +@State(Scope.Thread) +public class StringPerformance { + + 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<>(); + + @Benchmark + public String benchmarkStringDynamicConcat() { + result += baeldung; + return result; + } + + @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() { + String result = new String("baeldung"); + return result; + } + + @Benchmark + public String benchmarkStringLiteral() { + String result = "baeldung"; + return result; + } + + @Benchmark + public String benchmarkStringFormat_s() { + return String.format(formatString, baeldung); + } + + @Benchmark + public String benchmarkStringConcat() { + result = result.concat(baeldung); + return result; + } + + @Benchmark + public String benchmarkStringIntern() { + return baeldung.intern(); + } + + @Benchmark + public String benchmarkStringReplace() { + return longString.replace("average", " average !!!"); + } + + @Benchmark + public String benchmarkStringUtilsReplace() { + return StringUtils.replace(longString, "average", " average !!!"); + } + + @Benchmark + public List benchmarkGuavaSplitter() { + return Splitter.on(" ").trimResults() + .omitEmptyStrings() + .splitToList(longString); + } + + @Benchmark + public String [] benchmarkStringSplit() { + return longString.split(emptyString); + } + + @Benchmark + public String [] benchmarkStringSplitPattern() { + return spacePattern.split(longString, 0); + } + + @Benchmark + public List benchmarkStringTokenizer() { + StringTokenizer st = new StringTokenizer(longString); + while (st.hasMoreTokens()) { + stringTokenizer.add(st.nextToken()); + } + return stringTokenizer; + } + + @Benchmark + public List benchmarkStringIndexOf() { + int pos = 0, end; + while ((end = longString.indexOf(' ', pos)) >= 0) { + stringSplit.add(longString.substring(pos, end)); + pos = end + 1; + } + return stringSplit; + } + + @Benchmark + public String benchmarkIntegerToString() { + return Integer.toString(sampleNumber); + } + + @Benchmark + public String benchmarkStringValueOf() { + return String.valueOf(sampleNumber); + } + + + @Benchmark + public String benchmarkStringConvertPlus() { + return sampleNumber + ""; + } + + @Benchmark + public String benchmarkStringFormat_d() { + return String.format(formatDigit, sampleNumber); + } + + @Benchmark + public boolean benchmarkStringEquals() { + return longString.equals(baeldung); + } + + + @Benchmark + public boolean benchmarkStringEqualsIgnoreCase() { + return longString.equalsIgnoreCase(baeldung); + } + + @Benchmark + public boolean benchmarkStringMatches() { + return longString.matches(baeldung); + } + + @Benchmark + public boolean benchmarkPrecompiledMatches() { + return longPattern.matcher(baeldung).matches(); + } + + @Benchmark + public int benchmarkStringCompareTo() { + return longString.compareTo(baeldung); + } + + @Benchmark + public boolean benchmarkStringIsEmpty() { + return longString.isEmpty(); + } + + @Benchmark + public boolean benchmarkStringLengthZero() { + return longString.length() == 0; + } + + 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/test/java/com/baeldung/string/JoinerSplitterUnitTest.java b/java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java index 8901bcf9db..a9488e27a4 100644 --- a/java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java @@ -3,7 +3,9 @@ package com.baeldung.string; import org.junit.Test; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; @@ -62,5 +64,20 @@ public class JoinerSplitterUnitTest { assertEquals(result, expectation); } + + @Test + public void givenStringArray_transformedToStream_convertToMap() { + + String[] programming_languages = new String[] {"language:java","os:linux","editor:emacs"}; + + Map expectation=new HashMap<>(); + expectation.put("language", "java"); + expectation.put("os", "linux"); + expectation.put("editor", "emacs"); + + Map result = JoinerSplitter.arrayToMap(programming_languages); + assertEquals(result, expectation); + + } } diff --git a/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java b/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java index 3859a2b26b..6157640a4a 100644 --- a/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java @@ -2,10 +2,11 @@ package com.baeldung.string; import static org.assertj.core.api.Assertions.assertThat; +import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.google.common.base.Splitter; @@ -54,4 +55,18 @@ public class SplitUnitTest { assertThat(resultList) .containsExactly("car", "jeep", "scooter"); } + + @Test + public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_Regex() { + assertThat(" car , jeep, scooter ".trim() + .split("\\s*,\\s*")).containsExactly("car", "jeep", "scooter"); + + } + + @Test + public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_java_8() { + assertThat(Arrays.stream(" car , jeep, scooter ".split(",")) + .map(String::trim) + .toArray(String[]::new)).containsExactly("car", "jeep", "scooter"); + } } 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/javaxval/pom.xml b/javaxval/pom.xml index 7af766261b..63cb4c1d1d 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -1,55 +1,73 @@ - - 4.0.0 - com.baeldung - javaxval - 0.1-SNAPSHOT - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - org.hibernate - hibernate-validator-annotation-processor - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish.web - javax.el - ${javax.el.version} - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-test - ${org.springframework.version} - - - - - 2.0.1.Final - 6.0.7.Final - 3.0.0 - 2.2.6 - 5.0.2.RELEASE - - + + 4.0.0 + com.baeldung + javaxval + 0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + javax.validation + validation-api + ${validation-api.version} + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + org.hibernate + hibernate-validator-annotation-processor + ${hibernate-validator.version} + + + javax.el + javax.el-api + ${javax.el-api.version} + + + org.glassfish.web + javax.el + ${javax.el.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-test + ${org.springframework.version} + + + junit + junit + ${junit.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 2.0.1.Final + 6.0.7.Final + 3.0.0 + 2.2.6 + 5.0.2.RELEASE + 4.12 + 3.11.1 + \ No newline at end of file diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java new file mode 100644 index 0000000000..c9f2ab6f98 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.javabeanconstraints.appplication; + +import javax.validation.Validation; +import javax.validation.Validator; +import org.baeldung.javabeanconstraints.entities.UserNotBlank; + +public class Application { + + public static void main(String[] args) throws Exception { + Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); + UserNotBlank user = new UserNotBlank(" "); + validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage())); + } +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java new file mode 100644 index 0000000000..2ea6a3af56 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java @@ -0,0 +1,22 @@ +package org.baeldung.javabeanconstraints.entities; + +import javax.validation.constraints.NotBlank; + +public class UserNotBlank { + + @NotBlank(message = "Name is mandatory") + private final String name; + + public UserNotBlank(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "User{" + "name=" + name + "}"; + } +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java new file mode 100644 index 0000000000..39e34b63d3 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java @@ -0,0 +1,22 @@ +package org.baeldung.javabeanconstraints.entities; + +import javax.validation.constraints.NotEmpty; + +public class UserNotEmpty { + + @NotEmpty(message = "Name is mandatory") + private final String name; + + public UserNotEmpty(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "User{" + "name=" + name + "}"; + } +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java new file mode 100644 index 0000000000..598c9ba9f9 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java @@ -0,0 +1,22 @@ +package org.baeldung.javabeanconstraints.entities; + +import javax.validation.constraints.NotNull; + +public class UserNotNull { + + @NotNull(message = "Name is mandatory") + private final String name; + + public UserNotNull(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "User{" + "name=" + name + "}"; + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java new file mode 100644 index 0000000000..954833fef1 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java @@ -0,0 +1,63 @@ +package org.baeldung.javabeanconstraints.test; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.javabeanconstraints.entities.UserNotBlank; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserNotBlankUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenNotBlankName_thenNoConstraintViolations() { + UserNotBlank user = new UserNotBlank("John"); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenBlankName_thenOneConstraintViolation() { + UserNotBlank user = new UserNotBlank(" "); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenEmptyName_thenOneConstraintViolation() { + UserNotBlank user = new UserNotBlank(""); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenNullName_thenOneConstraintViolation() { + UserNotBlank user = new UserNotBlank(null); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenToString_thenCorrect() { + UserNotBlank user = new UserNotBlank("John"); + + assertThat(user.toString()).isEqualTo("User{name=John}"); + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java new file mode 100644 index 0000000000..c2675ed8b6 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java @@ -0,0 +1,54 @@ +package org.baeldung.javabeanconstraints.test; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.javabeanconstraints.entities.UserNotEmpty; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserNotEmptyUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenNotEmptyName_thenNoConstraintViolations() { + UserNotEmpty user = new UserNotEmpty("John"); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenEmptyName_thenOneConstraintViolation() { + UserNotEmpty user = new UserNotEmpty(""); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenNullName_thenOneConstraintViolation() { + UserNotEmpty user = new UserNotEmpty(null); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenToString_thenCorrect() { + UserNotEmpty user = new UserNotEmpty("John"); + + assertThat(user.toString()).isEqualTo("User{name=John}"); + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java new file mode 100644 index 0000000000..3dd1811947 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java @@ -0,0 +1,54 @@ +package org.baeldung.javabeanconstraints.test; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.javabeanconstraints.entities.UserNotNull; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserNotNullUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenNotNullName_thenNoConstraintViolations() { + UserNotNull user = new UserNotNull("John"); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenNullName_thenOneConstraintViolation() { + UserNotNull user = new UserNotNull(null); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenEmptyName_thenNoConstraintViolations() { + UserNotNull user = new UserNotNull(""); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenToString_thenCorrect() { + UserNotNull user = new UserNotNull("John"); + + assertThat(user.toString()).isEqualTo("User{name=John}"); + } +} diff --git a/jee-7/pom.xml b/jee-7/pom.xml index 08c8b5a068..242fa778c0 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung jee-7 1.0-SNAPSHOT war diff --git a/jenkins/hello-world/pom.xml b/jenkins/hello-world/pom.xml index 5684deaea3..fb2154c7ad 100644 --- a/jenkins/hello-world/pom.xml +++ b/jenkins/hello-world/pom.xml @@ -7,13 +7,6 @@ hpi Hello World Plugin A sample Jenkins Hello World plugin - https://wiki.jenkins-ci.org/display/JENKINS/TODO+Plugin - - - MIT License - http://opensource.org/licenses/MIT - - org.jenkins-ci.plugins diff --git a/jersey/README.md b/jersey/README.md index 3121c560cf..1a7b541e92 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -1,2 +1,3 @@ - [Jersey Filters and Interceptors](http://www.baeldung.com/jersey-filters-interceptors) - [Jersey MVC Support](https://www.baeldung.com/jersey-mvc) +- [Set a Response Body in JAX-RS](https://www.baeldung.com/jax-rs-response) diff --git a/jersey/pom.xml b/jersey/pom.xml index e248f9cf90..b55bdc5330 100644 --- a/jersey/pom.xml +++ b/jersey/pom.xml @@ -39,6 +39,11 @@ jersey-mvc-freemarker ${jersey.version} + + org.glassfish.jersey.ext + jersey-bean-validation + ${jersey.version} + org.glassfish.jersey.test-framework jersey-test-framework-core diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java b/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java index d4744066c4..b6b9853aae 100644 --- a/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java +++ b/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java @@ -1,12 +1,14 @@ package com.baeldung.jersey.server.config; import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.server.mvc.freemarker.FreemarkerMvcFeature; public class ViewApplicationConfig extends ResourceConfig { public ViewApplicationConfig() { packages("com.baeldung.jersey.server"); + property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true); property(FreemarkerMvcFeature.TEMPLATE_BASE_PATH, "templates/freemarker"); register(FreemarkerMvcFeature.class);; } diff --git a/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java b/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java new file mode 100644 index 0000000000..ca49797e31 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java @@ -0,0 +1,35 @@ +package com.baeldung.jersey.server.constraints; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.regex.Pattern; + +import javax.validation.Constraint; +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import javax.validation.Payload; + +@Retention(RetentionPolicy.RUNTIME) +@Constraint(validatedBy = { SerialNumber.Validator.class }) +public @interface SerialNumber { + + String message() + + default "Fruit serial number is not valid"; + + Class[] groups() default {}; + + Class[] payload() default {}; + + public class Validator implements ConstraintValidator { + @Override + public void initialize(final SerialNumber serial) { + } + + @Override + public boolean isValid(final String serial, final ConstraintValidatorContext constraintValidatorContext) { + final String serialNumRegex = "^\\d{3}-\\d{3}-\\d{4}$"; + return Pattern.matches(serialNumRegex, serial); + } + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java index 30620e331d..c55362487b 100644 --- a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java +++ b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java @@ -1,20 +1,57 @@ package com.baeldung.jersey.server.model; +import javax.validation.constraints.Min; +import javax.validation.constraints.Size; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement public class Fruit { - private final String name; - private final String colour; + @Min(value = 10, message = "Fruit weight must be 10 or greater") + private Integer weight; + @Size(min = 5, max = 200) + private String name; + @Size(min = 5, max = 200) + private String colour; + private String serial; + + public Fruit() { + } public Fruit(String name, String colour) { this.name = name; this.colour = colour; } - + public String getName() { return name; } + + public void setName(String name) { + this.name = name; + } + + public void setColour(String colour) { + this.colour = colour; + } public String getColour() { return colour; } + + public Integer getWeight() { + return weight; + } + + public void setWeight(Integer weight) { + this.weight = weight; + } + + public String getSerial() { + return serial; + } + + public void setSerial(String serial) { + this.serial = serial; + } } diff --git a/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java b/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java new file mode 100644 index 0000000000..cea61c897b --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java @@ -0,0 +1,26 @@ +package com.baeldung.jersey.server.providers; + +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +public class FruitExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(final ConstraintViolationException exception) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(prepareMessage(exception)) + .type("text/plain") + .build(); + } + + private String prepareMessage(ConstraintViolationException exception) { + final StringBuilder message = new StringBuilder(); + for (ConstraintViolation cv : exception.getConstraintViolations()) { + message.append(cv.getPropertyPath() + " " + cv.getMessage() + "\n"); + } + return message.toString(); + } + +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java index 4e1fa4aa11..ee34cdd3ca 100644 --- a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java +++ b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java @@ -5,7 +5,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.FormParam; import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @@ -15,7 +21,9 @@ import org.glassfish.jersey.server.mvc.ErrorTemplate; import org.glassfish.jersey.server.mvc.Template; import org.glassfish.jersey.server.mvc.Viewable; +import com.baeldung.jersey.server.constraints.SerialNumber; import com.baeldung.jersey.server.model.Fruit; +import com.baeldung.jersey.service.SimpleStorageService; @Path("/fruit") public class FruitResource { @@ -52,4 +60,49 @@ public class FruitResource { return name; } + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + public void createFruit( + @NotNull(message = "Fruit name must not be null") @FormParam("name") String name, + @NotNull(message = "Fruit colour must not be null") @FormParam("colour") String colour) { + + Fruit fruit = new Fruit(name, colour); + SimpleStorageService.storeFruit(fruit); + } + + @PUT + @Path("/update") + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + public void updateFruit(@SerialNumber @FormParam("serial") String serial) { + Fruit fruit = new Fruit(); + fruit.setSerial(serial); + SimpleStorageService.storeFruit(fruit); + } + + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + public void createFruit(@Valid Fruit fruit) { + SimpleStorageService.storeFruit(fruit); + } + + @GET + @Valid + @Produces(MediaType.APPLICATION_JSON) + @Path("/search/{name}") + public Fruit findFruitByName(@PathParam("name") String name) { + return SimpleStorageService.findByName(name); + } + + @GET + @Produces(MediaType.TEXT_HTML) + @Path("/exception") + @Valid + public Fruit exception() { + Fruit fruit = new Fruit(); + fruit.setName("a"); + fruit.setColour("b"); + return fruit; + } } diff --git a/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java b/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java new file mode 100644 index 0000000000..e21dd584a1 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java @@ -0,0 +1,25 @@ +package com.baeldung.jersey.service; + +import java.util.HashMap; +import java.util.Map; + +import com.baeldung.jersey.server.model.Fruit; + +public class SimpleStorageService { + + private static final Map fruits = new HashMap(); + + public static void storeFruit(final Fruit fruit) { + fruits.put(fruit.getName(), fruit); + } + + public static Fruit findByName(final String name) { + return fruits.entrySet() + .stream() + .filter(map -> name.equals(map.getKey())) + .map(map -> map.getValue()) + .findFirst() + .get(); + } + +} diff --git a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java index a0b6daed51..2eeb5710cb 100644 --- a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java +++ b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java @@ -2,41 +2,116 @@ package com.baeldung.jersey.server.rest; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Assert; +import org.glassfish.jersey.test.TestProperties; import org.junit.Test; import com.baeldung.jersey.server.config.ViewApplicationConfig; +import com.baeldung.jersey.server.model.Fruit; +import com.baeldung.jersey.server.providers.FruitExceptionMapper; public class FruitResourceIntegrationTest extends JerseyTest { @Override protected Application configure() { - return new ViewApplicationConfig(); + enable(TestProperties.LOG_TRAFFIC); + enable(TestProperties.DUMP_ENTITY); + + ViewApplicationConfig config = new ViewApplicationConfig(); + config.register(FruitExceptionMapper.class); + return config; } @Test - public void testAllFruit() { + public void givenGetAllFruit_whenCorrectRequest_thenAllTemplateInvoked() { final String response = target("/fruit/all").request() .get(String.class); - Assert.assertThat(response, allOf(containsString("banana"), containsString("apple"), containsString("kiwi"))); + assertThat(response, allOf(containsString("banana"), containsString("apple"), containsString("kiwi"))); } @Test - public void testIndex() { + public void givenGetFruit_whenCorrectRequest_thenIndexTemplateInvoked() { final String response = target("/fruit").request() .get(String.class); - Assert.assertThat(response, containsString("Welcome Fruit Index Page!")); + assertThat(response, containsString("Welcome Fruit Index Page!")); } @Test - public void testErrorTemplate() { + public void givenGetFruitByName_whenFruitUnknown_thenErrorTemplateInvoked() { final String response = target("/fruit/orange").request() .get(String.class); - Assert.assertThat(response, containsString("Error - Fruit not found: orange!")); + assertThat(response, containsString("Error - Fruit not found: orange!")); + } + + @Test + public void givenCreateFruit_whenFormContainsNullParam_thenResponseCodeIsBadRequest() { + Form form = new Form(); + form.param("name", "apple"); + form.param("colour", null); + Response response = target("fruit/create").request(MediaType.APPLICATION_FORM_URLENCODED) + .post(Entity.form(form)); + + assertEquals("Http Response should be 400 ", 400, response.getStatus()); + assertThat(response.readEntity(String.class), containsString("Fruit colour must not be null")); + } + + @Test + public void givenUpdateFruit_whenFormContainsBadSerialParam_thenResponseCodeIsBadRequest() { + Form form = new Form(); + form.param("serial", "2345-2345"); + + Response response = target("fruit/update").request(MediaType.APPLICATION_FORM_URLENCODED) + .put(Entity.form(form)); + + assertEquals("Http Response should be 400 ", 400, response.getStatus()); + assertThat(response.readEntity(String.class), containsString("Fruit serial number is not valid")); + } + + @Test + public void givenCreateFruit_whenFruitIsInvalid_thenResponseCodeIsBadRequest() { + Fruit fruit = new Fruit("Blueberry", "purple"); + fruit.setWeight(1); + + Response response = target("fruit/create").request(MediaType.APPLICATION_JSON_TYPE) + .post(Entity.entity(fruit, MediaType.APPLICATION_JSON_TYPE)); + + assertEquals("Http Response should be 400 ", 400, response.getStatus()); + assertThat(response.readEntity(String.class), containsString("Fruit weight must be 10 or greater")); + } + + @Test + public void givenFruitExists_whenSearching_thenResponseContainsFruit() { + Fruit fruit = new Fruit(); + fruit.setName("strawberry"); + fruit.setWeight(20); + Response response = target("fruit/create").request(MediaType.APPLICATION_JSON_TYPE) + .post(Entity.entity(fruit, MediaType.APPLICATION_JSON_TYPE)); + + assertEquals("Http Response should be 204 ", 204, response.getStatus()); + + final String json = target("fruit/search/strawberry").request() + .get(String.class); + assertThat(json, containsString("{\"name\":\"strawberry\",\"weight\":20}")); + } + + @Test + public void givenFruit_whenFruitIsInvalid_thenReponseContainsCustomExceptions() { + final Response response = target("fruit/exception").request() + .get(); + + assertEquals("Http Response should be 400 ", 400, response.getStatus()); + String responseString = response.readEntity(String.class); + assertThat(responseString, containsString("exception..colour size must be between 5 and 200")); + assertThat(responseString, containsString("exception..name size must be between 5 and 200")); } } diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index c52def554f..b05979b9c5 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -1,17 +1,15 @@ - + 4.0.0 - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + jhipster-microservice + com.baeldung.jhipster + 1.0.0-SNAPSHOT + com.car.app car-app - 0.0.1-SNAPSHOT war car-app @@ -37,9 +35,11 @@ 0.7.0 3.6 2.0.0 + 3.6.2 4.8 jdt_apt 1.1.0.Final + 2.10 1.4.1 3.0.1 yyyyMMddHHmmss @@ -186,12 +186,10 @@ commons-io commons-io - ${commons-io.version} io.dropwizard.metrics metrics-annotation - ${dropwizard-metrics.version} io.dropwizard.metrics @@ -200,17 +198,14 @@ io.dropwizard.metrics metrics-json - ${dropwizard-metrics.version} io.dropwizard.metrics metrics-jvm - ${dropwizard-metrics.version} io.dropwizard.metrics metrics-servlet - ${dropwizard-metrics.version} io.dropwizard.metrics @@ -505,8 +500,6 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - ${maven.compiler.source} - ${maven.compiler.target} org.mapstruct @@ -519,6 +512,7 @@ org.apache.maven.plugins maven-eclipse-plugin + ${maven-eclipse-plugin.version} true true diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index a9366e9bd3..803a0f62e6 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -1,54 +1,113 @@ - + 4.0.0 + + + jhipster-microservice + com.baeldung.jhipster + 1.0.0-SNAPSHOT + + com.dealer.app dealer-app - 0.0.1-SNAPSHOT war dealer-app - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 - + + ${maven.version} + + + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 2.5 + 3.5 + 0.4.13 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + - - io.github.jhipster - jhipster - ${jhipster.server.version} - - - io.dropwizard.metrics - metrics-core - - - io.dropwizard.metrics - metrics-annotation - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-json - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-jvm - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-servlet - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-servlets - com.fasterxml.jackson.datatype jackson-datatype-hibernate5 @@ -59,11 +118,11 @@ com.fasterxml.jackson.datatype - jackson-datatype-jsr310 + jackson-datatype-json-org com.fasterxml.jackson.datatype - jackson-datatype-json-org + jackson-datatype-jsr310 com.h2database @@ -82,34 +141,12 @@ com.hazelcast hazelcast-spring - - org.awaitility - awaitility - ${awaitility.version} - test - com.jayway.jsonpath json-path test - - io.springfox - springfox-swagger2 - ${springfox.version} - - - org.mapstruct - mapstruct - - - - - io.springfox - springfox-bean-validators - ${springfox.version} - com.mattbertolini liquibase-slf4j @@ -121,16 +158,16 @@ ${metrics-spring.version} - com.codahale.metrics metrics-annotation + com.codahale.metrics - com.codahale.metrics metrics-core + com.codahale.metrics - com.codahale.metrics metrics-healthchecks + com.codahale.metrics @@ -148,12 +185,56 @@ commons-io commons-io - ${commons-io.version} - org.apache.commons - commons-lang3 - ${commons-lang.version} + io.dropwizard.metrics + metrics-annotation + + + io.dropwizard.metrics + metrics-core + + + io.dropwizard.metrics + metrics-json + + + io.dropwizard.metrics + metrics-jvm + + + io.dropwizard.metrics + metrics-servlet + + + io.dropwizard.metrics + metrics-servlets + + + io.github.jhipster + jhipster + ${jhipster.server.version} + + + io.jsonwebtoken + jjwt + ${jjwt.version} + + + io.springfox + springfox-bean-validators + ${springfox.version} + + + io.springfox + springfox-swagger2 + ${springfox.version} + + + mapstruct + org.mapstruct + + javax.cache @@ -163,11 +244,41 @@ mysql mysql-connector-java + + net.logstash.logback + logstash-logback-encoder + ${logstash-logback-encoder.version} + + + logback-core + ch.qos.logback + + + logback-classic + ch.qos.logback + + + logback-access + ch.qos.logback + + + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + org.assertj assertj-core test + + org.awaitility + awaitility + ${awaitility.version} + test + org.hibernate hibernate-envers @@ -216,6 +327,10 @@ org.springframework.boot spring-boot-starter-aop + + org.springframework.boot + spring-boot-starter-cloud-connectors + org.springframework.boot spring-boot-starter-data-jpa @@ -232,16 +347,6 @@ org.springframework.boot spring-boot-starter-security - - org.springframework.security - spring-security-test - test - - - org.springframework.boot - spring-boot-test - test - org.springframework.boot spring-boot-starter-thymeleaf @@ -251,15 +356,15 @@ spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat + org.springframework.boot - io.jsonwebtoken - jjwt - ${jjwt.version} + org.springframework.boot + spring-boot-test + test @@ -268,19 +373,31 @@ org.springframework.cloud - spring-cloud-starter-ribbon - - - - io.netty - netty-transport-native-epoll - - + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.cloud + spring-cloud-starter-feign org.springframework.cloud spring-cloud-starter-hystrix + + org.springframework.cloud + spring-cloud-starter-ribbon + + + + netty-transport-native-epoll + io.netty + + + org.springframework.cloud spring-cloud-starter-spectator @@ -289,51 +406,51 @@ org.springframework.retry spring-retry - - org.springframework.cloud - spring-cloud-starter-eureka - - - org.springframework.cloud - spring-cloud-starter-config - - - org.springframework.cloud - spring-cloud-starter-feign - - - net.logstash.logback - logstash-logback-encoder - ${logstash-logback-encoder.version} - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-access - - - - - org.springframework.boot - spring-boot-starter-cloud-connectors - org.springframework.security spring-security-data + + org.springframework.security + spring-security-test + test + spring-boot:run + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + prepare-agent + + + + + + + + + + + + com.github.ekryd.sortpom @@ -356,6 +473,22 @@ false + + com.spotify + docker-maven-plugin + ${docker-maven-plugin.version} + + dealerapp + src/main/docker + + + / + ${project.build.directory} + ${project.build.finalName}.war + + + + org.apache.maven.plugins maven-compiler-plugin @@ -373,6 +506,7 @@ org.apache.maven.plugins maven-eclipse-plugin + ${maven-eclipse-plugin.version} true true @@ -479,28 +613,16 @@ - - org.sonarsource.scanner.maven - sonar-maven-plugin - ${sonar-maven-plugin.version} - org.liquibase liquibase-maven-plugin ${liquibase.version} - - src/main/resources/config/liquibase/master.xml - src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml - org.h2.Driver - jdbc:h2:file:./target/h2db/db/dealerapp - - dealerapp - - hibernate:spring:com.dealer.app.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy - true - debug - + + javax.validation + validation-api + ${validation-api.version} + org.javassist javassist @@ -516,12 +638,24 @@ spring-boot-starter-data-jpa ${project.parent.version} - - javax.validation - validation-api - ${validation-api.version} - + + src/main/resources/config/liquibase/master.xml + src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml + org.h2.Driver + jdbc:h2:file:./target/h2db/db/dealerapp + + dealerapp + + hibernate:spring:com.dealer.app.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy + true + debug + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + ${sonar-maven-plugin.version} org.springframework.boot @@ -532,58 +666,8 @@ - - com.spotify - docker-maven-plugin - ${docker-maven-plugin.version} - - dealerapp - src/main/docker - - - / - ${project.build.directory} - ${project.build.finalName}.war - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.jacoco - - jacoco-maven-plugin - - - ${jacoco-maven-plugin.version} - - - prepare-agent - - - - - - - - - - - - @@ -604,24 +688,12 @@ true - - - org.springframework.boot - spring-boot-starter-undertow - - - org.springframework.boot - spring-boot-devtools - true - - org.apache.maven.plugins maven-war-plugin - - + @@ -631,15 +703,20 @@ dev${profile.no-liquibase} - - - prod + + org.springframework.boot + spring-boot-devtools + true + org.springframework.boot spring-boot-starter-undertow + + + prod @@ -655,15 +732,11 @@ org.apache.maven.plugins maven-war-plugin - - + org.springframework.boot spring-boot-maven-plugin - - true - @@ -671,6 +744,9 @@ + + true + @@ -680,56 +756,20 @@ prod${profile.swagger}${profile.no-liquibase} + + + org.springframework.boot + spring-boot-starter-undertow + + cc - - - org.springframework.boot - spring-boot-starter-undertow - - - org.springframework.boot - spring-boot-devtools - true - - - - org.apache.maven.plugins - maven-war-plugin - - src/main/webapp/ - - - - org.springframework.boot - spring-boot-maven-plugin - - true - true - true - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - default-compile - none - - - default-testCompile - none - - - net.alchim31.maven scala-maven-plugin @@ -758,6 +798,37 @@ ${scala.version} + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + none + + + default-testCompile + none + + + + + org.apache.maven.plugins + maven-war-plugin + + src/main/webapp/ + + + + org.springframework.boot + spring-boot-maven-plugin + + true + true + true + + + @@ -766,6 +837,17 @@ dev,swagger + + + org.springframework.boot + spring-boot-devtools + true + + + org.springframework.boot + spring-boot-starter-undertow + + @@ -788,12 +870,12 @@ io.prometheus - simpleclient_servlet + simpleclient_dropwizard ${prometheus-simpleclient.version} io.prometheus - simpleclient_dropwizard + simpleclient_servlet ${prometheus-simpleclient.version} @@ -811,96 +893,4 @@ - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - ${maven.version} - - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 4.8 - jdt_apt - 1.1.0.Final - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - 0.0.20 - - ${project.build.directory}/test-results - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index 0ae74e11bb..ed0c929027 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -1,53 +1,136 @@ - + 4.0.0 + + + jhipster-microservice + com.baeldung.jhipster + 1.0.0-SNAPSHOT + + com.gateway gateway-app - 0.0.1-SNAPSHOT war gateway-app - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 - + + ${maven.version} + + + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 3.6.0 + 1.10 + 2.5 + 3.5 + 0.4.13 + 1.3 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + 1.3.0 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + - io.github.jhipster - jhipster - ${jhipster.server.version} + com.datastax.cassandra + cassandra-driver-core + + + metrics-core + com.codahale.metrics + + - io.dropwizard.metrics - metrics-core + com.datastax.cassandra + cassandra-driver-extras + ${cassandra-driver.version} - io.dropwizard.metrics - metrics-annotation - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-json - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-jvm - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-servlet - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-servlets + com.datastax.cassandra + cassandra-driver-mapping com.fasterxml.jackson.datatype @@ -59,11 +142,11 @@ com.fasterxml.jackson.datatype - jackson-datatype-jsr310 + jackson-datatype-json-org com.fasterxml.jackson.datatype - jackson-datatype-json-org + jackson-datatype-jsr310 com.h2database @@ -82,34 +165,12 @@ com.hazelcast hazelcast-spring - - org.awaitility - awaitility - ${awaitility.version} - test - com.jayway.jsonpath json-path test - - io.springfox - springfox-swagger2 - ${springfox.version} - - - org.mapstruct - mapstruct - - - - - io.springfox - springfox-bean-validators - ${springfox.version} - com.mattbertolini liquibase-slf4j @@ -121,16 +182,16 @@ ${metrics-spring.version} - com.codahale.metrics metrics-annotation + com.codahale.metrics - com.codahale.metrics metrics-core + com.codahale.metrics - com.codahale.metrics metrics-healthchecks + com.codahale.metrics @@ -148,17 +209,60 @@ commons-codec commons-codec - ${commons-codec.version} commons-io commons-io - ${commons-io.version} - org.apache.commons - commons-lang3 - ${commons-lang.version} + io.dropwizard.metrics + metrics-annotation + + + io.dropwizard.metrics + metrics-core + + + io.dropwizard.metrics + metrics-json + + + io.dropwizard.metrics + metrics-jvm + + + io.dropwizard.metrics + metrics-servlet + + + io.dropwizard.metrics + metrics-servlets + + + io.github.jhipster + jhipster + ${jhipster.server.version} + + + io.jsonwebtoken + jjwt + ${jjwt.version} + + + io.springfox + springfox-bean-validators + ${springfox.version} + + + io.springfox + springfox-swagger2 + ${springfox.version} + + + mapstruct + org.mapstruct + + javax.cache @@ -173,11 +277,41 @@ lz4 ${lz4.version} + + net.logstash.logback + logstash-logback-encoder + ${logstash-logback-encoder.version} + + + logback-core + ch.qos.logback + + + logback-classic + ch.qos.logback + + + logback-access + ch.qos.logback + + + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + org.assertj assertj-core test + + org.awaitility + awaitility + ${awaitility.version} + test + org.hibernate hibernate-envers @@ -226,6 +360,10 @@ org.springframework.boot spring-boot-starter-aop + + org.springframework.boot + spring-boot-starter-cloud-connectors + org.springframework.boot spring-boot-starter-data-jpa @@ -247,16 +385,6 @@ spring-boot-starter-test test - - org.springframework.security - spring-security-test - test - - - org.springframework.boot - spring-boot-test - test - org.springframework.boot spring-boot-starter-thymeleaf @@ -266,40 +394,15 @@ spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat + org.springframework.boot - io.jsonwebtoken - jjwt - ${jjwt.version} - - - - com.datastax.cassandra - cassandra-driver-core - - - com.codahale.metrics - metrics-core - - - - - com.datastax.cassandra - cassandra-driver-extras - ${cassandra-driver.version} - - - com.datastax.cassandra - cassandra-driver-mapping - - - - org.springframework.cloud - spring-cloud-starter-zuul + org.springframework.boot + spring-boot-test + test org.springframework.cloud @@ -307,72 +410,105 @@ org.springframework.cloud - spring-cloud-starter-ribbon - - - - io.netty - netty-transport-native-epoll - - - - - org.springframework.cloud - spring-cloud-starter-hystrix - - - org.springframework.cloud - spring-cloud-starter-spectator - - - org.springframework.retry - spring-retry + spring-cloud-starter-config org.springframework.cloud spring-cloud-starter-eureka - - org.springframework.cloud - spring-cloud-starter-config - org.springframework.cloud spring-cloud-starter-feign - net.logstash.logback - logstash-logback-encoder - ${logstash-logback-encoder.version} + org.springframework.cloud + spring-cloud-starter-hystrix + + + org.springframework.cloud + spring-cloud-starter-ribbon + - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-access + netty-transport-native-epoll + io.netty - org.springframework.boot - spring-boot-starter-cloud-connectors + org.springframework.cloud + spring-cloud-starter-spectator + + + + org.springframework.cloud + spring-cloud-starter-zuul + + + org.springframework.retry + spring-retry org.springframework.security spring-security-data + + org.springframework.security + spring-security-test + test + spring-boot:run + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + prepare-agent + + + + + + + + + com.github.eirslett + frontend-maven-plugin + ${frontend-maven-plugin.version} + + install-node-and-yarn + yarn + bower + gulp + + + + + + + + + + + + com.github.ekryd.sortpom @@ -395,6 +531,22 @@ false + + com.spotify + docker-maven-plugin + ${docker-maven-plugin.version} + + gateway + src/main/docker + + + / + ${project.build.directory} + ${project.build.finalName}.war + + + + org.apache.maven.plugins maven-compiler-plugin @@ -412,6 +564,7 @@ org.apache.maven.plugins maven-eclipse-plugin + ${maven-eclipse-plugin.version} true true @@ -518,28 +671,16 @@ - - org.sonarsource.scanner.maven - sonar-maven-plugin - ${sonar-maven-plugin.version} - org.liquibase liquibase-maven-plugin ${liquibase.version} - - src/main/resources/config/liquibase/master.xml - src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml - org.h2.Driver - jdbc:h2:file:./target/h2db/db/gateway - - gateway - - hibernate:spring:com.gateway.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy - true - debug - + + javax.validation + validation-api + ${validation-api.version} + org.javassist javassist @@ -555,12 +696,24 @@ spring-boot-starter-data-jpa ${project.parent.version} - - javax.validation - validation-api - ${validation-api.version} - + + src/main/resources/config/liquibase/master.xml + src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml + org.h2.Driver + jdbc:h2:file:./target/h2db/db/gateway + + gateway + + hibernate:spring:com.gateway.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy + true + debug + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + ${sonar-maven-plugin.version} org.springframework.boot @@ -571,74 +724,8 @@ - - com.spotify - docker-maven-plugin - ${docker-maven-plugin.version} - - gateway - src/main/docker - - - / - ${project.build.directory} - ${project.build.finalName}.war - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.jacoco - - jacoco-maven-plugin - - - ${jacoco-maven-plugin.version} - - - prepare-agent - - - - - - - - - com.github.eirslett - frontend-maven-plugin - ${frontend-maven-plugin.version} - - install-node-and-yarn - yarn - bower - gulp - - - - - - - - - - - - @@ -659,17 +746,6 @@ true - - - org.springframework.boot - spring-boot-starter-undertow - - - org.springframework.boot - spring-boot-devtools - true - - @@ -687,48 +763,22 @@ dev${profile.no-liquibase} - - - prod + + org.springframework.boot + spring-boot-devtools + true + org.springframework.boot spring-boot-starter-undertow + + + prod - - maven-clean-plugin - - - - target/www/ - - - - - - org.apache.maven.plugins - maven-war-plugin - - target/www/ - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - - build-info - - - - com.github.eirslett frontend-maven-plugin @@ -773,16 +823,47 @@ gulp test + test gulp - test test --no-notification + + maven-clean-plugin + + + + target/www/ + + + + + + org.apache.maven.plugins + maven-war-plugin + + target/www/ + + + + org.springframework.boot + spring-boot-maven-plugin + + + + build-info + + + + + true + + @@ -791,56 +872,20 @@ prod${profile.swagger}${profile.no-liquibase} + + + org.springframework.boot + spring-boot-starter-undertow + + cc - - - org.springframework.boot - spring-boot-starter-undertow - - - org.springframework.boot - spring-boot-devtools - true - - - - org.apache.maven.plugins - maven-war-plugin - - src/main/webapp/ - - - - org.springframework.boot - spring-boot-maven-plugin - - true - true - true - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - default-compile - none - - - default-testCompile - none - - - net.alchim31.maven scala-maven-plugin @@ -869,6 +914,37 @@ ${scala.version} + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + none + + + default-testCompile + none + + + + + org.apache.maven.plugins + maven-war-plugin + + src/main/webapp/ + + + + org.springframework.boot + spring-boot-maven-plugin + + true + true + true + + + @@ -877,6 +953,17 @@ dev,swagger + + + org.springframework.boot + spring-boot-devtools + true + + + org.springframework.boot + spring-boot-starter-undertow + + @@ -899,12 +986,12 @@ io.prometheus - simpleclient_servlet + simpleclient_dropwizard ${prometheus-simpleclient.version} io.prometheus - simpleclient_dropwizard + simpleclient_servlet ${prometheus-simpleclient.version} @@ -922,99 +1009,4 @@ - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - ${maven.version} - - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 1.10 - 2.5 - 3.5 - 0.4.13 - 1.3 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 4.8 - 1.3.0 - jdt_apt - 1.1.0.Final - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - 0.0.20 - - ${project.build.directory}/test-results - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - diff --git a/jhipster/jhipster-microservice/pom.xml b/jhipster/jhipster-microservice/pom.xml new file mode 100644 index 0000000000..4a60e47f87 --- /dev/null +++ b/jhipster/jhipster-microservice/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + jhipster-microservice + pom + JHipster Microservice + + + jhipster + com.baeldung.jhipster + 1.0.0-SNAPSHOT + + + + car-app + dealer-app + gateway-app + + diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index 9708b83a70..e242668759 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -6,10 +6,9 @@ JHipster Monolithic Application - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 + jhipster + com.baeldung.jhipster + 1.0.0-SNAPSHOT diff --git a/jhipster/pom.xml b/jhipster/pom.xml new file mode 100644 index 0000000000..2bf7bcb233 --- /dev/null +++ b/jhipster/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + com.baeldung.jhipster + jhipster + 1.0.0-SNAPSHOT + pom + JHipster + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + jhipster-monolithic + jhipster-microservice + + + diff --git a/jni/pom.xml b/jni/pom.xml index 274b9b58c3..d4cc409d33 100644 --- a/jni/pom.xml +++ b/jni/pom.xml @@ -1,21 +1,12 @@ 4.0.0 - com.baeldung jni - 0.0.1-SNAPSHOT - - - junit - junit - ${junit.version} - test - - - - - 4.8.1 - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + \ No newline at end of file diff --git a/jni/src/test/java/com/baeldung/jni/JNINativeTests.java b/jni/src/test/java/com/baeldung/jni/JNINativeManualTest.java similarity index 98% rename from jni/src/test/java/com/baeldung/jni/JNINativeTests.java rename to jni/src/test/java/com/baeldung/jni/JNINativeManualTest.java index 42e572d41b..8201945644 100644 --- a/jni/src/test/java/com/baeldung/jni/JNINativeTests.java +++ b/jni/src/test/java/com/baeldung/jni/JNINativeManualTest.java @@ -7,7 +7,7 @@ import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; -public class JNINativeTests { +public class JNINativeManualTest { @Before public void setup() { diff --git a/jooby/pom.xml b/jooby/pom.xml index 2867b7f4b6..83dd650701 100644 --- a/jooby/pom.xml +++ b/jooby/pom.xml @@ -1,60 +1,63 @@ - 4.0.0 - jooby - com.baeldung.jooby - 1.0 - jooby + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + jooby + com.baeldung.jooby + 1.0 + jooby - - org.jooby - modules - 1.1.3 - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - org.jooby - jooby-netty - - - org.jooby - jooby-jedis - ${jooby-jedis.version} - - - ch.qos.logback - logback-classic - - - junit - junit - test - - - io.rest-assured - rest-assured - test - - + + + + org.jooby + modules + ${jooby.version} + pom + + + - - - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - - + + + org.jooby + jooby-netty + ${jooby.version} + + + org.jooby + jooby-jedis + ${jooby.version} + + + io.rest-assured + rest-assured + test + ${rest-assured.version} + + - - 1.1.3 - com.baeldung.jooby.App - 1.1.3 - - 2.4.3 - + + + + org.apache.maven.plugins + maven-shade-plugin + ${maven-shade-plugin.version} + + + + + + 1.1.3 + 3.1.1 + com.baeldung.jooby.App + 2.4.3 + diff --git a/jooby/src/test/java/com/baeldung/jooby/AppTest.java b/jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java similarity index 96% rename from jooby/src/test/java/com/baeldung/jooby/AppTest.java rename to jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java index af2626c046..ab7388f5f4 100644 --- a/jooby/src/test/java/com/baeldung/jooby/AppTest.java +++ b/jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java @@ -9,7 +9,7 @@ import org.jooby.test.MockRouter; import org.junit.ClassRule; import org.junit.Test; -public class AppTest { +public class AppUnitTest { @ClassRule public static JoobyRule app = new JoobyRule(new App()); diff --git a/jta/README.md b/jta/README.md new file mode 100644 index 0000000000..445a291c8f --- /dev/null +++ b/jta/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Guide to Java EE JTA](https://www.baeldung.com/jee-jta) diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md index ce30c71792..30c4d03ded 100644 --- a/kotlin-libraries/README.md +++ b/kotlin-libraries/README.md @@ -6,5 +6,4 @@ - [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek) - [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson) - [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor) -- [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging) -- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence) \ No newline at end of file +- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 2b83328295..5b34a903ce 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -147,7 +147,6 @@ jmapper-core ${jmapper.version} - org.apache.crunch @@ -185,7 +184,72 @@ - + + org.apache.flink + flink-connector-kafka-0.11_2.11 + ${flink.version} + + + org.apache.flink + flink-streaming-java_2.11 + ${flink.version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + org.apache.flink + flink-core + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-java + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-test-utils_2.11 + ${flink.version} + test + + + org.assertj + assertj-core + ${assertj.version} + + + org.awaitility + awaitility + ${awaitility.version} + test + + + org.awaitility + awaitility-proxy + ${awaitility.version} + test + + @@ -336,6 +400,10 @@ 2.4.0 2.8.2 1.1.0 + 1.5.0 + 2.8.5 + 3.0.0 + 3.6.2 3.8.4 1.8 3.0.0 diff --git a/libraries/src/main/java/com/baeldung/flink/FlinkDataPipeline.java b/libraries-data/src/main/java/com/baeldung/flink/FlinkDataPipeline.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/FlinkDataPipeline.java rename to libraries-data/src/main/java/com/baeldung/flink/FlinkDataPipeline.java diff --git a/libraries/src/main/java/com/baeldung/flink/LineSplitter.java b/libraries-data/src/main/java/com/baeldung/flink/LineSplitter.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/LineSplitter.java rename to libraries-data/src/main/java/com/baeldung/flink/LineSplitter.java diff --git a/libraries/src/main/java/com/baeldung/flink/WordCount.java b/libraries-data/src/main/java/com/baeldung/flink/WordCount.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/WordCount.java rename to libraries-data/src/main/java/com/baeldung/flink/WordCount.java diff --git a/libraries/src/main/java/com/baeldung/flink/connector/Consumers.java b/libraries-data/src/main/java/com/baeldung/flink/connector/Consumers.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/connector/Consumers.java rename to libraries-data/src/main/java/com/baeldung/flink/connector/Consumers.java diff --git a/libraries/src/main/java/com/baeldung/flink/connector/Producers.java b/libraries-data/src/main/java/com/baeldung/flink/connector/Producers.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/connector/Producers.java rename to libraries-data/src/main/java/com/baeldung/flink/connector/Producers.java diff --git a/libraries/src/main/java/com/baeldung/flink/model/Backup.java b/libraries-data/src/main/java/com/baeldung/flink/model/Backup.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/model/Backup.java rename to libraries-data/src/main/java/com/baeldung/flink/model/Backup.java diff --git a/libraries/src/main/java/com/baeldung/flink/model/InputMessage.java b/libraries-data/src/main/java/com/baeldung/flink/model/InputMessage.java similarity index 99% rename from libraries/src/main/java/com/baeldung/flink/model/InputMessage.java rename to libraries-data/src/main/java/com/baeldung/flink/model/InputMessage.java index 183fa69c11..b3f75256ae 100644 --- a/libraries/src/main/java/com/baeldung/flink/model/InputMessage.java +++ b/libraries-data/src/main/java/com/baeldung/flink/model/InputMessage.java @@ -18,7 +18,6 @@ public class InputMessage { public String getSender() { return sender; } - public void setSender(String sender) { this.sender = sender; } diff --git a/libraries/src/main/java/com/baeldung/flink/operator/BackupAggregator.java b/libraries-data/src/main/java/com/baeldung/flink/operator/BackupAggregator.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/operator/BackupAggregator.java rename to libraries-data/src/main/java/com/baeldung/flink/operator/BackupAggregator.java diff --git a/libraries/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java b/libraries-data/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java rename to libraries-data/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java diff --git a/libraries/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java b/libraries-data/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java rename to libraries-data/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java diff --git a/libraries/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java b/libraries-data/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java rename to libraries-data/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java diff --git a/libraries/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java b/libraries-data/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java similarity index 89% rename from libraries/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java rename to libraries-data/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java index 1df456bbe5..9aaf8b9877 100644 --- a/libraries/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java +++ b/libraries-data/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java @@ -1,8 +1,6 @@ package com.baeldung.flink.schema; import com.baeldung.flink.model.InputMessage; -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.apache.flink.api.common.serialization.DeserializationSchema; diff --git a/libraries/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java 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..3077abc29c --- /dev/null +++ b/libraries-security/pom.xml @@ -0,0 +1,61 @@ + + + 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 + + + org.passay + passay + 1.3.1 + + + org.cryptacular + cryptacular + 1.2.2 + + + + + + 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/passay/NegativeMatchingRulesUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/NegativeMatchingRulesUnitTest.java new file mode 100644 index 0000000000..5054a5880e --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/NegativeMatchingRulesUnitTest.java @@ -0,0 +1,149 @@ +package com.baeldung.passay; + +import org.cryptacular.bean.EncodingHashBean; +import org.cryptacular.spec.CodecSpec; +import org.cryptacular.spec.DigestSpec; +import org.junit.Assert; +import org.junit.Test; +import org.passay.DictionaryRule; +import org.passay.DictionarySubstringRule; +import org.passay.DigestHistoryRule; +import org.passay.EnglishSequenceData; +import org.passay.HistoryRule; +import org.passay.IllegalCharacterRule; +import org.passay.IllegalRegexRule; +import org.passay.IllegalSequenceRule; +import org.passay.NumberRangeRule; +import org.passay.PasswordData; +import org.passay.PasswordValidator; +import org.passay.RepeatCharacterRegexRule; +import org.passay.RuleResult; +import org.passay.SourceRule; +import org.passay.UsernameRule; +import org.passay.WhitespaceRule; +import org.passay.dictionary.ArrayWordList; +import org.passay.dictionary.WordListDictionary; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class NegativeMatchingRulesUnitTest { + + @Test + public void givenDictionaryRules_whenValidatePassword_thenFoundIllegalWordsFromDictionary() { + ArrayWordList arrayWordList = new ArrayWordList(new String[] { "bar", "foobar" }); + + WordListDictionary wordListDictionary = new WordListDictionary(arrayWordList); + + DictionaryRule dictionaryRule = new DictionaryRule(wordListDictionary); + DictionarySubstringRule dictionarySubstringRule = new DictionarySubstringRule(wordListDictionary); + + PasswordValidator passwordValidator = new PasswordValidator(dictionaryRule, dictionarySubstringRule); + RuleResult validate = passwordValidator.validate(new PasswordData("foobar")); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_WORD:{matchingWord=foobar}", getDetail(validate, 0)); + assertEquals("ILLEGAL_WORD:{matchingWord=bar}", getDetail(validate, 1)); + } + + @Test + public void givenHistoryRule_whenValidatePassword_thenFoundIllegalWordsFromHistory() { + HistoryRule historyRule = new HistoryRule(); + + PasswordData passwordData = new PasswordData("123"); + passwordData.setPasswordReferences(new PasswordData.HistoricalReference("12345"), new PasswordData.HistoricalReference("1234"), new PasswordData.HistoricalReference("123")); + + PasswordValidator passwordValidator = new PasswordValidator(historyRule); + + RuleResult validate = passwordValidator.validate(passwordData); + + assertFalse(validate.isValid()); + assertEquals("HISTORY_VIOLATION:{historySize=3}", getDetail(validate, 0)); + } + + @Test + public void givenSeveralIllegalRules_whenValidatePassword_thenFoundSeveralIllegalPatterns() { + IllegalCharacterRule illegalCharacterRule = new IllegalCharacterRule(new char[] { 'a' }); + IllegalRegexRule illegalRegexRule = new IllegalRegexRule("\\w{2}\\d{2}"); + IllegalSequenceRule illegalSequenceRule = new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 3, true); + NumberRangeRule numberRangeRule = new NumberRangeRule(1, 10); + WhitespaceRule whitespaceRule = new WhitespaceRule(); + + PasswordValidator passwordValidator = new PasswordValidator(illegalCharacterRule, illegalRegexRule, illegalSequenceRule, numberRangeRule, whitespaceRule); + + RuleResult validate = passwordValidator.validate(new PasswordData("abcd22 ")); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_CHAR:{illegalCharacter=a, matchBehavior=contains}", getDetail(validate, 0)); + assertEquals("ILLEGAL_MATCH:{match=cd22, pattern=\\w{2}\\d{2}}", getDetail(validate, 1)); + assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=abc}", getDetail(validate, 2)); + assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=bcd}", getDetail(validate, 3)); + assertEquals("ILLEGAL_NUMBER_RANGE:{number=2, matchBehavior=contains}", getDetail(validate, 4)); + assertEquals("ILLEGAL_WHITESPACE:{whitespaceCharacter= , matchBehavior=contains}", getDetail(validate, 5)); + } + + @Test + public void givenSourceRule_whenValidatePassword_thenFoundIllegalWordsFromSource() { + SourceRule sourceRule = new SourceRule(); + + PasswordData passwordData = new PasswordData("password"); + passwordData.setPasswordReferences(new PasswordData.SourceReference("source", "password")); + + PasswordValidator passwordValidator = new PasswordValidator(sourceRule); + RuleResult validate = passwordValidator.validate(passwordData); + + assertFalse(validate.isValid()); + assertEquals("SOURCE_VIOLATION:{source=source}", getDetail(validate, 0)); + } + + @Test + public void givenRepeatCharacterRegexRuleRule_whenValidatePassword_thenFoundIllegalPatternMatches() { + RepeatCharacterRegexRule repeatCharacterRegexRule = new RepeatCharacterRegexRule(3); + + PasswordValidator passwordValidator = new PasswordValidator(repeatCharacterRegexRule); + + RuleResult validate = passwordValidator.validate(new PasswordData("aaabbb")); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_MATCH:{match=aaa, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 0)); + assertEquals("ILLEGAL_MATCH:{match=bbb, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 1)); + } + + @Test + public void givenUserNameRule_whenValidatePassword_thenFoundUserNameInPassword() { + PasswordValidator passwordValidator = new PasswordValidator(new UsernameRule()); + + PasswordData passwordData = new PasswordData("testuser1234"); + passwordData.setUsername("testuser"); + + RuleResult validate = passwordValidator.validate(passwordData); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_USERNAME:{username=testuser, matchBehavior=contains}", getDetail(validate, 0)); + } + + @Test + public void givenPasswordAndHashBeanAndEncryptedReferences_whenValidate_thenPasswordValidationShouldPass() { + List historicalReferences = Arrays.asList(new PasswordData.HistoricalReference("SHA256", "2e4551de804e27aacf20f9df5be3e8cd384ed64488b21ab079fb58e8c90068ab")); + PasswordData passwordData = new PasswordData("example!"); + passwordData.setPasswordReferences(historicalReferences); + + EncodingHashBean encodingHashBean = new EncodingHashBean(new CodecSpec("Base64"), new DigestSpec("SHA256"), 1, false); + + PasswordValidator passwordValidator = new PasswordValidator(new DigestHistoryRule(encodingHashBean)); + + RuleResult validate = passwordValidator.validate(passwordData); + + Assert.assertTrue(validate.isValid()); + } + + private String getDetail(RuleResult validate, int i) { + return validate.getDetails() + .get(i) + .toString(); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java new file mode 100644 index 0000000000..ff279e9317 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.passay; + +import org.junit.Assert; +import org.junit.Test; +import org.passay.CharacterData; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.PasswordGenerator; + +import java.util.stream.Stream; + +public class PasswordGeneratorUnitTest { + + @Test + public void givenDigitsGenerator_whenGeneratingPassword_thenPasswordContainsDigitsHasLength10() { + CharacterRule digits = new CharacterRule(EnglishCharacterData.Digit); + + PasswordGenerator passwordGenerator = new PasswordGenerator(); + String password = passwordGenerator.generatePassword(10, digits); + + Assert.assertTrue(password.length() == 10); + Assert.assertTrue(containsOnlyCharactersFromSet(password, "0123456789")); + } + + @Test + public void givenCustomizedRule_whenGenerating_thenGeneratedPasswordContainsCustomizedCharacters() { + CharacterRule specialCharacterRule = new CharacterRule(new CharacterData() { + @Override + public String getErrorCode() { + return "SAMPLE_ERROR_CODE"; + } + + @Override + public String getCharacters() { + return "ABCxyz123!@#"; + } + }); + + PasswordGenerator passwordGenerator = new PasswordGenerator(); + String password = passwordGenerator.generatePassword(10, specialCharacterRule); + + Assert.assertTrue(containsOnlyCharactersFromSet(password, "ABCxyz123!@#")); + } + + private boolean containsOnlyCharactersFromSet(String password, String setOfCharacters) { + return Stream.of(password.split("")) + .allMatch(it -> setOfCharacters.contains(it)); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java new file mode 100644 index 0000000000..3fc59a82d5 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java @@ -0,0 +1,81 @@ +package com.baeldung.passay; + +import org.junit.Assert; +import org.junit.Test; +import org.passay.LengthRule; +import org.passay.MessageResolver; +import org.passay.PasswordData; +import org.passay.PasswordValidator; +import org.passay.PropertiesMessageResolver; +import org.passay.RuleResult; +import org.passay.RuleResultDetail; +import org.passay.RuleResultMetadata; +import org.passay.WhitespaceRule; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class PasswordValidatorUnitTest { + + @Test + public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooShortPassword() { + PasswordData passwordData = new PasswordData("1234"); + + PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5)); + + RuleResult validate = passwordValidator.validate(passwordData); + assertEquals(false, validate.isValid()); + + RuleResultDetail ruleResultDetail = validate.getDetails() + .get(0); + assertEquals("TOO_SHORT", ruleResultDetail.getErrorCode()); + assertEquals(5, ruleResultDetail.getParameters() + .get("minimumLength")); + assertEquals(5, ruleResultDetail.getParameters() + .get("maximumLength")); + + Integer lengthCount = validate.getMetadata() + .getCounts() + .get(RuleResultMetadata.CountCategory.Length); + assertEquals(Integer.valueOf(4), lengthCount); + } + + @Test + public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooLongPassword() { + PasswordData passwordData = new PasswordData("123456"); + + PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5)); + + RuleResult validate = passwordValidator.validate(passwordData); + assertFalse(validate.isValid()); + Assert.assertEquals("TOO_LONG", validate.getDetails() + .get(0) + .getErrorCode()); + } + + @Test + public void givenPasswordValidatorWithLengthRule_whenValidation_thenCustomizedMeesagesAvailable() throws IOException { + URL resource = this.getClass() + .getClassLoader() + .getResource("messages.properties"); + Properties props = new Properties(); + props.load(new FileInputStream(resource.getPath())); + + MessageResolver resolver = new PropertiesMessageResolver(props); + PasswordValidator validator = new PasswordValidator(resolver, new LengthRule(8, 16), new WhitespaceRule()); + + RuleResult tooShort = validator.validate(new PasswordData("XXXX")); + RuleResult tooLong = validator.validate(new PasswordData("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ")); + + assertEquals("Password must not contain less characters than 16.", validator.getMessages(tooShort) + .get(0)); + assertEquals("Password must not have more characters than 16.", validator.getMessages(tooLong) + .get(0)); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java new file mode 100644 index 0000000000..0da1b43335 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.passay; + +import org.junit.Test; +import org.passay.AllowedCharacterRule; +import org.passay.AllowedRegexRule; +import org.passay.CharacterCharacteristicsRule; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.LengthComplexityRule; +import org.passay.LengthRule; +import org.passay.PasswordData; +import org.passay.PasswordValidator; +import org.passay.RuleResult; + +import static org.junit.Assert.*; + +public class PositiveMatchingRulesUnitTest { + + @Test + public void givenPasswordValidationRules_whenValidatingPassword_thenPosswordIsNotValidWithSeveralErrors() { + PasswordValidator passwordValidator = new PasswordValidator(new AllowedCharacterRule(new char[] { 'a', 'b', 'c' }), new AllowedRegexRule("\\d{2}\\w{10}"), new CharacterRule(EnglishCharacterData.LowerCase, 5), new LengthRule(8, 10)); + + RuleResult validate = passwordValidator.validate(new PasswordData("12abc")); + + assertFalse(validate.isValid()); + assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validate, 0)); + assertEquals("ALLOWED_CHAR:{illegalCharacter=2, matchBehavior=contains}", getDetail(validate, 1)); + assertEquals("ALLOWED_MATCH:{pattern=\\d{2}\\w{10}}", getDetail(validate, 2)); + assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, matchingCharacterCount=3, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=abc}", getDetail(validate, 3)); + assertEquals("TOO_SHORT:{minimumLength=8, maximumLength=10}", getDetail(validate, 4)); + } + + @Test + public void givenRulesForDifferentPasswordLength_whenValidatingTwoDifferentPassword_thenBothOfThemAreInvalid() { + PasswordData shortPassword = new PasswordData("12ab"); + PasswordData longPassword = new PasswordData("1234abcde"); + + LengthComplexityRule lengthComplexityRule = new LengthComplexityRule(); + lengthComplexityRule.addRules("[1,5]", new CharacterRule(EnglishCharacterData.LowerCase, 5)); + lengthComplexityRule.addRules("[6,10]", new AllowedCharacterRule(new char[] { 'a', 'b', 'c', 'd' })); + + PasswordValidator passwordValidator = new PasswordValidator(lengthComplexityRule); + + RuleResult validateShort = passwordValidator.validate(shortPassword); + RuleResult validateLong = passwordValidator.validate(longPassword); + + assertFalse(validateShort.isValid()); + assertFalse(validateLong.isValid()); + + assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=2, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=ab}", getDetail(validateShort, 0)); + assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validateLong, 0)); + } + + @Test + public void givenCharacterCharacteristicsRule_whenValidatingPassword_thenItIsInvalidAsItBreaksToManyRules() { + PasswordData shortPassword = new PasswordData(); + shortPassword.setPassword("12345abcde!"); + + CharacterCharacteristicsRule characterCharacteristicsRule = new CharacterCharacteristicsRule(4, new CharacterRule(EnglishCharacterData.LowerCase, 5), new CharacterRule(EnglishCharacterData.UpperCase, 5), new CharacterRule(EnglishCharacterData.Digit), + new CharacterRule(EnglishCharacterData.Special)); + + PasswordValidator passwordValidator = new PasswordValidator(characterCharacteristicsRule); + + RuleResult validate = passwordValidator.validate(shortPassword); + assertFalse(validate.isValid()); + + assertEquals("INSUFFICIENT_UPPERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=0, " + "validCharacters=ABCDEFGHIJKLMNOPQRSTUVWXYZ, " + "matchingCharacters=}", getDetail(validate, 0)); + assertEquals("INSUFFICIENT_CHARACTERISTICS:{" + "successCount=3, " + "minimumRequired=4, " + "ruleCount=4}", getDetail(validate, 1)); + } + + private String getDetail(RuleResult validate, int i) { + return validate.getDetails() + .get(i) + .toString(); + } +} diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java similarity index 67% rename from spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java rename to libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java index b362d72705..6565a5b085 100644 --- a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java +++ b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.scribejava; import org.junit.Test; import org.junit.runner.RunWith; @@ -7,10 +7,11 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class LogSinkApplicationIntegrationTest { +public class ScribejavaUnitTest { @Test - public void contextLoads() { + public void contextLoad(){ + } } diff --git a/libraries-security/src/test/resources/messages.properties b/libraries-security/src/test/resources/messages.properties new file mode 100644 index 0000000000..ad0039d71d --- /dev/null +++ b/libraries-security/src/test/resources/messages.properties @@ -0,0 +1,2 @@ +TOO_LONG=Password must not have more characters than %2$s. +TOO_SHORT=Password must not contain less characters than %2$s. \ No newline at end of file diff --git a/libraries/pom.xml b/libraries/pom.xml index 1a88acfb7b..91c54b6113 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -154,45 +154,7 @@ commons-dbutils ${commons.dbutils.version} - - org.apache.flink - flink-connector-kafka-0.11_2.11 - ${flink.version} - - - org.apache.flink - flink-streaming-java_2.11 - ${flink.version} - - - org.apache.flink - flink-core - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-java - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-test-utils_2.11 - ${flink.version} - test - org.apache.commons commons-math3 @@ -239,11 +201,7 @@ jackson-databind ${jackson.version} - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson.version} - + org.datanucleus @@ -900,7 +858,6 @@ 4.5.3 2.5 - 1.5.0 2.8.5 2.92 1.9.26 @@ -933,7 +890,7 @@ 2.5.5 1.23.0 v4-rev493-1.21.0 - 1.0.0 + 2.0.0 1.7.0 3.0.14 2.2.0 diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java b/libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java new file mode 100644 index 0000000000..7d4316e3ec --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java @@ -0,0 +1,8 @@ +package com.baeldung.commons.lang3.application; + +public class Application { + + public static void main(String[] args) { + + } +} diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java b/libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java new file mode 100644 index 0000000000..68aab46c33 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java @@ -0,0 +1,25 @@ +package com.baeldung.commons.lang3.beans; + +public class User { + + private final String name; + private final String email; + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "User{" + "name=" + name + ", email=" + email + '}'; + } +} diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java b/libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java new file mode 100644 index 0000000000..ae5d80244c --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java @@ -0,0 +1,11 @@ +package com.baeldung.commons.lang3.beans; + +import org.apache.commons.lang3.concurrent.LazyInitializer; + +public class UserInitializer extends LazyInitializer { + + @Override + protected User initialize() { + return new User("John", "john@domain.com"); + } +} 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/TransactionalWordCount.java b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java new file mode 100644 index 0000000000..0563ba6684 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java @@ -0,0 +1,105 @@ +package com.baeldung.kafka; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.consumer.OffsetAndMetadata; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.KafkaException; +import org.apache.kafka.common.TopicPartition; + +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; +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 TransactionalWordCount { + + 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 = createKafkaConsumer(); + KafkaProducer producer = createKafkaProducer(); + + producer.initTransactions(); + + try { + + while (true) { + + 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(); + + wordCountMap.forEach((key, value) -> producer.send(new ProducerRecord(OUTPUT_TOPIC, key, value.toString()))); + + Map offsetsToCommit = new HashMap<>(); + + for (TopicPartition partition : records.partitions()) { + List> partitionedRecords = records.records(partition); + long offset = partitionedRecords.get(partitionedRecords.size() - 1).offset(); + + offsetsToCommit.put(partition, new OffsetAndMetadata(offset + 1)); + } + + producer.sendOffsetsToTransaction(offsetsToCommit, CONSUMER_GROUP_ID); + producer.commitTransaction(); + + } + + } catch (KafkaException e) { + + producer.abortTransaction(); + + } + + + } + + 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"); + + KafkaConsumer consumer = new KafkaConsumer<>(props); + consumer.subscribe(singleton(INPUT_TOPIC)); + return consumer; + } + + 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-1"); + 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/libraries/src/main/java/com/baeldung/opencsv/examples/sync/BeanExamples.java b/libraries/src/main/java/com/baeldung/opencsv/examples/sync/BeanExamples.java index 76d044ca60..086f32677e 100644 --- a/libraries/src/main/java/com/baeldung/opencsv/examples/sync/BeanExamples.java +++ b/libraries/src/main/java/com/baeldung/opencsv/examples/sync/BeanExamples.java @@ -18,16 +18,19 @@ import java.util.List; public class BeanExamples { public static List beanBuilderExample(Path path, Class clazz) { + ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy(); + return beanBuilderExample(path, clazz, ms); + } + + public static List beanBuilderExample(Path path, Class clazz, MappingStrategy ms) { CsvTransfer csvTransfer = new CsvTransfer(); try { - ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy(); ms.setType(clazz); Reader reader = Files.newBufferedReader(path); - CsvToBean cb = new CsvToBeanBuilder(reader) - .withType(clazz) - .withMappingStrategy(ms) - .build(); + CsvToBean cb = new CsvToBeanBuilder(reader).withType(clazz) + .withMappingStrategy(ms) + .build(); csvTransfer.setCsvList(cb.parse()); reader.close(); @@ -40,11 +43,10 @@ public class BeanExamples { public static String writeCsvFromBean(Path path) { try { - Writer writer = new FileWriter(path.toString()); + Writer writer = new FileWriter(path.toString()); - StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer) - .withSeparator(CSVWriter.DEFAULT_SEPARATOR) - .build(); + StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer).withSeparator(CSVWriter.DEFAULT_SEPARATOR) + .build(); List list = new ArrayList<>(); list.add(new WriteExampleBean("Test1", "sfdsf", "fdfd")); diff --git a/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java index e46d8654a2..64e13a277e 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java @@ -42,4 +42,13 @@ public class BidiMapUnitTest { map.put("key1", "value1"); assertEquals(map.getKey("value1"), "key1"); } + + @Test + public void givenKeyValue_whenAddValue_thenReplaceFirstKey() { + BidiMap map = new DualHashBidiMap<>(); + map.put("key1", "value1"); + map.put("key2", "value1"); + assertEquals(map.size(), 1); + assertFalse(map.containsKey("key1")); + } } diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java new file mode 100644 index 0000000000..5eba736b4a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.commons.lang3.test; + +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.lang3.ArrayUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class ArrayUtilsUnitTest { + + @Test + public void givenArrayUtilsClass_whenCalledtoString_thenCorrect() { + String[] array = {"a", "b", "c"}; + assertThat(ArrayUtils.toString(array)).isEqualTo("{a,b,c}"); + } + + @Test + public void givenArrayUtilsClass_whenCalledtoStringIfArrayisNull_thenCorrect() { + String[] array = null; + assertThat(ArrayUtils.toString(array, "Array is null")).isEqualTo("Array is null"); + } + + @Test + public void givenArrayUtilsClass_whenCalledhashCode_thenCorrect() { + String[] array = {"a", "b", "c"}; + assertThat(ArrayUtils.hashCode(array)).isEqualTo(997619); + } + + @Test + public void givenArrayUtilsClass_whenCalledtoMap_thenCorrect() { + String[][] array = {{"1", "one", }, {"2", "two", }, {"3", "three"}}; + Map map = new HashMap(); + map.put("1", "one"); + map.put("2", "two"); + map.put("3", "three"); + assertThat(ArrayUtils.toMap(array)).isEqualTo(map); + } + + @Test + public void givenArrayUtilsClass_whenCallednullToEmptyStringArray_thenCorrect() { + String[] array = null; + assertThat(ArrayUtils.nullToEmpty(array)).isEmpty(); + } + + @Test + public void givenArrayUtilsClass_whenCallednullToEmptyObjectArray_thenCorrect() { + Object[] array = null; + assertThat(ArrayUtils.nullToEmpty(array)).isEmpty(); + } + + @Test + public void givenArrayUtilsClass_whenCalledsubarray_thenCorrect() { + int[] array = {1, 2, 3}; + int[] expected = {1}; + assertThat(ArrayUtils.subarray(array, 0, 1)).isEqualTo(expected); + } + + @Test + public void givenArrayUtilsClass_whenCalledisSameLength_thenCorrect() { + int[] array1 = {1, 2, 3}; + int[] array2 = {1, 2, 3}; + assertThat(ArrayUtils.isSameLength(array1, array2)).isTrue(); + } + + @Test + public void givenArrayUtilsClass_whenCalledreverse_thenCorrect() { + int[] array1 = {1, 2, 3}; + int[] array2 = {3, 2, 1}; + ArrayUtils.reverse(array1); + assertThat(array1).isEqualTo(array2); + } + + @Test + public void givenArrayUtilsClass_whenCalledIndexOf_thenCorrect() { + int[] array = {1, 2, 3}; + assertThat(ArrayUtils.indexOf(array, 1, 0)).isEqualTo(0); + } + + @Test + public void givenArrayUtilsClass_whenCalledcontains_thenCorrect() { + int[] array = {1, 2, 3}; + assertThat(ArrayUtils.contains(array, 1)).isTrue(); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java new file mode 100644 index 0000000000..f32980269a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class BasicThreadFactoryUnitTest { + + @Test + public void givenBasicThreadFactoryInstance_whenCalledBuilder_thenCorrect() { + BasicThreadFactory factory = new BasicThreadFactory.Builder() + .namingPattern("workerthread-%d") + .daemon(true) + .priority(Thread.MAX_PRIORITY) + .build(); + assertThat(factory).isInstanceOf(BasicThreadFactory.class); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java new file mode 100644 index 0000000000..f55f239d75 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.commons.lang3.test; + +import com.baeldung.commons.lang3.beans.User; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import org.apache.commons.lang3.reflect.ConstructorUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class ConstructorUtilsUnitTest { + + @Test + public void givenConstructorUtilsClass_whenCalledgetAccessibleConstructor_thenCorrect() { + assertThat(ConstructorUtils.getAccessibleConstructor(User.class, String.class, String.class)).isInstanceOf(Constructor.class); + } + + @Test + public void givenConstructorUtilsClass_whenCalledinvokeConstructor_thenCorrect() throws Exception { + assertThat(ConstructorUtils.invokeConstructor(User.class, "name", "email")).isInstanceOf(User.class); + } + + @Test + public void givenConstructorUtilsClass_whenCalledinvokeExactConstructor_thenCorrect() throws Exception { + String[] args = {"name", "email"}; + Class[] parameterTypes= {String.class, String.class}; + assertThat(ConstructorUtils.invokeExactConstructor(User.class, args, parameterTypes)).isInstanceOf(User.class); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java new file mode 100644 index 0000000000..8abb373e30 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.commons.lang3.test; + +import com.baeldung.commons.lang3.beans.User; +import org.apache.commons.lang3.reflect.FieldUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FieldUtilsUnitTest { + + private static User user; + + @BeforeClass + public static void setUpUserInstance() { + user = new User("Julie", "julie@domain.com"); + } + + @Test + public void givenFieldUtilsClass_whenCalledgetField_thenCorrect() { + assertThat(FieldUtils.getField(User.class, "name", true).getName()).isEqualTo("name"); + } + + @Test + public void givenFieldUtilsClass_whenCalledgetFieldForceAccess_thenCorrect() { + assertThat(FieldUtils.getField(User.class, "name", true).getName()).isEqualTo("name"); + } + + @Test + public void givenFieldUtilsClass_whenCalledgetDeclaredFieldForceAccess_thenCorrect() { + assertThat(FieldUtils.getDeclaredField(User.class, "name", true).getName()).isEqualTo("name"); + } + + @Test + public void givenFieldUtilsClass_whenCalledgetAllField_thenCorrect() { + assertThat(FieldUtils.getAllFields(User.class).length).isEqualTo(2); + } + + @Test + public void givenFieldUtilsClass_whenCalledreadField_thenCorrect() throws IllegalAccessException { + assertThat(FieldUtils.readField(user, "name", true)).isEqualTo("Julie"); + } + + @Test + public void givenFieldUtilsClass_whenCalledreadDeclaredField_thenCorrect() throws IllegalAccessException { + assertThat(FieldUtils.readDeclaredField(user, "name", true)).isEqualTo("Julie"); + } + + @Test + public void givenFieldUtilsClass_whenCalledwriteField_thenCorrect() throws IllegalAccessException { + FieldUtils.writeField(user, "name", "Julie", true); + assertThat(FieldUtils.readField(user, "name", true)).isEqualTo("Julie"); + + } + + @Test + public void givenFieldUtilsClass_whenCalledwriteDeclaredField_thenCorrect() throws IllegalAccessException { + FieldUtils.writeDeclaredField(user, "name", "Julie", true); + assertThat(FieldUtils.readField(user, "name", true)).isEqualTo("Julie"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java new file mode 100644 index 0000000000..1a5094a16d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.math.Fraction; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class FractionUnitTest { + + @Test + public void givenFractionClass_whenCalledgetFraction_thenCorrect() { + assertThat(Fraction.getFraction(5, 6)).isInstanceOf(Fraction.class); + } + + @Test + public void givenTwoFractionInstances_whenCalledadd_thenCorrect() { + Fraction fraction1 = Fraction.getFraction(1, 4); + Fraction fraction2 = Fraction.getFraction(3, 4); + assertThat(fraction1.add(fraction2).toString()).isEqualTo("1/1"); + } + + @Test + public void givenTwoFractionInstances_whenCalledsubstract_thenCorrect() { + Fraction fraction1 = Fraction.getFraction(3, 4); + Fraction fraction2 = Fraction.getFraction(1, 4); + assertThat(fraction1.subtract(fraction2).toString()).isEqualTo("1/2"); + } + + @Test + public void givenTwoFractionInstances_whenCalledmultiply_thenCorrect() { + Fraction fraction1 = Fraction.getFraction(3, 4); + Fraction fraction2 = Fraction.getFraction(1, 4); + assertThat(fraction1.multiplyBy(fraction2).toString()).isEqualTo("3/16"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java new file mode 100644 index 0000000000..bbd24c8207 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.builder.HashCodeBuilder; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class HashCodeBuilderUnitTest { + + @Test + public void givenHashCodeBuilderInstance_whenCalledtoHashCode_thenCorrect() { + int hashcode = new HashCodeBuilder(17, 37) + .append("John") + .append("john@domain.com") + .toHashCode(); + assertThat(hashcode).isEqualTo(1269178828); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java new file mode 100644 index 0000000000..28ed8d2514 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ImmutablePairUnitTest { + + private static ImmutablePair immutablePair; + + @BeforeClass + public static void setUpImmutablePairInstance() { + immutablePair = new ImmutablePair<>("leftElement", "rightElement"); + } + + @Test + public void givenImmutablePairInstance_whenCalledgetLeft_thenCorrect() { + assertThat(immutablePair.getLeft()).isEqualTo("leftElement"); + } + + @Test + public void givenImmutablePairInstance_whenCalledgetRight_thenCorrect() { + assertThat(immutablePair.getRight()).isEqualTo("rightElement"); + } + + @Test + public void givenImmutablePairInstance_whenCalledof_thenCorrect() { + assertThat(ImmutablePair.of("leftElement", "rightElement")).isInstanceOf(ImmutablePair.class); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenImmutablePairInstance_whenCalledSetValue_thenThrowUnsupportedOperationException() { + immutablePair.setValue("newValue"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java new file mode 100644 index 0000000000..a9dd3fa7c0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.tuple.ImmutableTriple; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ImmutableTripleUnitTest { + + private static ImmutableTriple immutableTriple; + + @BeforeClass + public static void setUpImmutableTripleInstance() { + immutableTriple = new ImmutableTriple<>("leftElement", "middleElement", "rightElement"); + } + + @Test + public void givenImmutableTripleInstance_whenCalledgetLeft_thenCorrect() { + assertThat(immutableTriple.getLeft()).isEqualTo("leftElement"); + } + + @Test + public void givenImmutableTripleInstance_whenCalledgetMiddle_thenCorrect() { + assertThat(immutableTriple.getMiddle()).isEqualTo("middleElement"); + } + + @Test + public void givenImmutableInstance_whenCalledgetRight_thenCorrect() { + assertThat(immutableTriple.getRight()).isEqualTo("rightElement"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java new file mode 100644 index 0000000000..a08399f8de --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.commons.lang3.test; + +import com.baeldung.commons.lang3.beans.User; +import com.baeldung.commons.lang3.beans.UserInitializer; +import org.apache.commons.lang3.concurrent.ConcurrentException; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class LazyInitializerUnitTest { + + @Test + public void givenLazyInitializerInstance_whenCalledget_thenCorrect() throws ConcurrentException { + UserInitializer userInitializer = new UserInitializer(); + assertThat(userInitializer.get()).isInstanceOf(User.class); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java new file mode 100644 index 0000000000..5e1d15f2f8 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.lang3.test; + +import com.baeldung.commons.lang3.beans.User; +import java.lang.reflect.Method; +import org.apache.commons.lang3.reflect.MethodUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class MethodUtilsUnitTest { + + @Test + public void givenMethodUtilsClass_whenCalledgetAccessibleMethod_thenCorrect() { + assertThat(MethodUtils.getAccessibleMethod(User.class, "getName")).isInstanceOf(Method.class); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java new file mode 100644 index 0000000000..02041f51e8 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.mutable.MutableObject; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class MutableObjectUnitTest { + + private static MutableObject mutableObject; + + @BeforeClass + public static void setUpMutableObject() { + mutableObject = new MutableObject("Initial value"); + } + + @Test + public void givenMutableObject_whenCalledgetValue_thenCorrect() { + assertThat(mutableObject.getValue()).isInstanceOf(String.class); + } + + @Test + public void givenMutableObject_whenCalledsetValue_thenCorrect() { + mutableObject.setValue("Another value"); + assertThat(mutableObject.getValue()).isEqualTo("Another value"); + } + + @Test + public void givenMutableObject_whenCalledtoString_thenCorrect() { + assertThat(mutableObject.toString()).isEqualTo("Another value"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java new file mode 100644 index 0000000000..174ec70c4d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.tuple.MutablePair; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class MutablePairUnitTest { + + private static MutablePair mutablePair; + + @BeforeClass + public static void setUpMutablePairInstance() { + mutablePair = new MutablePair<>("leftElement", "rightElement"); + } + + @Test + public void givenMutablePairInstance_whenCalledgetLeft_thenCorrect() { + assertThat(mutablePair.getLeft()).isEqualTo("leftElement"); + } + + @Test + public void givenMutablePairInstance_whenCalledgetRight_thenCorrect() { + assertThat(mutablePair.getRight()).isEqualTo("rightElement"); + } + + @Test + public void givenMutablePairInstance_whenCalledsetLeft_thenCorrect() { + mutablePair.setLeft("newLeftElement"); + assertThat(mutablePair.getLeft()).isEqualTo("newLeftElement"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java new file mode 100644 index 0000000000..bdf254a102 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.math.NumberUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class NumberUtilsUnitTest { + + @Test + public void givenNumberUtilsClass_whenCalledcompareWithIntegers_thenCorrect() { + assertThat(NumberUtils.compare(1, 1)).isEqualTo(0); + } + + @Test + public void givenNumberUtilsClass_whenCalledcompareWithLongs_thenCorrect() { + assertThat(NumberUtils.compare(1L, 1L)).isEqualTo(0); + } + + @Test + public void givenNumberUtilsClass_whenCalledcreateNumber_thenCorrect() { + assertThat(NumberUtils.createNumber("123456")).isEqualTo(123456); + } + + @Test + public void givenNumberUtilsClass_whenCalledisDigits_thenCorrect() { + assertThat(NumberUtils.isDigits("123456")).isTrue(); + } + + @Test + public void givenNumberUtilsClass_whenCallemaxwithIntegerArray_thenCorrect() { + int[] array = {1, 2, 3, 4, 5, 6}; + assertThat(NumberUtils.max(array)).isEqualTo(6); + } + + @Test + public void givenNumberUtilsClass_whenCalleminwithIntegerArray_thenCorrect() { + int[] array = {1, 2, 3, 4, 5, 6}; + assertThat(NumberUtils.min(array)).isEqualTo(1); + } + + @Test + public void givenNumberUtilsClass_whenCalleminwithByteArray_thenCorrect() { + byte[] array = {1, 2, 3, 4, 5, 6}; + assertThat(NumberUtils.min(array)).isEqualTo((byte) 1); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java new file mode 100644 index 0000000000..ab39ba7bd9 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class StringUtilsUnitTest { + + @Test + public void givenStringUtilsClass_whenCalledisBlank_thenCorrect() { + assertThat(StringUtils.isBlank(" ")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisEmpty_thenCorrect() { + assertThat(StringUtils.isEmpty("")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisAllLowerCase_thenCorrect() { + assertThat(StringUtils.isAllLowerCase("abd")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisAllUpperCase_thenCorrect() { + assertThat(StringUtils.isAllUpperCase("ABC")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisMixedCase_thenCorrect() { + assertThat(StringUtils.isMixedCase("abC")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisAlpha_thenCorrect() { + assertThat(StringUtils.isAlpha("abc")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisAlphanumeric_thenCorrect() { + assertThat(StringUtils.isAlphanumeric("abc123")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledcontains_thenCorrect() { + assertThat(StringUtils.contains("abc", "ab")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledcontainsAny_thenCorrect() { + assertThat(StringUtils.containsAny("abc", 'a', 'b', 'c')).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledcontainsIgnoreCase_thenCorrect() { + assertThat(StringUtils.containsIgnoreCase("abc", "ABC")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledswapCase_thenCorrect() { + assertThat(StringUtils.swapCase("abc")).isEqualTo("ABC"); + } + + @Test + public void givenStringUtilsClass_whenCalledreverse_thenCorrect() { + assertThat(StringUtils.reverse("abc")).isEqualTo("cba"); + } + + @Test + public void givenStringUtilsClass_whenCalleddifference_thenCorrect() { + assertThat(StringUtils.difference("abc", "abd")).isEqualTo("d"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java new file mode 100644 index 0000000000..0efe97f912 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.commons.lang3.test; + +import java.io.File; +import org.apache.commons.lang3.JavaVersion; +import org.apache.commons.lang3.SystemUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class SystemsUtilsUnitTest { + + @Test + public void givenSystemUtilsClass_whenCalledgetJavaHome_thenCorrect() { + assertThat(SystemUtils.getJavaHome()).isEqualTo(new File("/usr/lib/jvm/java-8-oracle/jre")); + } + + @Test + public void givenSystemUtilsClass_whenCalledgetUserHome_thenCorrect() { + assertThat(SystemUtils.getUserHome()).isEqualTo(new File("/home/travis")); + } + + @Test + public void givenSystemUtilsClass_whenCalledisJavaVersionAtLeast_thenCorrect() { + assertThat(SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_RECENT)).isTrue(); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java new file mode 100644 index 0000000000..7d506bbbab --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.tuple.Triple; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class TripleUnitTest { + + private static Triple triple; + + @BeforeClass + public static void setUpTripleInstance() { + triple = Triple.of("leftElement", "middleElement", "rightElement"); + } + + @Test + public void givenTripleInstance_whenCalledgetLeft_thenCorrect() { + assertThat(triple.getLeft()).isEqualTo("leftElement"); + } + + @Test + public void givenTripleInstance_whenCalledgetMiddle_thenCorrect() { + assertThat(triple.getMiddle()).isEqualTo("middleElement"); + } + + @Test + public void givenTripleInstance_whenCalledgetRight_thenCorrect() { + assertThat(triple.getRight()).isEqualTo("rightElement"); + } +} diff --git a/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java b/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java index 4406494d30..e61f4158a7 100644 --- a/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java +++ b/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java @@ -4,10 +4,12 @@ import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.KafkaStreams; +import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.StreamsConfig; +import org.apache.kafka.streams.Topology; import org.apache.kafka.streams.kstream.KStream; -import org.apache.kafka.streams.kstream.KStreamBuilder; import org.apache.kafka.streams.kstream.KTable; +import org.apache.kafka.streams.kstream.Produced; import org.apache.kafka.test.TestUtils; import org.junit.Ignore; import org.junit.Test; @@ -36,20 +38,20 @@ public class KafkaStreamsLiveTest { streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath()); // when - KStreamBuilder builder = new KStreamBuilder(); + StreamsBuilder builder = new StreamsBuilder(); KStream textLines = builder.stream(inputTopic); Pattern pattern = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS); KTable wordCounts = textLines.flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase()))).groupBy((key, word) -> word).count(); - wordCounts.foreach((word, count) -> System.out.println("word: " + word + " -> " + count)); + textLines.foreach((word, count) -> System.out.println("word: " + word + " -> " + count)); String outputTopic = "outputTopic"; final Serde stringSerde = Serdes.String(); - final Serde longSerde = Serdes.Long(); - wordCounts.to(stringSerde, longSerde, outputTopic); + final Serde longSerde = Serdes.String(); + textLines.to(outputTopic, Produced.with(stringSerde,longSerde)); - KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration); + KafkaStreams streams = new KafkaStreams(new Topology(), streamsConfiguration); streams.start(); // then diff --git a/lombok/README.md b/lombok/README.md index 1a787e32c7..d12c14416d 100644 --- a/lombok/README.md +++ b/lombok/README.md @@ -1,3 +1,5 @@ ## Relevant Articles: - [Introduction to Project Lombok](http://www.baeldung.com/intro-to-project-lombok) - [Using Lombok’s @Builder Annotation](http://www.baeldung.com/lombok-builder) +- [Using Lombok’s @Getter for Boolean Fields](https://www.baeldung.com/lombok-getter-boolean) +- [Lombok @Builder with Inheritance](https://www.baeldung.com/lombok-builder-inheritance) diff --git a/mustache/pom.xml b/mustache/pom.xml index d385246182..a276dfbf43 100644 --- a/mustache/pom.xml +++ b/mustache/pom.xml @@ -3,7 +3,6 @@ 4.0.0 mustache - 0.0.1-SNAPSHOT jar mustache @@ -24,10 +23,8 @@ org.assertj assertj-core - ${assertj.version} - log4j log4j @@ -55,13 +52,6 @@ ${datafactory.version} - - junit - junit - ${junit.version} - test - - @@ -73,90 +63,13 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/AutoconfigurationTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - 0.9.2 - 3.7.0 1.2.16 - 4.12 - UTF-8 - 3.7.0 - 2.21.0 0.8 3.3.7 - 1.8 \ No newline at end of file diff --git a/optaplanner/README.md b/optaplanner/README.md new file mode 100644 index 0000000000..1568a615c0 --- /dev/null +++ b/optaplanner/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [A Guide to OptaPlanner](https://www.baeldung.com/opta-planner) diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..46ee3cd368 --- /dev/null +++ b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,67 @@ +package org.baeldung; + +import java.io.IOException; +import java.util.HashMap; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.baeldung.spring.data.cassandra.config.CassandraConfig; +import org.baeldung.spring.data.cassandra.model.Book; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class SpringContextIntegrationTest { + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7f906bdbcd --- /dev/null +++ b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4be5891e3e --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.eclipselink.springdata.EclipselinkSpringDataApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EclipselinkSpringDataApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2f0557ccc1 --- /dev/null +++ b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.data.gemfire.function.GemfireConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ea32ed324b --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class) +@ActiveProfiles(profiles = "test") +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e093892365 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.redis.config.RedisConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RedisConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e76967ae8a --- /dev/null +++ b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.solr.config.SolrConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SolrConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a81a4eedb1 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.PersistenceConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..af4618d0f3 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java index 78c4116c67..ec0d4bca3c 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java @@ -78,9 +78,9 @@ public class PersistenceJPAConfig { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false"); + + return hibernateProperties; } diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java index 1c8ce5400f..cf6e69eb39 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java @@ -5,7 +5,7 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class[] getRootConfigClasses() { - return new Class[] { PersistenceJNDIConfig.class }; + return new Class[] { PersistenceJPAConfig.class }; } @Override diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepository.java similarity index 71% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepository.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepository.java index af30ae461e..114cf48c7c 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepository.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.criteria.repository; +package org.baeldung.persistence.dao; -import org.baeldung.persistence.criteria.model.Book; +import org.baeldung.persistence.model.Book; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepositoryCustom.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryCustom.java similarity index 58% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepositoryCustom.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryCustom.java index 35330cfa3c..b939907572 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepositoryCustom.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryCustom.java @@ -1,8 +1,8 @@ -package org.baeldung.persistence.criteria.repository; +package org.baeldung.persistence.dao; import java.util.List; -import org.baeldung.persistence.criteria.model.Book; +import org.baeldung.persistence.model.Book; public interface BookRepositoryCustom { diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/dao/BookRepositoryImpl.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryImpl.java similarity index 87% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/dao/BookRepositoryImpl.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryImpl.java index f782d69e1e..6e9aa998d7 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/dao/BookRepositoryImpl.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.criteria.dao; +package org.baeldung.persistence.dao; import java.util.ArrayList; import java.util.List; @@ -10,8 +10,7 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.baeldung.persistence.criteria.model.Book; -import org.baeldung.persistence.criteria.repository.BookRepositoryCustom; +import org.baeldung.persistence.model.Book; import org.springframework.stereotype.Repository; @Repository diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookService.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookService.java similarity index 63% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookService.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookService.java index 7b1aff857e..88b769e9bf 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookService.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookService.java @@ -1,12 +1,12 @@ -package org.baeldung.persistence.criteria.repository; +package org.baeldung.persistence.dao; -import static org.baeldung.persistence.criteria.repository.BookSpecifications.hasAuthor; -import static org.baeldung.persistence.criteria.repository.BookSpecifications.titleContains; +import static org.baeldung.persistence.dao.BookSpecifications.hasAuthor; +import static org.baeldung.persistence.dao.BookSpecifications.titleContains; import static org.springframework.data.jpa.domain.Specifications.where; import java.util.List; -import org.baeldung.persistence.criteria.model.Book; +import org.baeldung.persistence.model.Book; import org.springframework.stereotype.Service; @Service diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookSpecifications.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookSpecifications.java similarity index 78% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookSpecifications.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookSpecifications.java index 392b750977..ed9540060d 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookSpecifications.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookSpecifications.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.criteria.repository; +package org.baeldung.persistence.dao; -import org.baeldung.persistence.criteria.model.Book; +import org.baeldung.persistence.model.Book; import org.springframework.data.jpa.domain.Specification; public class BookSpecifications { diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/model/Book.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Book.java similarity index 91% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/model/Book.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Book.java index beb6c0190c..754bd179d1 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/model/Book.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Book.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.criteria.model; +package org.baeldung.persistence.model; import javax.persistence.Entity; import javax.persistence.Id; diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence.xml b/persistence-modules/spring-jpa/src/main/resources/persistence.xml index 65bad29cdc..6304fa0a65 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence.xml +++ b/persistence-modules/spring-jpa/src/main/resources/persistence.xml @@ -21,8 +21,6 @@ ${hibernate.hbm2ddl.auto} ${hibernate.dialect} - ${hibernate.cache.use_second_level_cache} - ${hibernate.cache.use_query_cache} diff --git a/pom.xml b/pom.xml index 7a7e2d7f64..bda69bfd42 100644 --- a/pom.xml +++ b/pom.xml @@ -398,16 +398,17 @@ javafx jgroups jee-7 - jhipster/jhipster-monolithic + jhipster jjwt jsf json-path json jsoup testing-modules/junit-5 - jws + libraries libraries-data + libraries-security libraries-server linkrest logging-modules/log-mdc @@ -470,10 +471,11 @@ 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 + spring-cloud-bus spring-core spring-cucumber spring-ejb @@ -603,7 +605,236 @@ spring-reactive-kotlin jnosql spring-boot-angular-ecommerce + cdi-portable-extension jta + + java-websocket + activejdbc + animal-sniffer-mvn-plugin + apache-avro + apache-bval + apache-shiro + apache-spark + asciidoctor + checker-plugin + + + core-java-sun + custom-pmd + dagger + data-structures + dubbo + flyway + + java-difference-date + + jni + jooby + + + + ratpack + rest-with-spark-java + spring-boot-autoconfiguration + spring-boot-custom-starter + spring-boot-jasypt + spring-custom-aop + spring-data-rest-querydsl + spring-groovy + spring-mobile + spring-mustache + spring-mvc-simple + spring-mybatis + spring-rest-hal-browser + spring-rest-shell + spring-rest-template + spring-roo + spring-security-stormpath + sse-jaxrs + static-analysis + stripe + + Twitter4J + wicket + xstream + cas/cas-secured-app + cas/cas-server + + + + + + + + + + + + + jenkins/hello-world + + + + spring-boot-custom-starter/greeter + spring-boot-h2/spring-boot-h2-database + + + + + + + + + + spring-context + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*SpringContextIntegrationTest.java + + + + + + + + + spring-5 + spring-5-data-reactive + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-security + spring-5-security + spring-activiti + spring-akka + spring-all + spring-aop + spring-apache-camel + spring-batch + spring-bom + spring-boot-admin/spring-boot-admin-client + spring-boot-admin/spring-boot-admin-server + spring-boot-bootstrap + spring-boot-bootstrap + spring-boot-camel + spring-boot-client + spring-boot-custom-starter + greeter-spring-boot-autoconfigure + greeter-spring-boot-sample-app + spring-boot-h2/spring-boot-h2-database + spring-boot-jasypt + spring-boot-keycloak + spring-boot-mvc + spring-boot-property-exp/property-exp-custom-config + spring-boot-property-exp/property-exp-default-config + spring-boot-vue + spring-cloud + spring-cloud/spring-cloud-archaius/basic-config + spring-cloud/spring-cloud-archaius/extra-configs + spring-cloud/spring-cloud-bootstrap/config + spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer + spring-cloud/spring-cloud-contract/spring-cloud-contract-producer + spring-cloud/spring-cloud-gateway + spring-cloud/spring-cloud-kubernetes/demo-backend + spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server + spring-cloud/spring-cloud-ribbon-client + spring-cloud/spring-cloud-security/auth-client + spring-cloud/spring-cloud-security/auth-resource + spring-cloud/spring-cloud-security/auth-server + spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit + spring-cloud/spring-cloud-task/springcloudtasksink + spring-cloud/spring-cloud-zookeeper + spring-cloud/spring-cloud-bus/spring-cloud-config-server + spring-cloud/spring-cloud-data-flow/log-sink + spring-cloud/spring-cloud-data-flow/time-processor + spring-cloud/spring-cloud-data-flow/time-source + spring-cucumber + spring-data-keyvalue + spring-data-rest + spring-dispatcher-servlet + spring-drools + spring-freemarker + spring-hibernate-3 + spring-hibernate4 + spring-integration + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-kafka + spring-katharsis + spring-ldap + spring-mobile + spring-mockito + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-velocity + spring-mvc-webflow + spring-protobuf + spring-quartz + remoting-hessian-burlap/spring-remoting-hessian-burlap-client + remoting-hessian-burlap/remoting-hessian-burlap-server + spring-reactor + spring-remoting/ + spring-remoting/remoting-http/remoting-http-server + spring-remoting/remoting-jms/remoting-jms-client + spring-remoting/remoting-rmi/remoting-rmi-server + spring-rest + spring-rest-angular + spring-rest-embedded-tomcat + spring-rest-full + spring-rest-simple + spring-resttemplate + spring-security-acl + spring-security-angular + spring-security-cache-control + spring-security-client/spring-security-jsp-authentication + spring-security-client/spring-security-jsp-authorize + spring-security-client/spring-security-jsp-config + spring-security-client/spring-security-mvc + spring-security-client/spring-security-thymeleaf-authentication + spring-security-client/spring-security-thymeleaf-authorize + spring-security-client/spring-security-thymeleaf-config + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-rest + spring-security-sso/spring-security-sso-auth-server + spring-security-sso/spring-security-sso-ui + spring-security-sso/spring-security-sso-ui-2 + spring-security-thymeleaf/spring-security-thymeleaf-authentication + spring-security-thymeleaf/spring-security-thymeleaf-authorize + spring-security-thymeleaf/spring-security-thymeleaf-config + spring-security-x509/spring-security-x509-basic-auth + spring-security-x509/spring-security-x509-client-auth + spring-session/spring-session-jdbc + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-swagger-codegen/spring-swagger-codegen-app + spring-thymeleaf + spring-userservice + spring-vault + spring-vertx + spring-zuul/spring-zuul-foos-resource + persistence-modules/spring-data-dynamodb + persistence-modules/spring-data-eclipselink + persistence-modules/spring-data-solr + persistence-modules/spring-hibernate-5 @@ -747,6 +978,7 @@ spring-boot-logging-log4j2 spring-cloud-data-flow spring-cloud + spring-cloud-bus spring-core spring-cucumber spring-ejb @@ -847,7 +1079,80 @@ - + + java-websocket + activejdbc + animal-sniffer-mvn-plugin + apache-avro + apache-bval + apache-shiro + apache-spark + asciidoctor + checker-plugin + + + core-java-sun + custom-pmd + dagger + data-structures + dubbo + flyway + + java-difference-date + + jni + jooby + + + + ratpack + rest-with-spark-java + spring-boot-autoconfiguration + spring-boot-custom-starter + spring-boot-jasypt + spring-custom-aop + spring-data-rest-querydsl + spring-groovy + spring-mobile + spring-mustache + spring-mvc-simple + spring-mybatis + spring-rest-hal-browser + spring-rest-shell + spring-rest-template + spring-roo + spring-security-stormpath + sse-jaxrs + static-analysis + stripe + + + wicket + xstream + cas/cas-secured-app + + + + + + + + + + + + + + jenkins/hello-world + + + + spring-boot-custom-starter/greeter + spring-boot-h2/spring-boot-h2-database + + + + @@ -1028,6 +1333,7 @@ spring-boot-logging-log4j2 spring-cloud-data-flow spring-cloud + spring-cloud-bus spring-core spring-cucumber spring-ejb @@ -1235,7 +1541,7 @@ parent-kotlin libraries geotools - jhipster/jhipster-monolithic + jhipster testing-modules/gatling spring-boot spring-boot-ops diff --git a/ratpack/README.md b/ratpack/README.md index 02b91da0bd..dded42fab6 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -4,4 +4,4 @@ - [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice) - [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) - [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix) - +- [Ratpack HTTP Client](https://www.baeldung.com/ratpack-http-client) diff --git a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java b/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java index 56650ba306..e3060b8e02 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java @@ -37,14 +37,14 @@ public class ReactorIntegrationTest { Flux.just(1, 2, 3, 4) .log() .map(i -> i * 2) - .zipWith(Flux.range(0, Integer.MAX_VALUE).log(), (two, one) -> String.format("First Flux: %d, Second Flux: %d", one, two)) + .zipWith(Flux.range(0, Integer.MAX_VALUE).log(), (one, two) -> String.format("First Flux: %d, Second Flux: %d", one, two)) .subscribe(elements::add); assertThat(elements).containsExactly( - "First Flux: 0, Second Flux: 2", - "First Flux: 1, Second Flux: 4", - "First Flux: 2, Second Flux: 6", - "First Flux: 3, Second Flux: 8"); + "First Flux: 2, Second Flux: 0", + "First Flux: 4, Second Flux: 1", + "First Flux: 6, Second Flux: 2", + "First Flux: 8, Second Flux: 3"); } @Test diff --git a/rest-with-spark-java/src/test/java/com/baeldung/AppTest.java b/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java similarity index 96% rename from rest-with-spark-java/src/test/java/com/baeldung/AppTest.java rename to rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java index c7b88dd6d1..9e24879767 100644 --- a/rest-with-spark-java/src/test/java/com/baeldung/AppTest.java +++ b/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java @@ -16,16 +16,16 @@ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; -public class AppTest extends TestCase { +public class AppLiveTest extends TestCase { ObjectMapper mapper = new ObjectMapper(); - public AppTest( String testName ) { + public AppLiveTest( String testName ) { super( testName ); } public static Test suite() { - return new TestSuite( AppTest.class ); + return new TestSuite( AppLiveTest.class ); } public void testApp() throws IOException, ClassNotFoundException { diff --git a/rxjava-2/README.md b/rxjava-2/README.md index ccf575757f..78eb6e6428 100644 --- a/rxjava-2/README.md +++ b/rxjava-2/README.md @@ -2,5 +2,6 @@ - [RxJava and Error Handling](http://www.baeldung.com/rxjava-error-handling) - [RxJava 2 – Flowable](http://www.baeldung.com/rxjava-2-flowable) +- [RxJava 2 - Completable](http://www.baeldung.com/rxjava-completable) - [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) -- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) \ No newline at end of file +- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml index 4c5ea014d7..a18b096b6d 100644 --- a/rxjava-2/pom.xml +++ b/rxjava-2/pom.xml @@ -38,9 +38,8 @@ 3.8.0 - 2.1.3 + 2.2.2 1.7.0 2.0.0 - \ No newline at end of file diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java new file mode 100644 index 0000000000..6acda310a5 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java @@ -0,0 +1,112 @@ +package com.baeldung.rxjava; + +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Single; +import io.reactivex.observers.DisposableCompletableObserver; +import org.junit.Before; +import org.junit.Test; + +public class CompletableUnitTest { + + Completable first; + Completable second; + Completable error; + Throwable throwable = new RuntimeException(); + + @Before + public void setUpCompletables() { + first = Completable.fromSingle(Single.just(1)); + second = Completable.fromRunnable(() -> {}); + error = Single.error(throwable) + .ignoreElement(); + } + + @Test + public void whenCompletableConstructed_thenCompletedSuccessfully() { + Completable completed = Completable.complete(); + completed.subscribe(new DisposableCompletableObserver() { + @Override + public void onComplete() { + System.out.println("Completed!"); + } + + @Override + public void onError(Throwable e) { + e.printStackTrace(); + } + }); + Flowable flowable = Flowable.just("request received", "user logged in"); + Completable flowableCompletable = Completable.fromPublisher(flowable); + Completable singleCompletable = Single.just(1) + .ignoreElement(); + + completed.andThen(flowableCompletable) + .andThen(singleCompletable) + .test() + .assertComplete(); + } + + @Test + public void whenCombiningCompletables_thenCompletedSuccessfully() { + first.andThen(second) + .test() + .assertComplete(); + } + + @Test + public void whenCombinedWithError_thenCompletedWithError() { + first.andThen(second) + .andThen(error) + .test() + .assertError(throwable); + } + + @Test + public void whenCombinedWithNever_thenDoesNotComplete() { + first.andThen(second) + .andThen(Completable.never()) + .test() + .assertNotComplete(); + } + + @Test + public void whenMergedCompletables_thenCompletedSuccessfully() { + Completable.mergeArray(first, second) + .test() + .assertComplete(); + } + + @Test + public void whenMergedWithError_thenCompletedWithError() { + Completable.mergeArray(first, second, error) + .test() + .assertError(throwable); + } + + @Test + public void whenFlatMaped_thenCompletedSuccessfully() { + Completable allElementsCompletable = Flowable.just("request received", "user logged in") + .flatMapCompletable(message -> Completable + .fromRunnable(() -> System.out.println(message)) + ); + allElementsCompletable + .test() + .assertComplete(); + } + + @Test + public void whenAmbWithNever_thenCompletedSuccessfully() { + Completable.ambArray(first, Completable.never(), second) + .test() + .assertComplete(); + } + + @Test + public void whenAmbWithError_thenCompletedWithError() { + Completable.ambArray(error, first, second) + .test() + .assertError(throwable); + } + +} 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-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9dfac2bd9e --- /dev/null +++ b/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.flips.ApplicationConfig; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index e4dd454635..5c723c6e29 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -62,28 +62,6 @@ spring-boot-starter-test test - - - org.junit.jupiter - junit-jupiter-api - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - @@ -175,32 +153,13 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LiveTest.java - - - - UTF-8 - UTF-8 - 1.8 1.2.40 1.2.40 - 1.0.0 - 5.0.2 + diff --git a/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ce4c172960 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7843a8968d --- /dev/null +++ b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveTestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveTestApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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-5-reactive-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2bcd974510 --- /dev/null +++ b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.security.SpringSecurity5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSecurity5Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 0665eb4f57..7977fd820f 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -13,3 +13,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) - [Spring Webflux and CORS](http://www.baeldung.com/spring-webflux-cors) - [Handling Errors in Spring WebFlux](http://www.baeldung.com/spring-webflux-errors) +- [Server-Sent Events in Spring](https://www.baeldung.com/spring-server-sent-events) diff --git a/spring-5-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ce4c172960 --- /dev/null +++ b/spring-5-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..967f67e760 --- /dev/null +++ b/spring-5-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.dsl.CustomConfigurerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CustomConfigurerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 9f60b8a364..293edb5bda 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -1,5 +1,6 @@ - 4.0.0 com.baeldung @@ -134,7 +135,26 @@ + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + methods + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + @@ -142,6 +162,8 @@ 1.5.6 4.1 ${project.build.directory}/generated-snippets + 2.21.0 + diff --git a/spring-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..75b3df4978 --- /dev/null +++ b/spring-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Spring5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-activiti/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-activiti/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ae37e77f86 --- /dev/null +++ b/spring-activiti/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.example.activitiwithspring.ActivitiWithSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ActivitiWithSpringApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-all/pom.xml b/spring-all/pom.xml index c4c4cf7963..bab2e431ec 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -45,6 +45,15 @@ spring-shell ${org.springframework.shell.version} + + org.springframework + spring-websocket + + + org.springframework + spring-messaging + + org.springframework @@ -190,7 +199,24 @@ - + + + dev + + true + + + dev + + + + prod + + prod + + + + org.baeldung.sample.App diff --git a/spring-all/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java b/spring-all/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java index eb5543e3db..2d1905ee9c 100644 --- a/spring-all/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java +++ b/spring-all/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java @@ -2,9 +2,11 @@ package org.baeldung.profiles; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; @Configuration @ComponentScan("org.baeldung.profiles") +@PropertySource(value = "classpath:application.properties") public class SpringProfilesConfig { } diff --git a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java index 73df386aff..9257a3aa3a 100644 --- a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java +++ b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java @@ -13,21 +13,36 @@ import org.springframework.web.bind.annotation.RequestMapping; public class ScopesController { public static final Logger LOG = LoggerFactory.getLogger(ScopesController.class); - @Resource(name = "requestMessage") - HelloMessageGenerator requestMessage; + @Resource(name = "requestScopedBean") + HelloMessageGenerator requestScopedBean; - @Resource(name = "sessionMessage") - HelloMessageGenerator sessionMessage; + @Resource(name = "sessionScopedBean") + HelloMessageGenerator sessionScopedBean; - @RequestMapping("/scopes") - public String getScopes(final Model model) { - LOG.info("Request Message:" + requestMessage.getMessage()); - LOG.info("Session Message" + sessionMessage.getMessage()); - requestMessage.setMessage("Good morning!"); - sessionMessage.setMessage("Good afternoon!"); - model.addAttribute("requestMessage", requestMessage.getMessage()); - model.addAttribute("sessionMessage", sessionMessage.getMessage()); + @Resource(name = "applicationScopedBean") + HelloMessageGenerator applicationScopedBean; + + @RequestMapping("/scopes/request") + public String getRequestScopeMessage(final Model model) { + model.addAttribute("previousMessage", requestScopedBean.getMessage()); + requestScopedBean.setMessage("Request Scope Message!"); + model.addAttribute("currentMessage", requestScopedBean.getMessage()); return "scopesExample"; } + @RequestMapping("/scopes/session") + public String getSessionScopeMessage(final Model model) { + model.addAttribute("previousMessage", sessionScopedBean.getMessage()); + sessionScopedBean.setMessage("Session Scope Message!"); + model.addAttribute("currentMessage", sessionScopedBean.getMessage()); + return "scopesExample"; + } + + @RequestMapping("/scopes/application") + public String getApplicationScopeMessage(final Model model) { + model.addAttribute("previousMessage", applicationScopedBean.getMessage()); + applicationScopedBean.setMessage("Application Scope Message!"); + model.addAttribute("currentMessage", applicationScopedBean.getMessage()); + return "scopesExample"; + } } diff --git a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java index fb34725508..b5fe494ee2 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java @@ -27,19 +27,25 @@ public class ScopesConfig { @Bean @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator requestMessage() { + public HelloMessageGenerator requestScopedBean() { return new HelloMessageGenerator(); } @Bean @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator sessionMessage() { + public HelloMessageGenerator sessionScopedBean() { return new HelloMessageGenerator(); } @Bean @Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator globalSessionMessage() { + public HelloMessageGenerator applicationScopedBean() { + return new HelloMessageGenerator(); + } + + @Bean + @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator websocketScopedBean() { return new HelloMessageGenerator(); } diff --git a/spring-all/src/main/resources/application.properties b/spring-all/src/main/resources/application.properties new file mode 100644 index 0000000000..cbfe3f2df2 --- /dev/null +++ b/spring-all/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.profiles.active=@spring.profiles.active@ \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/view/scopesExample.jsp b/spring-all/src/main/webapp/WEB-INF/view/scopesExample.jsp index 7974cf0220..0946f1b5ef 100644 --- a/spring-all/src/main/webapp/WEB-INF/view/scopesExample.jsp +++ b/spring-all/src/main/webapp/WEB-INF/view/scopesExample.jsp @@ -2,9 +2,9 @@ -

Bean Scopes Examples

-
- Request Message: ${requestMessage }
- Session Message: ${sessionMessage } +

Bean Scopes Examples

+
Previous Message: ${previousMessage } +
Current Message: ${currentMessage } +
\ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java b/spring-all/src/test/java/org/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java new file mode 100644 index 0000000000..929d088a14 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java @@ -0,0 +1,22 @@ +package org.baeldung.profiles; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringProfilesWithMavenPropertiesIntegrationTest { + + @Autowired + DatasourceConfig datasourceConfig; + + @Test + public void testSpringProfiles() { + Assert.assertTrue(datasourceConfig instanceof DevDatasourceConfig); + } +} \ No newline at end of file diff --git a/spring-amqp-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-amqp-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f134074cf8 --- /dev/null +++ b/spring-amqp-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springamqpsimple.SpringAmqpApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringAmqpApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..cf1ac7de89 --- /dev/null +++ b/spring-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-apache-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-apache-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..efd0603c76 --- /dev/null +++ b/spring-apache-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.camel.main.App; + +public class SpringContextIntegrationTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite new file mode 100644 index 0000000000..4456ef63cc Binary files /dev/null and b/spring-batch/repository.sqlite differ diff --git a/spring-batch/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c3a9f74759 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.baeldung.batch.App; +import org.junit.Test; + +public class SpringContextIntegrationTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-bom/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-bom/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6dee4b808e --- /dev/null +++ b/spring-bom/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.spring.bom.HelloWorldApp; + +public class SpringContextIntegrationTest { + + @Test + public final void testMain() throws Exception { + HelloWorldApp.main(null); + } +} diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1f1fae17bc --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootadminclient.SpringBootAdminClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminClientApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4c151d97df --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootadminserver.SpringBootAdminServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminServerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4f595916f7 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.ecommerce.EcommerceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EcommerceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java index 4f4f6fb6af..d6fc1836c7 100644 --- a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java @@ -1,10 +1,27 @@ package com.baeldung.autoconfiguration; +import java.util.Arrays; +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureOrder; -import org.springframework.boot.autoconfigure.condition.*; +import org.springframework.boot.autoconfigure.condition.ConditionMessage; import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style; -import org.springframework.context.annotation.*; +import org.springframework.boot.autoconfigure.condition.ConditionOutcome; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; +import org.springframework.boot.autoconfigure.condition.SpringBootCondition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotatedTypeMetadata; @@ -14,11 +31,6 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.util.ClassUtils; -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; -import java.util.Arrays; -import java.util.Properties; - @Configuration @ConditionalOnClass(DataSource.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) diff --git a/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..136ea2481f --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AutoconfigurationApplication.class) +@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 519b36ce4f..4b09f11714 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -2,3 +2,4 @@ - [Bootstrap a Simple Application using Spring Boot](http://www.baeldung.com/spring-boot-start) - [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) - [Thin JARs with Spring Boot](http://www.baeldung.com/spring-boot-thin-jar) +- [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry) diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index c1ce4df6e2..b5bcc587b1 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -78,6 +78,43 @@ + + cloud-gcp + + + org.springframework.cloud + spring-cloud-gcp-starter + 1.0.0.RELEASE + + + org.springframework.cloud + spring-cloud-gcp-starter-sql-mysql + 1.0.0.RELEASE + + + + ${project.name}-gcp + + + src/main/resources + + **/logback.xml + + + + + + com.google.cloud.tools + appengine-maven-plugin + 1.3.2 + + + org.springframework.boot + spring-boot-maven-plugin + + + + cloudfoundry @@ -91,6 +128,7 @@ + ${project.name}-cf src/main/resources @@ -103,9 +141,6 @@ org.springframework.boot spring-boot-maven-plugin - - ${project.name}-cf - org.apache.maven.plugins diff --git a/spring-boot-bootstrap/src/main/appengine/app.yaml b/spring-boot-bootstrap/src/main/appengine/app.yaml new file mode 100644 index 0000000000..a65ec6533a --- /dev/null +++ b/spring-boot-bootstrap/src/main/appengine/app.yaml @@ -0,0 +1,19 @@ +runtime: java +env: flex +runtime_config: + jdk: openjdk8 +env_variables: + SPRING_PROFILES_ACTIVE: "gcp,mysql" +handlers: +- url: /.* + script: this field is required, but ignored +resources: + cpu: 2 + memory_gb: 2 + disk_size_gb: 10 + volumes: + - name: ramdisk1 + volume_type: tmpfs + size_gb: 0.5 +manual_scaling: + instances: 1 diff --git a/spring-boot-bootstrap/src/main/resources/application-gcp.properties b/spring-boot-bootstrap/src/main/resources/application-gcp.properties new file mode 100644 index 0000000000..3dd11eeb8c --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-gcp.properties @@ -0,0 +1,3 @@ +spring.cloud.gcp.sql.instance-connection-name=baeldung-spring-boot-bootstrap:europe-west2:baeldung-spring-boot-bootstrap-db +spring.cloud.gcp.sql.database-name=baeldung_bootstrap_db +spring.cloud.gcp.logging.enabled=true \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/application.properties b/spring-boot-bootstrap/src/main/resources/application.properties index eee89ca460..d83166d843 100644 --- a/spring-boot-bootstrap/src/main/resources/application.properties +++ b/spring-boot-bootstrap/src/main/resources/application.properties @@ -8,4 +8,5 @@ spring.thymeleaf.suffix=.html server.error.path=/error server.error.whitelabel.enabled=false -spring.jpa.generate-ddl=true \ No newline at end of file +spring.jpa.generate-ddl=true +spring.jpa.hibernate.ddl-auto=update \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/logback-gcp.xml b/spring-boot-bootstrap/src/main/resources/logback-gcp.xml new file mode 100644 index 0000000000..9a9c1c633d --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/logback-gcp.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties b/spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties new file mode 100644 index 0000000000..6ba0b5ffcc --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties @@ -0,0 +1 @@ +spring.cloud.appId=baeldung-spring-boot-bootstrap diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringCloudRestConfigIntegrationTest.java b/spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 85% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringCloudRestConfigIntegrationTest.java rename to spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 8cc30a32ab..9ae417a546 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringCloudRestConfigIntegrationTest.java +++ b/spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -7,9 +7,9 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class SpringCloudRestConfigIntegrationTest { +public class SpringContextIntegrationTest { + @Test public void contextLoads() { } - } diff --git a/spring-boot-camel/pom.xml b/spring-boot-camel/pom.xml index f04e8e34f7..19a0bec809 100644 --- a/spring-boot-camel/pom.xml +++ b/spring-boot-camel/pom.xml @@ -38,6 +38,12 @@ spring-boot-starter-web ${spring-boot-starter.version} + + org.springframework.boot + spring-boot-starter-test + ${spring-boot-starter.version} + test + diff --git a/spring-boot-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6eee0abf1e --- /dev/null +++ b/spring-boot-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.camel.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..97debc5b63 --- /dev/null +++ b/spring-boot-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.boot.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c9f7220ab9 --- /dev/null +++ b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.parent.App; + +public class SpringContextIntegrationTest { + + @Test + public final void testMain() throws Exception { + App.main(new String[] {}); + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml index 9c2d85da86..5862bdd6c8 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml @@ -40,6 +40,13 @@ ${greeter.version} true + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9c8d825ea4 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.greeter.autoconfigure.GreeterAutoConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = GreeterAutoConfiguration.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..23f285238b --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.greeter.sample.GreeterSampleApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GreeterSampleApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-h2/README.md b/spring-boot-h2/README.md new file mode 100644 index 0000000000..af5f395440 --- /dev/null +++ b/spring-boot-h2/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps) 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/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-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f48199d4e8 --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.h2db.demo.ClientSpringBootApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ClientSpringBootApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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-jasypt/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..dce3819a26 --- /dev/null +++ b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jasypt.Main; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Main.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7367568611 --- /dev/null +++ b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.keycloak.SpringBoot; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBoot.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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-logging-log4j2/spring-boot-logging-log4j2-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2d46b21ba5 --- /dev/null +++ b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootlogging.SpringBootLoggingApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootLoggingApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index e456155f36..65d23ebfc6 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,16 @@ org.springframework.boot spring-boot-starter-web + + org.apache.tomcat.embed + tomcat-embed-jasper + + + + org.glassfish + javax.faces + 2.3.7 + org.springframework.boot @@ -46,16 +54,18 @@ org.springframework.boot spring-boot-maven-plugin + + com.baeldung.springbootmvc.SpringBootMvcApplication + JAR + - UTF-8 - UTF-8 - 1.8 1.10.0 + com.baeldung.springbootmvc.SpringBootMvcApplication diff --git a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java new file mode 100644 index 0000000000..030216b747 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java @@ -0,0 +1,12 @@ +package com.baeldung.nosuchbeandefinitionexception; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BeanA { + + @Autowired + BeanB dependency; + +} \ No newline at end of file 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/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java new file mode 100644 index 0000000000..8709cf85ac --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java @@ -0,0 +1,12 @@ +package com.baeldung.nosuchbeandefinitionexception; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class NoSuchBeanDefinitionDemoApp { + + public static void main(String[] args) { + SpringApplication.run(NoSuchBeanDefinitionDemoApp.class, args); + } +} 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/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-boot-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6ed93e8c44 --- /dev/null +++ b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml index 958a07a86b..ab22c5ad30 100644 --- a/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -20,7 +20,14 @@ spring-boot-starter ${spring-boot.version} + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + diff --git a/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6dd3419d39 --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6dd3419d39 --- /dev/null +++ b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-security/README.md b/spring-boot-security/README.md index a79e7de610..30a3218672 100644 --- a/spring-boot-security/README.md +++ b/spring-boot-security/README.md @@ -9,3 +9,5 @@ ### Relevant Articles: - [Spring Boot Security Auto-Configuration](http://www.baeldung.com/spring-boot-security-autoconfiguration) +- [Spring Security for Spring Boot Integration Tests](https://www.baeldung.com/spring-security-integration-tests) +- [Introduction to Spring Security Taglibs](https://www.baeldung.com/spring-security-taglibs) diff --git a/spring-boot-vue/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-vue/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6ed93e8c44 --- /dev/null +++ b/spring-boot-vue/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 54382992d4..192c4f9fed 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -33,3 +33,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Container Configuration in Spring Boot 2](http://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) - [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey) - [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) +- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 50859f674c..0ea6b6156f 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -145,6 +145,20 @@ chaos-monkey-spring-boot ${chaos.monkey.version} + + + + + org.springframework.boot + spring-boot-starter-log4j + 1.3.8.RELEASE + + + org.graylog2 + gelfj + 1.1.16 + compile + @@ -224,4 +238,4 @@ 2.2.4 - \ No newline at end of file + diff --git a/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java b/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java new file mode 100644 index 0000000000..be49a0e927 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.graylog; + +import org.apache.log4j.Logger; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class GraylogDemoApplication { + + private final static Logger LOG = + Logger.getLogger(GraylogDemoApplication.class); + + public static void main(String[] args) { + SpringApplication.run(GraylogDemoApplication.class, args); + LOG.info("Hello from Spring Boot"); + } +} diff --git a/spring-boot/src/main/resources/log4j.xml b/spring-boot/src/main/resources/log4j.xml new file mode 100644 index 0000000000..61c1b7b229 --- /dev/null +++ b/spring-boot/src/main/resources/log4j.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-bus/pom.xml b/spring-cloud-bus/pom.xml new file mode 100644 index 0000000000..d493c4e984 --- /dev/null +++ b/spring-cloud-bus/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-bus + 1.0.0-SNAPSHOT + pom + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + spring-cloud-config-client + spring-cloud-config-server + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud-dependencies.version} + pom + import + + + + + + Brixton.SR7 + + + diff --git a/spring-cloud-bus/spring-cloud-config-client/pom.xml b/spring-cloud-bus/spring-cloud-config-client/pom.xml index bd9fb45587..b2b69303bf 100644 --- a/spring-cloud-bus/spring-cloud-config-client/pom.xml +++ b/spring-cloud-bus/spring-cloud-config-client/pom.xml @@ -1,76 +1,53 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + spring-cloud-config-client + jar - com.baeldung.spring.cloud - spring-cloud-config-client - 0.0.1-SNAPSHOT - jar + spring-cloud-config-client + Demo Spring Cloud Config Client - spring-cloud-config-client - Demo Spring Cloud Config Client + + spring-cloud-bus + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT + - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.boot + spring-boot-starter-web + - - - org.springframework.cloud - spring-cloud-starter-config - - - org.springframework.boot - spring-boot-starter-web - + + org.springframework.boot + spring-boot-starter-test + test + - - org.springframework.boot - spring-boot-starter-test - test - + + org.springframework.boot + spring-boot-actuator + - - org.springframework.boot - spring-boot-actuator - + + org.springframework.cloud + spring-cloud-starter-bus-amqp + + - - org.springframework.cloud - spring-cloud-starter-bus-amqp - - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - UTF-8 - UTF-8 - 1.8 - Dalston.SR1 - + + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 56% rename from spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java rename to spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 19ad9676cb..c0298daeb1 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java +++ b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,13 +1,15 @@ -package com.baeldung.spring.cloud.kubernetes.frontend; +package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.SpringCloudConfigClientApplication; + @RunWith(SpringRunner.class) -@SpringBootTest -public class KubernetesFrontendApplicationIntegrationTest { +@SpringBootTest(classes = SpringCloudConfigClientApplication.class) +public class SpringContextIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-bus/spring-cloud-config-server/pom.xml b/spring-cloud-bus/spring-cloud-config-server/pom.xml index 194289ea1e..f50b78ff18 100644 --- a/spring-cloud-bus/spring-cloud-config-server/pom.xml +++ b/spring-cloud-bus/spring-cloud-config-server/pom.xml @@ -1,77 +1,54 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + spring-cloud-config-server + jar - com.baeldung.spring.cloud - spring-cloud-config-server - 0.0.1-SNAPSHOT - jar + spring-cloud-config-server + Demo Spring Cloud Config Server - spring-cloud-config-server - Demo Spring Cloud Config Server + + spring-cloud-bus + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT + - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - + + + org.springframework.cloud + spring-cloud-config-server + - - - org.springframework.cloud - spring-cloud-config-server - + + org.springframework.boot + spring-boot-starter-security + - - org.springframework.boot - spring-boot-starter-security - + + org.springframework.boot + spring-boot-starter-test + test + - - org.springframework.boot - spring-boot-starter-test - test - + + org.springframework.cloud + spring-cloud-config-monitor + - - org.springframework.cloud - spring-cloud-config-monitor - + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + + - - org.springframework.cloud - spring-cloud-starter-stream-rabbit - - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - UTF-8 - UTF-8 - 1.8 - Dalston.SR1 - + + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationTests.java b/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationIntegrationTest.java similarity index 81% rename from spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationTests.java rename to spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationIntegrationTest.java index 3969c7ba2d..12e0928ad8 100644 --- a/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationTests.java +++ b/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class SpringCloudConfigServerApplicationTests { +public class SpringCloudConfigServerApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c43bb9f067 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringCloudConfigServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudConfigServerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b87ace74a4 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.JobConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ContextConfiguration(classes = JobConfiguration.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..eb2a5c54ef --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.DataFlowServerApplication; +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(classes = DataFlowServerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..28dbc9a8d8 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.DataFlowShellApplication; +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(classes = DataFlowShellApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8dc814ddce --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.LogSinkApplication; +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(classes = LogSinkApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..dcfeafa2bb --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.TimeProcessorApplication; +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(classes = TimeProcessorApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2c402824f0 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.TimeSourceApplication; +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(classes = TimeSourceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java deleted file mode 100644 index 6d71a785a3..0000000000 --- a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.spring.cloud; - -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 TimeSourceApplicationIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 7d180047de..924ea2be36 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -33,6 +33,10 @@ spring-cloud-contract spring-cloud-kubernetes spring-cloud-archaius + spring-cloud-functions + spring-cloud-vault + spring-cloud-security + spring-cloud-task diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e5ebbce1aa --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.archaius.additionalsources.AdditionalSourcesSimpleApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AdditionalSourcesSimpleApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..16542981e8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.archaius.basic.BasicArchaiusApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BasicArchaiusApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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/extra-configs/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4c2531f490 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.archaius.extraconfigs.ExtraConfigsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ExtraConfigsApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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-aws/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..fcba9c4132 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.aws.InstanceProfileAwsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = InstanceProfileAwsApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6016788eab --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.config.ConfigApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/discovery/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6016788eab --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/discovery/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.config.ConfigApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1e2db33395 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.discovery.DiscoveryApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DiscoveryApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ef3bb5ef95 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.gateway.GatewayApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GatewayApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0ffc2410e3 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.svcbook.BookServiceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookServiceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3589666f17 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.svcrating.RatingServiceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = RatingServiceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4403d9e93b --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.zipkin.ZipkinApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ZipkinApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-config/client/pom.xml b/spring-cloud/spring-cloud-config/client/pom.xml index bd8c817256..800a496a82 100644 --- a/spring-cloud/spring-cloud-config/client/pom.xml +++ b/spring-cloud/spring-cloud-config/client/pom.xml @@ -15,18 +15,15 @@ org.springframework.cloud spring-cloud-starter-config - ${spring-cloud-starter-config.version} - + org.springframework.boot spring-boot-starter-web - ${org.springframework.boot.version} - + org.springframework.boot spring-boot-starter-test - ${org.springframework.boot.version} test @@ -40,8 +37,4 @@ - - 1.2.2.RELEASE - 1.4.2.RELEASE - diff --git a/spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java b/spring-cloud/spring-cloud-config/client/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 76% rename from spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java rename to spring-cloud/spring-cloud-config/client/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 9bca369c64..d727772cf9 100644 --- a/spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java +++ b/spring-cloud/spring-cloud-config/client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloud.config.client; +package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; @@ -6,10 +6,12 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import com.baeldung.spring.cloud.config.client.ConfigClient; + @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ConfigClient.class) @WebAppConfiguration -public class ConfigClientLiveTest { +public class SpringContextIntegrationTest { @Test public void contextLoads() { } diff --git a/spring-cloud/spring-cloud-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml index 61b27244b6..7bbb903cf9 100644 --- a/spring-cloud/spring-cloud-config/server/pom.xml +++ b/spring-cloud/spring-cloud-config/server/pom.xml @@ -15,23 +15,19 @@ org.springframework.cloud spring-cloud-config-server - ${spring-cloud-config-server.version} - + org.springframework.boot spring-boot-starter-security - ${org.springframework.boot.version} - + org.springframework.boot spring-boot-starter-web - ${org.springframework.boot.version} - + org.springframework.boot spring-boot-starter-test - ${org.springframework.boot.version} test @@ -41,14 +37,8 @@ org.springframework.boot spring-boot-maven-plugin - ${org.springframework.boot.version} - + - - 1.2.2.RELEASE - 1.4.2.RELEASE - - diff --git a/spring-cloud/spring-cloud-config/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-config/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..cd30392d4f --- /dev/null +++ b/spring-cloud/spring-cloud-config/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.cloud.config.server.ConfigServer; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = ConfigServer.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + @Test + public void contextLoads() { + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a705f18bc6 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.connectors.heroku.ConnectorsHerokuApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConnectorsHerokuApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-consul/pom.xml b/spring-cloud/spring-cloud-consul/pom.xml index 8181832bea..2a2714d597 100644 --- a/spring-cloud/spring-cloud-consul/pom.xml +++ b/spring-cloud/spring-cloud-consul/pom.xml @@ -25,6 +25,13 @@ spring-cloud-starter-consul-config ${spring-cloud-starter-consul.version} + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-cloud/spring-cloud-consul/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-consul/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6290ccc03e --- /dev/null +++ b/spring-cloud/spring-cloud-consul/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.consul.discovery.DiscoveryClientApplication; +import com.baeldung.spring.cloud.consul.health.ServiceDiscoveryApplication; +import com.baeldung.spring.cloud.consul.properties.DistributedPropertiesApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { DiscoveryClientApplication.class, ServiceDiscoveryApplication.class, + DistributedPropertiesApplication.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1c1192cc3f --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.springcloudcontractconsumer.SpringCloudContractConsumerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractConsumerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2b6703ae5c --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.springcloudcontractproducer.SpringCloudContractProducerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractProducerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml index c7822d51ee..8bc51adcab 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml @@ -28,6 +28,24 @@ spring-boot-starter-web ${spring-boot-starter-web.version} + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + + + org.springframework.boot + spring-boot-test + 1.5.10.RELEASE + test + + + org.springframework + spring-test + 4.0.5.RELEASE + test + 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 new file mode 100644 index 0000000000..8b2b0ad385 --- /dev/null +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -0,0 +1,94 @@ + + + 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/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java new file mode 100644 index 0000000000..34e97d3b6c --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.cloudfunction.aws; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +@SpringBootApplication +public class CloudFunctionAwsApplication { + + public static void main(String[] args) { + SpringApplication.run(CloudFunctionAwsApplication.class, args); + } + + @Bean + public Function reverseString() { + return value -> new StringBuilder(value).reverse().toString(); + } + +} diff --git a/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java new file mode 100644 index 0000000000..52514dcd12 --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.cloudfunction.aws; + +import org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler; + +public class StringReverseHandler extends SpringBootRequestHandler { + +} diff --git a/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java new file mode 100644 index 0000000000..c443b98c18 --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.cloudfunction.functions.aws; + +import java.util.function.Function; + +public class Greeter implements Function { + + @Override + public String apply(String s) { + return "Hello " + s + ", and welcome to Spring Cloud Function!!!"; + } +} diff --git a/spring-cloud/spring-cloud-functions/src/main/resources/application.properties b/spring-cloud/spring-cloud-functions/src/main/resources/application.properties new file mode 100644 index 0000000000..b445bfa4ed --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/main/resources/application.properties @@ -0,0 +1 @@ +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/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java new file mode 100644 index 0000000000..6039debe3f --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java @@ -0,0 +1,33 @@ +package com.baeldung.spring.cloudfunction.aws; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class CloudFunctionApplicationTests { + + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate testRestTemplate; + + @Test + public void givenAString_whenReverseStringCloudFunctionInvoked_thenStringIsReversed() { + assertThat(this.testRestTemplate.getForObject("http://localhost:" + port + "/reverseString/HelloWorld", String.class)).isEqualTo("dlroWolleH"); + } + + @Test + public void givenAString_whenGreeterCloudFunctionInvoked_thenPrintsGreeting() { + assertThat(this.testRestTemplate.getForObject("http://localhost:" + port + "/greeter/BaeldungUser", String.class)).isEqualTo("Hello BaeldungUser, and welcome to Spring Cloud Function!!!"); + } + +} diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index 8babbff274..4d8b57d4cf 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -38,6 +38,11 @@ org.springframework.boot spring-boot-starter-webflux + + org.springframework.boot + spring-boot-starter-test + test + org.hibernate diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f2addf5c1a --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.GatewayApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GatewayApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml index ce1e1856ed..11b9275b46 100644 --- a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml @@ -24,33 +24,32 @@ org.springframework.cloud spring-cloud-starter-hystrix - ${spring-cloud-starter-hystrix.version} org.springframework.cloud spring-cloud-starter-hystrix-dashboard - ${spring-cloud-starter-hystrix.version} org.springframework.cloud spring-cloud-starter-feign - ${spring-cloud-starter-feign.version} org.springframework.boot spring-boot-starter-web - ${spring-boot-starter-web.version} org.springframework.boot spring-boot-starter-thymeleaf - ${spring-boot-starter-web.version} org.springframework.boot spring-boot-starter-actuator - ${spring-boot-starter-web.version} + + org.springframework.boot + spring-boot-starter-test + test + diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java deleted file mode 100644 index 2440b97aaf..0000000000 --- a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.spring.cloud.kubernetes.backend; - -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 KubernetesBackendApplicationIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ce57cf5052 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.kubernetes.backend.KubernetesBackendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesBackendApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f7e9e35540 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.kubernetes.frontend.KubernetesFrontendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesFrontendApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..24e758ff82 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +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(classes = BooksApiApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapApplicationIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 72% rename from spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapApplicationIntegrationTest.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 7c54288665..28c6e67377 100644 --- a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapApplicationIntegrationTest.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -6,10 +6,10 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest -public class SpringBootBootstrapApplicationIntegrationTest { - +@SpringBootTest(classes = SpringCloudRestConfigApplication.class) +public class SpringContextIntegrationTest { @Test public void contextLoads() { } + } diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e22359a016 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +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(classes = SpringCloudRestServerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..07d7db0505 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +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(classes = BookReviewsApiApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..baa1b12eff --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ServerLocationApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientLiveTest.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 64% rename from spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientLiveTest.java rename to spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 364368713a..60a208d6f4 100644 --- a/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientLiveTest.java +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,13 +1,15 @@ -package com.baeldung; +package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.CloudSite; + @RunWith(SpringRunner.class) -@SpringBootTest -public class SpringCloudConfigClientLiveTest { +@SpringBootTest(classes = CloudSite.class) +public class SpringContextIntegrationTest { @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-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 64% rename from spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java rename to spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 5ab3292388..4d4c312bce 100644 --- a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java +++ b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,13 +1,15 @@ -package org.baeldung.spring.cloud; +package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.Application; + @RunWith(SpringRunner.class) -@SpringBootTest -public class DataFlowShellApplicationIntegrationTest { +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { @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-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 64% rename from spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java rename to spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 9bd0fd8c24..63a89ac45c 100644 --- a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java +++ b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,13 +1,15 @@ -package org.baeldung.spring.cloud; +package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.AuthServer; + @RunWith(SpringRunner.class) -@SpringBootTest -public class TimeProcessorApplicationIntegrationTest { +@SpringBootTest(classes = AuthServer.class) +public class SpringContextIntegrationTest { @Test public void contextLoads() { 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-cloud/spring-cloud-stream-starters/twitter/twitter b/spring-cloud/spring-cloud-stream-starters/twitter/twitter deleted file mode 160000 index f9673ef0c1..0000000000 --- a/spring-cloud/spring-cloud-stream-starters/twitter/twitter +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f9673ef0c11c51b327555aaca61ee196935f998b diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml index bf725da5cf..6f582576d8 100644 --- a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml @@ -1,11 +1,11 @@ - - + + 4.0.0 com.baeldung.twitterhdfs twitterhdfs jar - 1.0.0 + 1.0.0-SNAPSHOT twitterhdfs @@ -45,9 +45,6 @@ - UTF-8 - UTF-8 - 1.8 1.3.1.RELEASE diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3d370e7b48 --- /dev/null +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.twitterhdfs.aggregate.AggregateApp; +import com.baeldung.twitterhdfs.processor.ProcessorApp; +import com.baeldung.twitterhdfs.sink.SinkApp; +import com.baeldung.twitterhdfs.source.SourceApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {AggregateApp.class, ProcessorApp.class, SinkApp.class, SourceApp.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..70c5f46aa1 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.stream.rabbit.MultipleOutputsServiceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MultipleOutputsServiceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-task/pom.xml b/spring-cloud/spring-cloud-task/pom.xml new file mode 100644 index 0000000000..ef76d464bc --- /dev/null +++ b/spring-cloud/spring-cloud-task/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-task + 1.0.0-SNAPSHOT + pom + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 + + + + springcloudtaskbatch + springcloudtasksink + + + + + + org.springframework.cloud + spring-cloud-task-dependencies + ${spring-cloud-task.version} + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud-dependencies.version} + pom + import + + + + + + Brixton.SR7 + 1.2.2.RELEASE + + + diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml index f97d78099f..89c9318c4e 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -3,14 +3,12 @@ 4.0.0 org.baeldung.cloud springcloudtaskbatch - 0.0.1-SNAPSHOT - springcloudtaskbatch + springcloudtaskbatch - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + spring-cloud-task + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT @@ -47,18 +45,6 @@ - - - - org.springframework.cloud - spring-cloud-task-dependencies - ${spring-cloud-task.version} - pom - import - - - - @@ -70,10 +56,6 @@ com.baeldung.TaskDemo - UTF-8 - UTF-8 - 1.8 - 1.2.2.RELEASE diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4b5aff2db8 --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.task.JobConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = JobConfiguration.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml index fdcbabdd51..ca0de342a9 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml @@ -2,19 +2,15 @@ 4.0.0 - - com.baeldung SpringCloudTaskSink - 0.0.1-SNAPSHOT jar SpringCloudTaskSink Demo project for Spring Boot - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + + spring-cloud-task + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT @@ -36,11 +32,6 @@ spring-boot-starter-test test - - org.springframework.boot - spring-boot-starter-test - test - org.springframework.cloud @@ -49,25 +40,6 @@ - - - - org.springframework.cloud - spring-cloud-task-dependencies - ${spring-cloud-task.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - @@ -78,11 +50,7 @@ - UTF-8 - UTF-8 - 1.8 1.2.2.RELEASE - Edgware.SR2 1.3.0.RELEASE diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationTests.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationIntegrationTest.java similarity index 97% rename from spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationTests.java rename to spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationIntegrationTest.java index 1f47eada14..104c04138e 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationTests.java +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationIntegrationTest.java @@ -24,7 +24,7 @@ import static org.mockito.Mockito.verify; @RunWith(SpringRunner.class) @SpringBootTest( classes = SpringCloudTaskSinkApplication.class) -public class SpringCloudTaskSinkApplicationTests { +public class SpringCloudTaskSinkApplicationIntegrationTest { @Autowired ApplicationContext context; diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b8dd03d65f --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringCloudTaskFinal.SpringCloudTaskSinkApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudTaskSinkApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-h2/spring-boot-h2-remote-app/.gitignore b/spring-cloud/spring-cloud-vault/.gitignore similarity index 85% rename from spring-boot-h2/spring-boot-h2-remote-app/.gitignore rename to spring-cloud/spring-cloud-vault/.gitignore index 82eca336e3..e6237b6f81 100644 --- a/spring-boot-h2/spring-boot-h2-remote-app/.gitignore +++ b/spring-cloud/spring-cloud-vault/.gitignore @@ -22,4 +22,8 @@ /nbbuild/ /dist/ /nbdist/ -/.nb-gradle/ \ No newline at end of file +/.nb-gradle/ + +## Extra +/vault-data/ +*.log diff --git a/spring-cloud/spring-cloud-vault/database-setup.sql b/spring-cloud/spring-cloud-vault/database-setup.sql new file mode 100644 index 0000000000..4bb1293f74 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/database-setup.sql @@ -0,0 +1,20 @@ +-- +-- Sample schema for testing vault database secrets +-- +create schema fakebank; +use fakebank; +create table account( + id decimal(16,0), + name varchar(30), + branch_id decimal(16,0), + customer_id decimal(16,0), + primary key (id)); + +-- +-- MySQL user that will be used by Vault to create other users on demand +-- +create user 'fakebank-admin'@'%' identified by 'Sup&rSecre7!' +grant all privileges on fakebank.* to 'fakebank-admin'@'%' with grant option; +grant create user on *.* to 'fakebank-admin' with grant option; + +flush privileges; diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml new file mode 100644 index 0000000000..68b8e44875 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + spring-cloud-vault + jar + + spring-cloud-vault + Demo project for Spring Boot + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + UTF-8 + UTF-8 + 1.8 + Finchley.SR1 + + + + + + + + + org.springframework.cloud + spring-cloud-starter-vault-config + + + + org.springframework.cloud + spring-cloud-vault-config-databases + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + mysql + mysql-connector-java + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud/spring-cloud-vault/sample-policy.hcl b/spring-cloud/spring-cloud-vault/sample-policy.hcl new file mode 100644 index 0000000000..554888661e --- /dev/null +++ b/spring-cloud/spring-cloud-vault/sample-policy.hcl @@ -0,0 +1,6 @@ +path "secret/fakebank" { + capabilities = ["read"] + allowed_parameters = { + "api_key" = [] + } +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java new file mode 100644 index 0000000000..81ece1ca4c --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java @@ -0,0 +1,12 @@ +package org.baeldung.spring.cloud.vaultsample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class VaultSampleApplication { + + public static void main(String[] args) { + SpringApplication.run(VaultSampleApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/application.yml b/spring-cloud/spring-cloud-vault/src/main/resources/application.yml new file mode 100644 index 0000000000..3d347ec855 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + application: + name: fakebank + + datasource: + url: jdbc:mysql://localhost:3306/fakebank diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml b/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml new file mode 100644 index 0000000000..1e837c4920 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml @@ -0,0 +1,37 @@ +spring: + cloud: + vault: + uri: https://localhost:8200 + connection-timeout: 5000 + read-timeout: 15000 + config: + order: -10 + + ssl: + trust-store: classpath:/vault.jks + trust-store-password: changeit + + generic: + enabled: true + application-name: fakebank + + kv: + enabled: false + backend: kv + application-name: fakebank + + database: + enabled: true + role: fakebank-accounts-rw +# backend: database +# username-property: spring.datasource.username +# password-property: spring.datasource.password + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/vault.jks b/spring-cloud/spring-cloud-vault/src/main/resources/vault.jks new file mode 100644 index 0000000000..7090707543 Binary files /dev/null and b/spring-cloud/spring-cloud-vault/src/main/resources/vault.jks differ diff --git a/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java new file mode 100644 index 0000000000..7a9c5ba11a --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java @@ -0,0 +1,66 @@ +package org.baeldung.spring.cloud.vaultsample; + +import static org.junit.Assert.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; + +import javax.sql.DataSource; + +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.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class VaultSampleApplicationLiveTest { + + @Autowired + Environment env; + + @Autowired + DataSource datasource; + + + @Test + public void whenGenericBackendEnabled_thenEnvHasAccessToVaultSecrets() { + + String fooValue = env.getProperty("foo"); + assertEquals("test-bar", fooValue); + + } + + @Test + public void whenKvBackendEnabled_thenEnvHasAccessToVaultSecrets() { + + String fooValue = env.getProperty("foo.versioned"); + assertEquals("bar1", fooValue); + + + } + + + @Test + public void whenDatabaseBackendEnabled_thenDatasourceUsesVaultCredentials() { + + try (Connection c = datasource.getConnection()) { + + ResultSet rs = c.createStatement() + .executeQuery("select 1"); + + rs.next(); + Long value = rs.getLong(1); + + assertEquals(Long.valueOf(1), value); + + } catch (SQLException sex) { + throw new RuntimeException(sex); + } + + } + +} diff --git a/spring-cloud/spring-cloud-vault/src/test/resources/bootstrap.properties b/spring-cloud/spring-cloud-vault/src/test/resources/bootstrap.properties new file mode 100644 index 0000000000..8c54227dda --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/resources/bootstrap.properties @@ -0,0 +1,3 @@ +spring.cloud.vault.token=b93d1b0d-15b5-f69e-d311-352a65fa7bc8 + +logging.level.org.springframework=INFO \ No newline at end of file diff --git a/spring-cloud/spring-cloud-vault/src/test/resources/vault.jks b/spring-cloud/spring-cloud-vault/src/test/resources/vault.jks new file mode 100644 index 0000000000..7090707543 Binary files /dev/null and b/spring-cloud/spring-cloud-vault/src/test/resources/vault.jks differ diff --git a/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.cert b/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.cert new file mode 100644 index 0000000000..6a598df419 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.cert @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC+zCCAeOgAwIBAgIJAKoy5OBgOKYwMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV +BAMMCWxvY2FsaG9zdDAeFw0xODA4MDkwMTM1MzJaFw0yODA4MDYwMTM1MzJaMBQx +EjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAMXiHqB5dYdxJ1+abSG55gb3NNo3fzNbkjp/tAIl1FUeyCyyP/yERrkUkhFj +4gg/q1YHUO/ftc0PdL/JBaVBTKnzsxgp7hY/dUEkZqXZ649X0UrJIRd13w5N71cL +P1+PjCrqokMVceU18kK7CyaOmiTKYFmt/RTJQLmFQspmJXNSiq7zUvAgyvoY5TzJ +n7MuSobHXq17pnlm+XbnAgDJUt9yR6BC2dFF20iZU4uTXy2VRngfLey3p+6in0TO +jD4cEMJqwgUbjiI8m/hESCketVkq0W0qkkVfWBNzz5qqGHNRbhZBwT7SM0MuXum+ +qEY7n7jcQAk5BDb613liVQjQ0tkCAwEAAaNQME4wHQYDVR0OBBYEFHYjQ0/HJgXd +BnqM4jLPjmygfi8fMB8GA1UdIwQYMBaAFHYjQ0/HJgXdBnqM4jLPjmygfi8fMAwG +A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBABSf++sinLT9dFnC+B6ut5Zp +haTL7PA1/CdmhTdE2vlFPGGw2BD4c/gphBsHKSNHE96irTqFXI/kl6labQpZ5P8G +JORLfaAyl58UT1FayxL4ISzwsp+UrqO60vxkYyLkbEJjuaxIv11oOoFDIp5oBTqe +BVoCfcTjYtTr+IwwlypLPrVTnDNGX5oPIBbTUFvR0t5RaLZgmXLT78ERhWOLINqh +Yi6j7fYaRm/C5IQ8N/TASot7V0SMH2Rt6PrzJb5SLV8r+yozg2BSfU6hZUyKwABR +N3zppKvKzdhlVo9OuSW3x4Tb3V+CVE/8CmTwRfhab9SCmvmaa2FxI+8/2OPVWDU= +-----END CERTIFICATE----- diff --git a/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.key b/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.key new file mode 100644 index 0000000000..eba611823a --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAxeIeoHl1h3EnX5ptIbnmBvc02jd/M1uSOn+0AiXUVR7ILLI/ +/IRGuRSSEWPiCD+rVgdQ79+1zQ90v8kFpUFMqfOzGCnuFj91QSRmpdnrj1fRSskh +F3XfDk3vVws/X4+MKuqiQxVx5TXyQrsLJo6aJMpgWa39FMlAuYVCymYlc1KKrvNS +8CDK+hjlPMmfsy5KhsderXumeWb5ducCAMlS33JHoELZ0UXbSJlTi5NfLZVGeB8t +7Len7qKfRM6MPhwQwmrCBRuOIjyb+ERIKR61WSrRbSqSRV9YE3PPmqoYc1FuFkHB +PtIzQy5e6b6oRjufuNxACTkENvrXeWJVCNDS2QIDAQABAoIBACEyB5VACtlHwCUn +kLshplbwzWr1+F6zM9qgZaAenHoTCd2FoXpI7lxJ+R71tItRsvphi9BRpPvbZehu +XoYUaDnyac7Z6djNmGvvIVEdN4j6YF+9UdHPsjWCGW5uspjjSc5BQisiw9KBtDxB +iGNVdMJLONKSf2wnPrZgho3RiOLJX/poPyGTkMHuhBVvo4oy7Ax3XalaAcufgqwm +YBQJ1Tka+33EUiLkxzJTXxNbIAI2scP8jhGn6mokS0V4gZPxJKUZEyydXRWwi6ex +ua/7q76ELJS5b+xKRYfGsvavFDx8R+LqX8oegALD33ki3rm1MQW7GmikRL98+EVW +Q9mQsqECgYEA/IrP8vycbJOgn1vriNItFcZtczSBlrXCRF0up2cqKMs9c+T5i51x +ZKXK5lo3DfMT+YDM+iiGZ9+vM0UA2VxbFD3XV9mQDBaNC+Duknqxx+OLmWva9YwR +nMaevqVV9LCn+GgUcK+IygEnpzpdP4q8YcXAfGAnZgnihN/AUYAaB70CgYEAyJe4 +yO0S9gAH5aoDdooL0YXrH/Dzd+fAgNsawLhoOltcoZqZFWeAllM0GsrCpfTRltuy +dn9ca3YK0GlWl7h5rDle1HO3nhp1FcpeG1oxmkeQta3PG66uUuMccTAljCLFrEe3 +DguH8+qdjhLk+ZnUB9AVkS79pzdwuEHVljCK600CgYB6mMygkh9B2lzkX9Q0xItc +gcqKXdf3GN9pHq9SVxOxYBDCHUtDirgMeyvHrc4COJneyrc3TcsJzB4aToo9+sbA +SdErdZOnOp9YP+axN1zsw7r2TNSr1UaLjCRuOodC1SuFvMkHdz95iRv946h2+1u+ +PyjVeDxIHc5YYOLU7dI1JQKBgQDF5KDBYNm25brkwcCe3nvgXfzjyyN25KUOupn/ +DS6Oe/m72Lgz3KOIKleaIvS7IvbunJnIu8dioNb0Wye5kJ5A4WyDrhG1IabnM3l6 +BJYw/W9vPSS4y7FhRnuV0wkH4nofh7S5X3jlk02Sj2NkN3Vtq8TLMY++uzwyG4jq +ncM/dQKBgQC+6mA5OfbVN4lRn+zrSiIH5gpvZYPh9wXeTnDWHa13sJsu3e8AQxtk +TfE0W13UV5jhGL8Wvyyxn+doGFTdcZapOlwuoQ6RcgHcVQm2sOl60GAa4idmm0A6 +TcgnIOTyVRlNBoWLCfN83BlGz4gcDpnuZZ/0JuguixgLS323hQlLvg== +-----END RSA PRIVATE KEY----- diff --git a/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl b/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl new file mode 100644 index 0000000000..c880f2d744 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl @@ -0,0 +1,20 @@ +/* + * Sample configuration file for tests + */ + +// Enable UI +ui = true + +// Filesystem storage +storage "file" { + path = "./vault-data" +} + +// TCP Listener using a self-signed certificate +listener "tcp" { + address = "127.0.0.1:8200" + tls_cert_file = "./src/test/vault-config/localhost.cert" + tls_key_file = "./src/test/vault-config/localhost.key" +} + + diff --git a/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt b/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt new file mode 100644 index 0000000000..b965a95321 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt @@ -0,0 +1,82 @@ +== Vault server bootstrap + +1. Run vaul-start in one shell + +2. Open another shell and execute the command below: +> vault operator init + +Vault will output the unseal keys and root token: STORE THEM SAFELY !!! + +Example output: +Unseal Key 1: OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o +Unseal Key 2: iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT +Unseal Key 3: K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF +Unseal Key 4: +5zhysLAO4hIdZs0kiZpkrRovw11uQacfloiBwnZBJA/ +Unseal Key 5: GDwSq18lXV3Cw4MoHsKIH137kuI0mdl36UiD9WxOdulc + +Initial Root Token: d341fdaf-1cf9-936a-3c38-cf5eec94b5c0 + +... + +== Admin token setup + +1. Set the VAULT_TOKEN environment variable with the root token value +export VAULT_TOKEN=d341fdaf-1cf9-936a-3c38-cf5eec94b5c0 (Linux) +set VAULT_TOKEN=d341fdaf-1cf9-936a-3c38-cf5eec94b5c0 (Windows) + +2. Create another admin token + +>vault token create -display-name=admin +Key Value +--- ----- +token 3779c3ca-9f5e-1d8f-3842-efa96d88de43 <=== this is the new root token +token_accessor 2dfa4031-973b-cf88-c749-ee6f520ecaea +token_duration ∞ +token_renewable false +token_policies ["root"] +identity_policies [] +policies ["root"] + +3. Create ~/.vault-secret with your root token +4. Unset the VAULT_TOKEN environment variable ! + +=== Test DB setup (MySQL only, for now) + +1. Create test db +2. Create admin account used to create dynamic accounts: + +create schema fakebank; +create user 'fakebank-admin'@'%' identified by 'Sup&rSecre7!' +grant all privileges on fakebank.* to 'fakebank-admin'@'%' with grant option; +grant create user on *.* to 'fakebank-admin' with grant option; +flush privileges; + + +=== Database secret backend setup +> vault secrets enable database + +==== Create db configuration +> vault write database/config/mysql-fakebank ^ + plugin_name=mysql-legacy-database-plugin ^ + connection_url="{{username}}:{{password}}@tcp(127.0.0.1:3306)/fakebank" ^ + allowed_roles="*" ^ + username="fakebank-admin" ^ + password="Sup&rSecre7!" + +==== Create roles +> vault write database/roles/fakebank-accounts-ro ^ + db_name=mysql-fakebank ^ + creation_statements="CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';GRANT SELECT ON fakebank.* TO '{{name}}'@'%';" ^ + default_ttl="1h" ^ + max_ttl="24h" + +> vault write database/roles/fakebank-accounts-rw ^ + db_name=mysql-fakebank ^ + creation_statements="CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';GRANT SELECT,INSERT,UPDATE ON fakebank.* TO '{{name}}'@'%';" ^ + default_ttl="1m" ^ + max_ttl="2m" + +=== Get credentials +> vault read database/creds/fakebank-accounts-rw + + diff --git a/spring-cloud/spring-cloud-vault/vault-env.bat b/spring-cloud/spring-cloud-vault/vault-env.bat new file mode 100644 index 0000000000..d7aa5da215 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-env.bat @@ -0,0 +1,5 @@ +@echo off +echo Setting environment variables to access local vault.. +set VAULT_ADDR=https://localhost:8200 +set VAULT_CACERT=%~dp0%/src/test/vault-config/localhost.cert +rem set VAULT_TLS_SERVER_NAME=localhost diff --git a/spring-cloud/spring-cloud-vault/vault-env.sh b/spring-cloud/spring-cloud-vault/vault-env.sh new file mode 100644 index 0000000000..06077cee2e --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-env.sh @@ -0,0 +1,6 @@ +#!/bin/bash +echo Setting environment variables to access local vault.. +SCRIPTPATH=$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd ) +export VAULT_ADDR=https://localhost:8200 +export VAULT_CACERT=$SCRIPTPATH/src/test/vault-config/localhost.cert +export VAULT_TLS_SERVER_NAME=localhost diff --git a/spring-cloud/spring-cloud-vault/vault-start.bat b/spring-cloud/spring-cloud-vault/vault-start.bat new file mode 100644 index 0000000000..e8f6ce4c9f --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-start.bat @@ -0,0 +1,3 @@ +echo Starting vault server... +pushd %~dp0% +vault server -config %~dp0%/src/test/vault-config/vault-test.hcl diff --git a/spring-cloud/spring-cloud-vault/vault-start.sh b/spring-cloud/spring-cloud-vault/vault-start.sh new file mode 100644 index 0000000000..d5af7cfee6 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-start.sh @@ -0,0 +1,5 @@ +#!/bin/bash +SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )" +pushd $SCRIPTPATH +echo Starting vault server... +vault server -config $SCRIPTPATH/src/test/vault-config/vault-test.hcl diff --git a/spring-cloud/spring-cloud-vault/vault-unseal.bat b/spring-cloud/spring-cloud-vault/vault-unseal.bat new file mode 100644 index 0000000000..8133f90892 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-unseal.bat @@ -0,0 +1,7 @@ + +call %~dp0%/vault-env.bat + +vault operator unseal OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o +vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT +vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT +vault operator unseal K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF diff --git a/spring-cloud/spring-cloud-vault/vault-unseal.sh b/spring-cloud/spring-cloud-vault/vault-unseal.sh new file mode 100644 index 0000000000..699b383801 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-unseal.sh @@ -0,0 +1,8 @@ +#!/bin/bash +SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )" +. $SCRIPTPATH/vault-env.sh + +# Please replace the unseal keys below for your own +vault operator unseal OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o +vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT +vault operator unseal K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0f544b3ed1 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GreetingApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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/main/java/com/baeldung/dependency/exception/app/CustomConfiguration.java b/spring-core/src/main/java/com/baeldung/dependency/exception/app/SpringDependenciesExampleApplication.java similarity index 73% rename from spring-core/src/main/java/com/baeldung/dependency/exception/app/CustomConfiguration.java rename to spring-core/src/main/java/com/baeldung/dependency/exception/app/SpringDependenciesExampleApplication.java index 4366cb617a..e45438a9fe 100644 --- a/spring-core/src/main/java/com/baeldung/dependency/exception/app/CustomConfiguration.java +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/app/SpringDependenciesExampleApplication.java @@ -6,8 +6,8 @@ import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = "com.baeldung.dependency.exception") -public class CustomConfiguration { +public class SpringDependenciesExampleApplication { public static void main(String[] args) { - SpringApplication.run(CustomConfiguration.class, args); + SpringApplication.run(SpringDependenciesExampleApplication.class, args); } } 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-cucumber/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cucumber/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..80efd86f13 --- /dev/null +++ b/spring-cucumber/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringDemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDemoApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-custom-aop/pom.xml b/spring-custom-aop/pom.xml index fd5f87a476..f0b1dbb5ac 100644 --- a/spring-custom-aop/pom.xml +++ b/spring-custom-aop/pom.xml @@ -149,6 +149,7 @@ 3.1.7 8.5.11 18.0 + 8.0.43 diff --git a/spring-custom-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0384c67e26 --- /dev/null +++ b/spring-custom-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,25 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.annotation.servletcomponentscan.SpringBootAnnotatedApp; +import com.baeldung.annotation.servletcomponentscan.SpringBootPlainApp; +import com.baeldung.git.CommitIdApplication; +import com.baeldung.internationalization.InternationalizationApp; +import com.baeldung.intro.App; +import com.baeldung.servlets.ApplicationMain; +import com.baeldung.webjar.WebjarsdemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { SpringBootAnnotatedApp.class, SpringBootPlainApp.class, CommitIdApplication.class, + InternationalizationApp.class, App.class, ApplicationMain.class, Application.class, + WebjarsdemoApplication.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9c9d58dd0b --- /dev/null +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTestConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) +@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6f45039c96 --- /dev/null +++ b/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.es.config.Config; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = Config.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-jpa/README.md b/spring-data-jpa/README.md index 20e9d41839..8817020eec 100644 --- a/spring-data-jpa/README.md +++ b/spring-data-jpa/README.md @@ -11,6 +11,9 @@ - [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) - [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) +- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) +- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) +- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java new file mode 100644 index 0000000000..a575f0b915 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.MerchandiseEntity; +import org.springframework.data.repository.CrudRepository; + +public interface InventoryRepository extends CrudRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java b/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java new file mode 100644 index 0000000000..bfc690e0e2 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java @@ -0,0 +1,66 @@ +package com.baeldung.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.math.BigDecimal; + +@Entity +public class MerchandiseEntity { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String title; + + private BigDecimal price; + + private String brand; + + public MerchandiseEntity() { + } + + public MerchandiseEntity(String title, BigDecimal price) { + this.title = title; + this.price = price; + } + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public String getBrand() { + return brand; + } + + public void setBrand(String brand) { + this.brand = brand; + } + + @Override + public String toString() { + return "MerchandiseEntity{" + + "id=" + id + + ", title='" + title + '\'' + + ", price=" + price + + ", brand='" + brand + '\'' + + '}'; + } +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/InventoryRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/InventoryRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9d6334445c --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/InventoryRepositoryIntegrationTest.java @@ -0,0 +1,60 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.MerchandiseEntity; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.math.BigDecimal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class}) +public class InventoryRepositoryIntegrationTest { + + private static final String ORIGINAL_TITLE = "Pair of Pants"; + private static final String UPDATED_TITLE = "Branded Luxury Pants"; + private static final String UPDATED_BRAND = "Armani"; + private static final String ORIGINAL_SHORTS_TITLE = "Pair of Shorts"; + + @Autowired + private InventoryRepository repository; + + @Test + public void shouldCreateNewEntryInDB() { + MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); + pants = repository.save(pants); + + MerchandiseEntity shorts = new MerchandiseEntity(ORIGINAL_SHORTS_TITLE, new BigDecimal(3)); + shorts = repository.save(shorts); + + assertNotNull(pants.getId()); + assertNotNull(shorts.getId()); + assertNotEquals(pants.getId(), shorts.getId()); + } + + @Test + public void shouldUpdateExistingEntryInDB() { + MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); + pants = repository.save(pants); + + Long originalId = pants.getId(); + + pants.setTitle(UPDATED_TITLE); + pants.setPrice(BigDecimal.TEN); + pants.setBrand(UPDATED_BRAND); + + MerchandiseEntity result = repository.save(pants); + + assertEquals(originalId, result.getId()); + assertEquals(UPDATED_TITLE, result.getTitle()); + assertEquals(BigDecimal.TEN, result.getPrice()); + assertEquals(UPDATED_BRAND, result.getBrand()); + } +} diff --git a/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0a60412813 --- /dev/null +++ b/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,22 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-keyvalue/pom.xml b/spring-data-keyvalue/pom.xml index 6ab928303d..edd8967b97 100644 --- a/spring-data-keyvalue/pom.xml +++ b/spring-data-keyvalue/pom.xml @@ -1,9 +1,7 @@ 4.0.0 - com.baeldung spring-data-keyvalue - 1.0 parent-boot-2 @@ -13,7 +11,6 @@ - org.springframework.boot spring-boot-starter @@ -30,8 +27,4 @@ - - 2.0.3.RELEASE - - \ No newline at end of file diff --git a/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..d28bdcbc89 --- /dev/null +++ b/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.data.keyvalue.SpringDataKeyValueApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataKeyValueApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..04d549a288 --- /dev/null +++ b/spring-data-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.config.MongoConfig; +import com.baeldung.config.SimpleMongoConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MongoConfig.class, SimpleMongoConfig.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7f906bdbcd --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0380e3dc2f --- /dev/null +++ b/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringDataRestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index 4e4346e43b..7ac291740e 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -61,6 +61,12 @@ commons-fileupload ${commons-fileupload.version} + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8a9d3421c2 --- /dev/null +++ b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.springdispatcherservlet.configuration.AppConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-drools/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-drools/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..68325682e5 --- /dev/null +++ b/spring-drools/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.drools.service.TaxiFareConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TaxiFareConfiguration.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4d2d83646d --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springejbclient.SpringEjbClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringEjbClientApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-exceptions/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..492673b168 --- /dev/null +++ b/spring-exceptions/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.spring.config.CoreConfig; +import org.baeldung.spring.config.MvcConfig; +import org.baeldung.spring.config.PersistenceConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { CoreConfig.class, MvcConfig.class, PersistenceConfig.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-freemarker/pom.xml b/spring-freemarker/pom.xml index f0626195fd..4ff57e27f0 100644 --- a/spring-freemarker/pom.xml +++ b/spring-freemarker/pom.xml @@ -44,6 +44,13 @@ freemarker ${freemarker.version} + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-freemarker/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-freemarker/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ab0e6e8f49 --- /dev/null +++ b/spring-freemarker/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.freemarker.config.SpringWebConfig; +import com.baeldung.freemarker.config.WebConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringWebConfig.class, WebConfiguration.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java similarity index 97% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java rename to spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java index 91ca6dbfe9..dbefba5ba5 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java @@ -7,7 +7,7 @@ import java.io.File; import org.junit.Test; import org.springframework.context.support.GenericGroovyApplicationContext; -public class GroovyConfigurationTest { +public class GroovyConfigurationUnitTest { private static final String FILE_NAME = "GroovyBeanConfig.groovy"; private static final String FILE_PATH = "src/main/java/com/baeldug/groovyconfig/"; diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java similarity index 93% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java rename to spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java index 2d9b1000ff..c1e16f1b62 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java @@ -5,7 +5,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -public class JavaConfigurationTest { +public class JavaConfigurationUnitTest { @Test public void whenJavaConfig_thenCorrectPerson() { diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java similarity index 94% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java rename to spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java index 3ee724207c..b8d341ee39 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class XmlConfigurationTest { +public class XmlConfigurationUnitTest { @Test public void whenXmlConfig_thenCorrectPerson() { diff --git a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppTest.java b/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java similarity index 82% rename from spring-groovy/src/test/java/com/baeldug/spring_groovy/AppTest.java rename to spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java index 19eefb6c0f..3d8fa3e2d8 100644 --- a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppTest.java +++ b/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java @@ -7,7 +7,7 @@ import junit.framework.TestSuite; /** * Unit test for simple App. */ -public class AppTest +public class AppUnitTest extends TestCase { /** @@ -15,7 +15,7 @@ public class AppTest * * @param testName name of the test case */ - public AppTest( String testName ) + public AppUnitTest( String testName ) { super( testName ); } @@ -25,7 +25,7 @@ public class AppTest */ public static Test suite() { - return new TestSuite( AppTest.class ); + return new TestSuite( AppUnitTest.class ); } /** diff --git a/spring-hibernate4/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-hibernate4/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..af4618d0f3 --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-integration/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-integration/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..92e80a0903 --- /dev/null +++ b/spring-integration/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,21 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.si.security.MessageConsumer; +import com.baeldung.si.security.SecuredDirectChannel; +import com.baeldung.si.security.SecurityConfig; +import com.baeldung.si.security.SecurityPubSubChannel; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SecurityConfig.class, SecuredDirectChannel.class, SecurityPubSubChannel.class, + MessageConsumer.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8eb1589de7 --- /dev/null +++ b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringJenkinsPipelineApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringJenkinsPipelineApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 40dc91a88d..872835177d 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -118,6 +118,14 @@ 3.10.0 test + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-jersey/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-jersey/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..21f180854c --- /dev/null +++ b/spring-jersey/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.server.config.RestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jinq/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-jinq/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ccf774330f --- /dev/null +++ b/spring-jinq/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.jinq.JinqApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JinqApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index 949a78b2a1..814875f77b 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -33,6 +33,14 @@ activemq-all ${activemq.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-jms/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-jms/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e13809f571 --- /dev/null +++ b/spring-jms/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:EmbeddedActiveMQ.xml"}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..40bf86c76f --- /dev/null +++ b/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.kafka.KafkaApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KafkaApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-katharsis/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-katharsis/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..48081903b6 --- /dev/null +++ b/spring-katharsis/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9c233e6562 --- /dev/null +++ b/spring-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.ldap.javaconfig.AppConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mobile/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mobile/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7f906bdbcd --- /dev/null +++ b/spring-mobile/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mockito/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mockito/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7ce9f70302 --- /dev/null +++ b/spring-mockito/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.MocksApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MocksApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mustache/pom.xml b/spring-mustache/pom.xml index 4e7a1ba5a3..9e4c528ee0 100644 --- a/spring-mustache/pom.xml +++ b/spring-mustache/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-mustache - 0.0.1-SNAPSHOT jar spring-mustache Demo project for Spring Boot @@ -50,9 +48,6 @@ - UTF-8 - UTF-8 - 1.8 3.3.7 0.8 diff --git a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java similarity index 94% rename from spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java rename to spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java index 9138dfe92b..1eecf58986 100644 --- a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java +++ b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class SpringMustacheApplicationTests { +public class SpringMustacheApplicationIntegrationTest { @Autowired private TestRestTemplate restTemplate; diff --git a/spring-mvc-forms-jsp/pom.xml b/spring-mvc-forms-jsp/pom.xml index 6c75c9299b..5536314086 100644 --- a/spring-mvc-forms-jsp/pom.xml +++ b/spring-mvc-forms-jsp/pom.xml @@ -63,6 +63,12 @@ jackson-databind ${jackson-databind.version} + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java index b8b36df84e..2b2844e0de 100644 --- a/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java +++ b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java @@ -14,7 +14,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.baeldung.springmvcforms", "com.baeldung.jstl"}) -class ApplicationConfiguration implements WebMvcConfigurer { +public class ApplicationConfiguration implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c1e9b71550 --- /dev/null +++ b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import com.baeldung.springmvcforms.configuration.ApplicationConfiguration; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfiguration.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextIntegrationTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..da87a6830a --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung.listbindingexample; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.listbindingexample.ListBindingApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {ListBindingApplication.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextIntegrationTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e6b0dbf98c --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung.sessionattrs; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.sessionattrs.SessionAttrsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SessionAttrsApplication.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 44b1d65bc8..3a580202cf 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -30,3 +30,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) +- [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) +- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) diff --git a/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3649332870 --- /dev/null +++ b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.mvc.velocity.spring.config.WebConfig; +import com.baeldung.mvc.velocity.test.config.TestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-webflow/pom.xml b/spring-mvc-webflow/pom.xml index f7070efb94..e1a279a787 100644 --- a/spring-mvc-webflow/pom.xml +++ b/spring-mvc-webflow/pom.xml @@ -52,6 +52,14 @@ log4j-over-slf4j ${org.slf4j.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6f028c78d8 --- /dev/null +++ b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.WebFlowConfig; +import org.baeldung.spring.WebMvcConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {WebFlowConfig.class, WebMvcConfig.class}) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index fd33c25241..7187b5c270 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -86,6 +86,13 @@ + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java index 9752526963..22260fca70 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -1,11 +1,13 @@ package com.baeldung.spring; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @ImportResource("classpath:webMvcConfig.xml") @Configuration +@ComponentScan public class ClientWebConfig implements WebMvcConfigurer { public ClientWebConfig() { diff --git a/spring-mvc-xml/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ec34abd367 --- /dev/null +++ b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.ClientWebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ClientWebConfig.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java index 427613f23f..c1e5579103 100644 --- a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java +++ b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java @@ -31,7 +31,7 @@ public class StudentController { @RequestMapping(value = "/signup", method = RequestMethod.POST) public String signup(@Validated @ModelAttribute("student") Student student, BindingResult result, ModelMap model) { - if (studentService.getStudentByUserName(student.getUserName())) { + if (studentService.getStudentByUserName(student.getUserName()) != null) { model.addAttribute("message", "User Name exists. Try another user name"); return "signup"; } else { @@ -50,7 +50,7 @@ public class StudentController { @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(@ModelAttribute("studentLogin") StudentLogin studentLogin, BindingResult result, ModelMap model) { - boolean found = studentService.getStudentByLogin(studentLogin.getUserName(), studentLogin.getPassword()); + boolean found = studentService.getStudentByLogin(studentLogin.getUserName(), studentLogin.getPassword()) != null; if (found) { return "success"; } else { diff --git a/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..615ebd5f4a --- /dev/null +++ b/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.protobuf.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..516cc587a7 --- /dev/null +++ b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.springquartz.SpringQuartzApp; +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(classes = SpringQuartzApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-reactor/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-reactor/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7f906bdbcd --- /dev/null +++ b/spring-reactor/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2de3ed94d1 --- /dev/null +++ b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.AmqpClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AmqpClient.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..5dc6d1df75 --- /dev/null +++ b/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.AmqpServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AmqpServer.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1aec444aa0 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.BurlapClient; +import com.baeldung.client.HessianClient; + +@SpringBootTest(classes = {BurlapClient.class, HessianClient.class}) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f1aad1f601 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.Server; + +@SpringBootTest(classes = Server.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f1aad1f601 --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.Server; + +@SpringBootTest(classes = Server.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a94e639dc8 --- /dev/null +++ b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.JmsClient; + +@SpringBootTest(classes = JmsClient.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..5c9cc5f872 --- /dev/null +++ b/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.JmsServer; + +@SpringBootTest(classes = JmsServer.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3460792fc6 --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.RmiClient; + +@SpringBootTest(classes = RmiClient.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2063dd5e6e --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.RmiServer; + +@SpringBootTest(classes = RmiServer.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-angular/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-angular/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..228d0019bd --- /dev/null +++ b/spring-rest-angular/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.web.main.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml index 9f6eb0d703..a8c53dbc3a 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 @@ -58,36 +57,18 @@ httpcore ${httpcore.version} + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + - - 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-embedded-tomcat/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8b8ff1a322 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.embedded.configuration.UserConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { UserConfiguration.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-full/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-full/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..35939c992f --- /dev/null +++ b/spring-rest-full/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-query-language/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-query-language/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..35939c992f --- /dev/null +++ b/spring-rest-query-language/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..d99dacd331 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,24 @@ +package org.baeldung; + +import org.baeldung.config.MainApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.custom.CustomApplication; +import com.baeldung.produceimage.ImageApplication; +import com.baeldung.propertyeditor.PropertyEditorApplication; +import com.baeldung.responseheaders.ResponseHeadersApplication; +import com.baeldung.web.log.app.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { CustomApplication.class, ImageApplication.class, PropertyEditorApplication.class, + ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.Application.class, + MainApplication.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3a5a20cfeb --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.resttemplate.configuration.RestTemplateConfigurationApplication; +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(classes = RestTemplateConfigurationApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-acl/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-acl/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c7890d79ac --- /dev/null +++ b/spring-security-acl/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.acl.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-angular/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8c62ac5e91 --- /dev/null +++ b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootsecurityrest.basicauth.SpringBootSecurityApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootSecurityApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-cache-control/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c047fc6210 --- /dev/null +++ b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.cachecontrol.AppRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AppRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-core/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-core/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..5698afa417 --- /dev/null +++ b/spring-security-core/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.app.App; +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(classes = App.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/README.MD b/spring-security-mvc-boot/README.MD index eec61f087f..6bd9b9295c 100644 --- a/spring-security-mvc-boot/README.MD +++ b/spring-security-mvc-boot/README.MD @@ -10,3 +10,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Multiple Authentication Providers in Spring Security](http://www.baeldung.com/spring-security-multiple-auth-providers) - [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role) - [Spring Data with Spring Security](https://www.baeldung.com/spring-data-security) +- [Spring Security – Whitelist IP Range](https://www.baeldung.com/spring-security-whitelist-ip-range) diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java index b4ed8277d6..3a8032a734 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java @@ -8,7 +8,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration -@EnableWebSecurity +@EnableWebSecurity//(debug = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java index da5db5e825..940194c421 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java @@ -1,8 +1,15 @@ package org.baeldung.ip.web; +import java.util.List; + +import javax.servlet.Filter; import javax.servlet.http.HttpServletRequest; import org.baeldung.custom.persistence.model.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @@ -12,6 +19,20 @@ import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MainController { + @Autowired + @Qualifier("springSecurityFilterChain") + private Filter springSecurityFilterChain; + + @RequestMapping(method = RequestMethod.GET, value = "/filters") + @ResponseBody + public void getFilters() { + FilterChainProxy filterChainProxy = (FilterChainProxy) springSecurityFilterChain; + List list = filterChainProxy.getFilterChains(); + list.stream() + .flatMap(chain -> chain.getFilters().stream()) + .forEach(filter -> System.out.println(filter.getClass())); + } + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id, HttpServletRequest request) { diff --git a/spring-security-mvc-boot/src/main/resources/application.properties b/spring-security-mvc-boot/src/main/resources/application.properties index f015086a4f..25eac743d1 100644 --- a/spring-security-mvc-boot/src/main/resources/application.properties +++ b/spring-security-mvc-boot/src/main/resources/application.properties @@ -6,4 +6,7 @@ spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.database=H2 spring.jpa.show-sql=false -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect + + +#logging.level.org.springframework.security.web.FilterChainProxy=DEBUG \ No newline at end of file diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9e74e83a53 --- /dev/null +++ b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a4a85a8fa2 --- /dev/null +++ b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.ClientConfig; +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { ClientConfig.class, MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0b701e9acf --- /dev/null +++ b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +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(classes = SampleLDAPApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1d7f9ae497 --- /dev/null +++ b/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 2add895ecb..8b15e658e8 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -133,6 +133,14 @@ guava ${guava.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f1df880862 --- /dev/null +++ b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, PersistenceConfig.class, SecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index 7ffbd76aac..85c8475657 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -113,6 +113,14 @@ metrics-core ${codahale.metrics.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9e74e83a53 --- /dev/null +++ b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-socket/README.md b/spring-security-mvc-socket/README.md index 828d9a3448..6c2ad7b985 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: Build an 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..d1b8365077 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -148,10 +148,18 @@ jackson-annotations ${jackson.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + - + org.apache.tomcat.maven @@ -171,7 +179,6 @@ - spring-security-mvc-socket diff --git a/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..00202a98cb --- /dev/null +++ b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,24 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.springsecuredsockets.config.AppConfig; +import com.baeldung.springsecuredsockets.config.DataStoreConfig; +import com.baeldung.springsecuredsockets.config.SecurityConfig; +import com.baeldung.springsecuredsockets.config.SocketBrokerConfig; +import com.baeldung.springsecuredsockets.config.SocketSecurityConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppConfig.class, DataStoreConfig.class, SecurityConfig.class, + SocketBrokerConfig.class, SocketSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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-openid/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-openid/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..79a725dcae --- /dev/null +++ b/spring-security-openid/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.SpringOpenidApplication; +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(classes = SpringOpenidApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-react/pom.xml b/spring-security-react/pom.xml index 11ad679128..32817945be 100644 --- a/spring-security-react/pom.xml +++ b/spring-security-react/pom.xml @@ -82,6 +82,14 @@ ${jstl.version} runtime + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-security-react/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-react/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a921976fc3 --- /dev/null +++ b/spring-security-react/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6cf624c179 --- /dev/null +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/WebSecurityConfig.xml" }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e2e9f2af2b --- /dev/null +++ b/spring-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.ClientWebConfig; +import org.baeldung.spring.SecurityJavaConfig; +import org.baeldung.spring.WebConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/test/AuthServerIntegrationTest.java b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 88% rename from spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/test/AuthServerIntegrationTest.java rename to spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 9e2d6feca1..66ee232b10 100644 --- a/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/test/AuthServerIntegrationTest.java +++ b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.test; +package org.baeldung; import org.baeldung.config.AuthorizationServerApplication; import org.junit.Test; @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = AuthorizationServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class AuthServerIntegrationTest { +public class SpringContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { diff --git a/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/test/UiIntegrationTest.java b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 88% rename from spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/test/UiIntegrationTest.java rename to spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 6386eac0b8..2fb0210929 100644 --- a/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/test/UiIntegrationTest.java +++ b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.test; +package org.baeldung; import org.baeldung.config.UiApplication; import org.junit.Test; @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class UiIntegrationTest { +public class SpringContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { diff --git a/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/test/UiIntegrationTest.java b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 88% rename from spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/test/UiIntegrationTest.java rename to spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 6386eac0b8..2fb0210929 100644 --- a/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/test/UiIntegrationTest.java +++ b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.test; +package org.baeldung; import org.baeldung.config.UiApplication; import org.junit.Test; @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class UiIntegrationTest { +public class SpringContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7ec6125f84 --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7ec6125f84 --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b921f76a0d --- /dev/null +++ b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springsessionjdbc.SpringSessionJdbcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionJdbcApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a62e728826 --- /dev/null +++ b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.session.SessionWebApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SessionWebApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-sleuth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-sleuth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ef722ecba0 --- /dev/null +++ b/spring-sleuth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.session.SleuthWebApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SleuthWebApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java b/spring-social-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 87% rename from spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java rename to spring-social-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 43aaea18b1..29ed401118 100644 --- a/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java +++ b/spring-social-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.test; +package org.baeldung; import org.baeldung.config.Application; import org.junit.Test; @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class ApplicationIntegrationTest { +public class SpringContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { diff --git a/spring-spel/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-spel/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f394374a94 --- /dev/null +++ b/spring-spel/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:applicationContext.xml"}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-state-machine/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-state-machine/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..72292a5089 --- /dev/null +++ b/spring-state-machine/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,23 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.statemachine.config.ForkJoinStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.HierarchicalStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SimpleStateMachineConfiguration.class, SimpleEnumStateMachineConfiguration.class, + JunctionStateMachineConfiguration.class, HierarchicalStateMachineConfiguration.class, + ForkJoinStateMachineConfiguration.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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..4aff696828 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 @@ -24,6 +21,12 @@ spring-boot-starter-web ${spring.version} + + org.springframework.boot + spring-boot-starter-test + ${spring.version} + test + @@ -37,7 +40,6 @@ - 1.8 0.0.1-SNAPSHOT 1.5.10.RELEASE diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2143dc7f4d --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.petstore.app.PetStoreApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PetStoreApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-thymeleaf/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c7a0b4fc60 --- /dev/null +++ b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,22 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..825b89eb10 --- /dev/null +++ b/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.custom.config.MvcConfig; +import org.baeldung.custom.config.PersistenceDerbyJPAConfig; +import org.baeldung.custom.config.SecSecurityConfig; +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(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-vault/README.md b/spring-vault/README.md new file mode 100644 index 0000000000..8db065a3dd --- /dev/null +++ b/spring-vault/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring Vault](https://www.baeldung.com/spring-vault) diff --git a/spring-vault/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-vault/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a2d727ea79 --- /dev/null +++ b/spring-vault/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.springvault.SpringVaultApplication; +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(classes = SpringVaultApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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/spring-vertx/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-vertx/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b1f7b39f7e --- /dev/null +++ b/spring-vertx/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.vertxspring.VertxSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VertxSpringApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..35efff49c2 --- /dev/null +++ b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.amqp.SpringWebfluxAmqpApplication; +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(classes = SpringWebfluxAmqpApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..623966373b --- /dev/null +++ b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.ResourceServerApplication; +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(classes = ResourceServerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a3d49627e5 --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.UiApplication; +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(classes = UiApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java b/static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java similarity index 92% rename from static-analysis/src/test/java/com/baeldung/pmd/CntTest.java rename to static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java index ed72602f99..cdbf9f6f5e 100644 --- a/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java +++ b/static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java @@ -4,7 +4,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; -public class CntTest { +public class CntUnitTest { private Cnt service; diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 40c4e8cde9..836848282b 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -1,7 +1,6 @@ ### Relevant Articles: - [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) - [A Guide to JUnit 5](http://www.baeldung.com/junit-5) -- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) diff --git a/testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java b/testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java new file mode 100644 index 0000000000..d545daf0df --- /dev/null +++ b/testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java @@ -0,0 +1,15 @@ +package com.baeldung.testpropertysource; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class ClassUsingProperty { + + @Value("${baeldung.testpropertysource.one}") + private String propertyOne; + + public String retrievePropertyOne() { + return propertyOne; + } +} diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java new file mode 100644 index 0000000000..f983abdd54 --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.testpropertysource; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ClassUsingProperty.class) +@TestPropertySource +public class DefaultTestPropertySourceIntegrationTest { + + @Autowired + ClassUsingProperty classUsingProperty; + + @Test + public void givenDefaultTestPropertySource_whenVariableOneRetrieved_thenValueInDefaultFileReturned() { + String output = classUsingProperty.retrievePropertyOne(); + + assertThat(output).isEqualTo("default-value"); + } +} diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java new file mode 100644 index 0000000000..93d4cc58da --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.testpropertysource; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ClassUsingProperty.class) +@TestPropertySource(locations = "/other-location.properties") +public class LocationTestPropertySourceIntegrationTest { + + @Autowired + ClassUsingProperty classUsingProperty; + + @Test + public void givenDefaultTestPropertySource_whenVariableOneRetrieved_thenValueInDefaultFileReturned() { + String output = classUsingProperty.retrievePropertyOne(); + + assertThat(output).isEqualTo("other-location-value"); + } +} diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java new file mode 100644 index 0000000000..d98e2b9f98 --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.testpropertysource; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ClassUsingProperty.class) +@TestPropertySource(locations = "/other-location.properties", properties = "baeldung.testpropertysource.one=other-properties-value") +public class PropertiesTestPropertySourceIntegrationTest { + + @Autowired + ClassUsingProperty classUsingProperty; + + @Test + public void givenDefaultTestPropertySource_whenVariableOneRetrieved_thenValueInDefaultFileReturned() { + String output = classUsingProperty.retrievePropertyOne(); + + assertThat(output).isEqualTo("other-properties-value"); + } +} diff --git a/testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties b/testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties new file mode 100644 index 0000000000..a443a2b776 --- /dev/null +++ b/testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties @@ -0,0 +1 @@ +baeldung.testpropertysource.one=default-value \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/resources/other-location.properties b/testing-modules/spring-testing/src/test/resources/other-location.properties new file mode 100644 index 0000000000..6ef791ec75 --- /dev/null +++ b/testing-modules/spring-testing/src/test/resources/other-location.properties @@ -0,0 +1 @@ +baeldung.testpropertysource.one=other-location-value \ No newline at end of file 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 - - diff --git a/vaadin-spring/README.md b/vaadin-spring/README.md deleted file mode 100644 index 347c92d7b5..0000000000 --- a/vaadin-spring/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Sample Application with Spring Boot and Vaadin](https://www.baeldung.com/spring-boot-vaadin)