diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java index cb476b9d9e..a50028a9ae 100644 --- a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java +++ b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java @@ -28,14 +28,14 @@ public class Log { System.out.println("Had " + count + " commits overall on current branch"); logs = git.log() - .add(repository.resolve("remotes/origin/testbranch")) + .add(repository.resolve(git.getRepository().getFullBranch())) .call(); count = 0; for (RevCommit rev : logs) { System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); count++; } - System.out.println("Had " + count + " commits overall on test-branch"); + System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch()); logs = git.log() .all() diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java index ed7168b2c2..ad34890996 100644 --- a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java +++ b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java @@ -1,3 +1,5 @@ +package com.baeldung.jgit; + import com.baeldung.jgit.helper.Helper; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.ObjectReader; diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java new file mode 100644 index 0000000000..cd1f3e94d5 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java @@ -0,0 +1,54 @@ +package com.baeldung.algorithms.string; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class LongestSubstringNonRepeatingCharacters { + + public static String getUniqueCharacterSubstringBruteForce(String input) { + String output = ""; + for (int start = 0; start < input.length(); start++) { + Set visited = new HashSet<>(); + int end = start; + for (; end < input.length(); end++) { + char currChar = input.charAt(end); + if (visited.contains(currChar)) { + break; + } else { + visited.add(currChar); + } + } + if (output.length() < end - start + 1) { + output = input.substring(start, end); + } + } + return output; + } + + public static String getUniqueCharacterSubstring(String input) { + Map visited = new HashMap<>(); + String output = ""; + for (int start = 0, end = 0; end < input.length(); end++) { + char currChar = input.charAt(end); + if (visited.containsKey(currChar)) { + start = Math.max(visited.get(currChar) + 1, start); + } + if (output.length() < end - start + 1) { + output = input.substring(start, end + 1); + } + visited.put(currChar, end); + } + return output; + } + + public static void main(String[] args) { + if(args.length > 0) { + System.out.println(getUniqueCharacterSubstring(args[0])); + } else { + System.err.println("This program expects command-line input. Please try again!"); + } + } + +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java new file mode 100644 index 0000000000..9f1e6a2519 --- /dev/null +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.algorithms.string; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring; +import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce; + +public class LongestSubstringNonRepeatingCharactersUnitTest { + + @Test + void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() { + assertEquals("", getUniqueCharacterSubstringBruteForce("")); + assertEquals("A", getUniqueCharacterSubstringBruteForce("A")); + assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF")); + assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("ABCDEFF")); + assertEquals("NGISAWE", getUniqueCharacterSubstringBruteForce("CODINGISAWESOME")); + assertEquals("be coding", getUniqueCharacterSubstringBruteForce("always be coding")); + } + + @Test + void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() { + assertEquals("", getUniqueCharacterSubstring("")); + assertEquals("A", getUniqueCharacterSubstring("A")); + assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF")); + assertEquals("ABCDEF", getUniqueCharacterSubstring("ABCDEFF")); + assertEquals("NGISAWE", getUniqueCharacterSubstring("CODINGISAWESOME")); + assertEquals("be coding", getUniqueCharacterSubstring("always be coding")); + } + +} diff --git a/algorithms-miscellaneous-2/pom.xml b/algorithms-miscellaneous-2/pom.xml index 25472d4888..5461f4ebe1 100644 --- a/algorithms-miscellaneous-2/pom.xml +++ b/algorithms-miscellaneous-2/pom.xml @@ -33,6 +33,11 @@ jgrapht-core ${org.jgrapht.core.version} + + org.jgrapht + jgrapht-ext + ${org.jgrapht.ext.version} + pl.allegro.finance tradukisto @@ -83,6 +88,7 @@ 3.6.1 1.0.1 1.0.1 + 1.0.1 3.9.0 1.11 diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java new file mode 100644 index 0000000000..3b841d574a --- /dev/null +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertTrue; +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import javax.imageio.ImageIO; +import org.jgrapht.ext.JGraphXAdapter; +import org.jgrapht.graph.DefaultDirectedGraph; +import org.jgrapht.graph.DefaultEdge; +import org.junit.Before; +import org.junit.Test; +import com.mxgraph.layout.mxCircleLayout; +import com.mxgraph.layout.mxIGraphLayout; +import com.mxgraph.util.mxCellRenderer; + +public class GraphImageGenerationUnitTest { + static DefaultDirectedGraph g; + + @Before + public void createGraph() throws IOException { + File imgFile = new File("src/test/resources/graph.png"); + imgFile.createNewFile(); + g = new DefaultDirectedGraph(DefaultEdge.class); + String x1 = "x1"; + String x2 = "x2"; + String x3 = "x3"; + g.addVertex(x1); + g.addVertex(x2); + g.addVertex(x3); + g.addEdge(x1, x2); + g.addEdge(x2, x3); + g.addEdge(x3, x1); + } + + @Test + public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException { + JGraphXAdapter graphAdapter = new JGraphXAdapter(g); + mxIGraphLayout layout = new mxCircleLayout(graphAdapter); + layout.execute(graphAdapter.getDefaultParent()); + File imgFile = new File("src/test/resources/graph.png"); + BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null); + ImageIO.write(image, "PNG", imgFile); + assertTrue(imgFile.exists()); + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-2/src/test/resources/graph.png b/algorithms-miscellaneous-2/src/test/resources/graph.png new file mode 100644 index 0000000000..56995b8dd9 Binary files /dev/null and b/algorithms-miscellaneous-2/src/test/resources/graph.png differ diff --git a/core-java-net/README.md b/core-java-net/README.md deleted file mode 100644 index b7a142ea27..0000000000 --- a/core-java-net/README.md +++ /dev/null @@ -1,3 +0,0 @@ -========= - -## Core Java Net diff --git a/core-java-net/.gitignore b/core-java-networking/.gitignore similarity index 100% rename from core-java-net/.gitignore rename to core-java-networking/.gitignore diff --git a/core-java-networking/README.md b/core-java-networking/README.md new file mode 100644 index 0000000000..626ea794e6 --- /dev/null +++ b/core-java-networking/README.md @@ -0,0 +1,7 @@ +========= + +## Core Java Networking + +### Relevant Articles + +- [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server) diff --git a/core-java-net/pom.xml b/core-java-networking/pom.xml similarity index 80% rename from core-java-net/pom.xml rename to core-java-networking/pom.xml index 28d5766a9a..178295e1ec 100644 --- a/core-java-net/pom.xml +++ b/core-java-networking/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - core-java-net + core-java-networking 0.1.0-SNAPSHOT jar - core-java-net + core-java-networking com.baeldung @@ -14,6 +14,6 @@ - core-java-net + core-java-networking diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java diff --git a/core-java-net/src/test/resources/.gitignore b/core-java-networking/src/test/resources/.gitignore similarity index 100% rename from core-java-net/src/test/resources/.gitignore rename to core-java-networking/src/test/resources/.gitignore diff --git a/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java new file mode 100644 index 0000000000..20a13178cc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java @@ -0,0 +1,11 @@ +package com.baeldung.basicsyntax; + +public class SimpleAddition { + + public static void main(String[] args) { + int a = 10; + int b = 5; + double c = a + b; + System.out.println( a + " + " + b + " = " + c); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java b/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java new file mode 100644 index 0000000000..b669947d9c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java @@ -0,0 +1,171 @@ +package com.baeldung.java.properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Enumeration; +import java.util.Properties; + +import org.junit.Test; + +public class PropertiesUnitTest { + + @Test + public void givenPropertyValue_whenPropertiesFileLoaded_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + String catalogConfigPath = rootPath + "catalog"; + + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + Properties catalogProps = new Properties(); + catalogProps.load(new FileInputStream(catalogConfigPath)); + + String appVersion = appProps.getProperty("version"); + assertEquals("1.0", appVersion); + + assertEquals("files", catalogProps.getProperty("c1")); + } + + @Test + public void givenPropertyValue_whenXMLPropertiesFileLoaded_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String iconConfigPath = rootPath + "icons.xml"; + Properties iconProps = new Properties(); + iconProps.loadFromXML(new FileInputStream(iconConfigPath)); + + assertEquals("icon1.jpg", iconProps.getProperty("fileIcon")); + } + + @Test + public void givenAbsentProperty_whenPropertiesFileLoaded_thenReturnsDefault() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + String appVersion = appProps.getProperty("version"); + String appName = appProps.getProperty("name", "defaultName"); + String appGroup = appProps.getProperty("group", "baeldung"); + String appDownloadAddr = appProps.getProperty("downloadAddr"); + + assertEquals("1.0", appVersion); + assertEquals("TestApp", appName); + assertEquals("baeldung", appGroup); + assertNull(appDownloadAddr); + } + + @Test(expected = Exception.class) + public void givenImproperObjectCasting_whenPropertiesFileLoaded_thenThrowsException() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + float appVerFloat = (float) appProps.get("version"); + } + + @Test + public void givenPropertyValue_whenPropertiesSet_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + appProps.setProperty("name", "NewAppName"); + appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); + + String newAppName = appProps.getProperty("name"); + assertEquals("NewAppName", newAppName); + + String newAppDownloadAddr = appProps.getProperty("downloadAddr"); + assertEquals("www.baeldung.com/downloads", newAppDownloadAddr); + } + + @Test + public void givenPropertyValueNull_whenPropertiesRemoved_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + String versionBeforeRemoval = appProps.getProperty("version"); + assertEquals("1.0", versionBeforeRemoval); + + appProps.remove("version"); + String versionAfterRemoval = appProps.getProperty("version"); + assertNull(versionAfterRemoval); + } + + @Test + public void whenPropertiesStoredInFile_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + String newAppConfigPropertiesFile = rootPath + "newApp.properties"; + appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file"); + + String newAppConfigXmlFile = rootPath + "newApp.xml"; + appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file"); + } + + @Test + public void givenPropertyValueAbsent_LoadsValuesFromDefaultProperties() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + + String defaultConfigPath = rootPath + "default.properties"; + Properties defaultProps = new Properties(); + defaultProps.load(new FileInputStream(defaultConfigPath)); + + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(defaultProps); + appProps.load(new FileInputStream(appConfigPath)); + + String appName = appProps.getProperty("name"); + String appVersion = appProps.getProperty("version"); + String defaultSite = appProps.getProperty("site"); + + assertEquals("1.0", appVersion); + assertEquals("TestApp", appName); + assertEquals("www.google.com", defaultSite); + } + + @Test + public void givenPropertiesSize_whenPropertyFileLoaded_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appPropsPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appPropsPath)); + + appProps.list(System.out); // list all key-value pairs + + Enumeration valueEnumeration = appProps.elements(); + while (valueEnumeration.hasMoreElements()) { + System.out.println(valueEnumeration.nextElement()); + } + + Enumeration keyEnumeration = appProps.keys(); + while (keyEnumeration.hasMoreElements()) { + System.out.println(keyEnumeration.nextElement()); + } + + int size = appProps.size(); + assertEquals(3, size); + } +} diff --git a/core-java/src/test/resources/app.properties b/core-java/src/test/resources/app.properties new file mode 100644 index 0000000000..ff6174ec2a --- /dev/null +++ b/core-java/src/test/resources/app.properties @@ -0,0 +1,3 @@ +version=1.0 +name=TestApp +date=2016-11-12 \ No newline at end of file diff --git a/core-java/src/test/resources/catalog b/core-java/src/test/resources/catalog new file mode 100644 index 0000000000..488513d0ce --- /dev/null +++ b/core-java/src/test/resources/catalog @@ -0,0 +1,3 @@ +c1=files +c2=images +c3=videos \ No newline at end of file diff --git a/core-java/src/test/resources/default.properties b/core-java/src/test/resources/default.properties new file mode 100644 index 0000000000..df1bab371c --- /dev/null +++ b/core-java/src/test/resources/default.properties @@ -0,0 +1,4 @@ +site=www.google.com +name=DefaultAppName +topic=Properties +category=core-java \ No newline at end of file diff --git a/core-java/src/test/resources/icons.xml b/core-java/src/test/resources/icons.xml new file mode 100644 index 0000000000..0db7b2699a --- /dev/null +++ b/core-java/src/test/resources/icons.xml @@ -0,0 +1,8 @@ + + + + xml example + icon1.jpg + icon2.jpg + icon3.jpg + \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt b/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt new file mode 100644 index 0000000000..239c425c03 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt @@ -0,0 +1,28 @@ +package com.baeldung.functions + +import kotlin.random.Random + +/** + * An extension function on all collections to apply a function to all collection + * elements. + */ +fun Collection.each(block: (T) -> Unit) { + for (e in this) block(e) +} + +/** + * In order to see the the JVM bytecode: + * 1. Compile the Kotlin file using `kotlinc Inline.kt` + * 2. Take a peek at the bytecode using the `javap -c InlineKt` + */ +fun main() { + val numbers = listOf(1, 2, 3, 4, 5) + val random = random() + + numbers.each { println(random * it) } // capturing the random variable +} + +/** + * Generates a random number. + */ +private fun random(): Int = Random.nextInt() \ No newline at end of file diff --git a/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events b/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events deleted file mode 100644 index d3ce8b9cea..0000000000 Binary files a/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events and /dev/null differ diff --git a/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events b/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events deleted file mode 100644 index 2ab0ec469f..0000000000 Binary files a/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events and /dev/null differ diff --git a/events/README.md b/events/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/events/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events b/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events deleted file mode 100644 index d805fc253e..0000000000 Binary files a/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events and /dev/null differ diff --git a/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events b/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events deleted file mode 100644 index 3d67b74ced..0000000000 Binary files a/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events and /dev/null differ diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java deleted file mode 100644 index 7813e89a48..0000000000 --- a/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.hibernate.entities; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) -@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), - @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) -@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/resources/init_database.sql b/hibernate5/src/main/resources/init_database.sql deleted file mode 100644 index 154a5a0bc0..0000000000 --- a/hibernate5/src/main/resources/init_database.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -@CODE -void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String designation) throws SQLException { - CallableStatement updateStatement = conn.prepareCall("update deptemployee set designation = '" + designation + "' where employeeNumber = '" + employeeNumber + "'"); - updateStatement.execute(); -} -$$; \ No newline at end of file diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java deleted file mode 100644 index ef6ec89bc4..0000000000 --- a/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.baeldung.hibernate; - -import java.io.IOException; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.query.NativeQuery; -import org.hibernate.query.Query; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.baeldung.hibernate.entities.Department; -import com.baeldung.hibernate.entities.DeptEmployee; - -public class NamedQueryIntegrationTest { - private static Session session; - - private Transaction transaction; - - private Long purchaseDeptId; - - @BeforeClass - public static void setUpClass() throws IOException { - session = HibernateUtil.getSessionFactory("hibernate-namedquery.properties").openSession(); - } - - @Before - public void setUp() throws IOException { - transaction = session.beginTransaction(); - session.createNativeQuery("delete from deptemployee").executeUpdate(); - session.createNativeQuery("delete from department").executeUpdate(); - Department salesDepartment = new Department("Sales"); - Department purchaseDepartment = new Department("Purchase"); - DeptEmployee employee1 = new DeptEmployee("John Wayne", "001", salesDepartment); - DeptEmployee employee2 = new DeptEmployee("Sarah Vinton", "002", salesDepartment); - DeptEmployee employee3 = new DeptEmployee("Lisa Carter", "003", salesDepartment); - session.persist(salesDepartment); - session.persist(purchaseDepartment); - purchaseDeptId = purchaseDepartment.getId(); - session.persist(employee1); - session.persist(employee2); - session.persist(employee3); - transaction.commit(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - if(transaction.isActive()) { - transaction.rollback(); - } - } - - @Test - public void whenNamedQueryIsCalledUsingCreateNamedQuery_ThenOk() { - Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeNumber", DeptEmployee.class); - query.setParameter("employeeNo", "001"); - DeptEmployee result = query.getSingleResult(); - Assert.assertNotNull(result); - Assert.assertEquals("John Wayne", result.getName()); - } - - @Test - public void whenNamedNativeQueryIsCalledUsingCreateNamedQuery_ThenOk() { - Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeName", DeptEmployee.class); - query.setParameter("name", "John Wayne"); - DeptEmployee result = query.getSingleResult(); - Assert.assertNotNull(result); - Assert.assertEquals("001", result.getEmployeeNumber()); - } - - @Test - public void whenNamedNativeQueryIsCalledUsingGetNamedNativeQuery_ThenOk() { - @SuppressWarnings("rawtypes") - NativeQuery query = session.getNamedNativeQuery("DeptEmployee_FindByEmployeeName"); - query.setParameter("name", "John Wayne"); - DeptEmployee result = (DeptEmployee) query.getSingleResult(); - Assert.assertNotNull(result); - Assert.assertEquals("001", result.getEmployeeNumber()); - } - - @Test - public void whenUpdateQueryIsCalledWithCreateNamedQuery_ThenOk() { - Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDepartment"); - spQuery.setParameter("employeeNo", "001"); - Department newDepartment = session.find(Department.class, purchaseDeptId); - spQuery.setParameter("newDepartment", newDepartment); - spQuery.executeUpdate(); - transaction.commit(); - } - - @Test - public void whenNamedStoredProcedureIsCalledWithCreateNamedQuery_ThenOk() { - Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDesignation"); - spQuery.setParameter("employeeNumber", "002"); - spQuery.setParameter("newDesignation", "Supervisor"); - spQuery.executeUpdate(); - transaction.commit(); - } -} diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java new file mode 100644 index 0000000000..e8aa12d4bd --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java @@ -0,0 +1,228 @@ +package com.baeldung.java.map.compare; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.hamcrest.collection.IsMapContaining.hasKey; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +import com.google.common.base.Equivalence; +import com.google.common.collect.MapDifference; +import com.google.common.collect.MapDifference.ValueDifference; +import com.google.common.collect.Maps; + +public class HashMapComparisonUnitTest { + + Map asiaCapital1; + Map asiaCapital2; + Map asiaCapital3; + + Map asiaCity1; + Map asiaCity2; + Map asiaCity3; + + @Before + public void setup(){ + asiaCapital1 = new HashMap(); + asiaCapital1.put("Japan", "Tokyo"); + asiaCapital1.put("South Korea", "Seoul"); + + asiaCapital2 = new HashMap(); + asiaCapital2.put("South Korea", "Seoul"); + asiaCapital2.put("Japan", "Tokyo"); + + asiaCapital3 = new HashMap(); + asiaCapital3.put("Japan", "Tokyo"); + asiaCapital3.put("China", "Beijing"); + + asiaCity1 = new HashMap(); + asiaCity1.put("Japan", new String[] { "Tokyo", "Osaka" }); + asiaCity1.put("South Korea", new String[] { "Seoul", "Busan" }); + + asiaCity2 = new HashMap(); + asiaCity2.put("South Korea", new String[] { "Seoul", "Busan" }); + asiaCity2.put("Japan", new String[] { "Tokyo", "Osaka" }); + + asiaCity3 = new HashMap(); + asiaCity3.put("Japan", new String[] { "Tokyo", "Osaka" }); + asiaCity3.put("China", new String[] { "Beijing", "Hong Kong" }); + } + + @Test + public void whenCompareTwoHashMapsUsingEquals_thenSuccess() { + assertTrue(asiaCapital1.equals(asiaCapital2)); + assertFalse(asiaCapital1.equals(asiaCapital3)); + } + + @Test + public void whenCompareTwoHashMapsWithArrayValuesUsingEquals_thenFail() { + assertFalse(asiaCity1.equals(asiaCity2)); + } + + @Test + public void whenCompareTwoHashMapsUsingStreamAPI_thenSuccess() { + assertTrue(areEqual(asiaCapital1, asiaCapital2)); + assertFalse(areEqual(asiaCapital1, asiaCapital3)); + } + + @Test + public void whenCompareTwoHashMapsWithArrayValuesUsingStreamAPI_thenSuccess() { + assertTrue(areEqualWithArrayValue(asiaCity1, asiaCity2)); + assertFalse(areEqualWithArrayValue(asiaCity1, asiaCity3)); + } + + @Test + public void whenCompareTwoHashMapKeys_thenSuccess() { + assertTrue(asiaCapital1.keySet().equals(asiaCapital2.keySet())); + assertFalse(asiaCapital1.keySet().equals(asiaCapital3.keySet())); + } + + @Test + public void whenCompareTwoHashMapKeyValuesUsingStreamAPI_thenSuccess() { + Map asiaCapital3 = new HashMap(); + asiaCapital3.put("Japan", "Tokyo"); + asiaCapital3.put("South Korea", "Seoul"); + asiaCapital3.put("China", "Beijing"); + + Map asiaCapital4 = new HashMap(); + asiaCapital4.put("South Korea", "Seoul"); + asiaCapital4.put("Japan", "Osaka"); + asiaCapital4.put("China", "Beijing"); + + Map result = areEqualKeyValues(asiaCapital3, asiaCapital4); + + assertEquals(3, result.size()); + assertThat(result, hasEntry("Japan", false)); + assertThat(result, hasEntry("South Korea", true)); + assertThat(result, hasEntry("China", true)); + } + + @Test + public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map> entriesDiffering = diff.entriesDiffering(); + + assertFalse(diff.areEqual()); + assertEquals(1, entriesDiffering.size()); + assertThat(entriesDiffering, hasKey("India")); + assertEquals("New Delhi", entriesDiffering.get("India").leftValue()); + assertEquals("Delhi", entriesDiffering.get("India").rightValue()); + } + + @Test + public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map entriesOnlyOnRight = diff.entriesOnlyOnRight(); + Map entriesOnlyOnLeft = diff.entriesOnlyOnLeft(); + + assertEquals(1, entriesOnlyOnRight.size()); + assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing")); + assertEquals(1, entriesOnlyOnLeft.size()); + assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul")); + } + + @Test + public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map entriesInCommon = diff.entriesInCommon(); + + assertEquals(1, entriesInCommon.size()); + assertThat(entriesInCommon, hasEntry("Japan", "Tokyo")); + } + + @Test + public void givenSimilarMapsWithArrayValue_whenCompareUsingGuava_thenFail() { + MapDifference diff = Maps.difference(asiaCity1, asiaCity2); + assertFalse(diff.areEqual()); + } + + @Test + public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() { + Equivalence eq = new Equivalence() { + @Override + protected boolean doEquivalent(String[] a, String[] b) { + return Arrays.equals(a, b); + } + + @Override + protected int doHash(String[] value) { + return value.hashCode(); + } + }; + + MapDifference diff = Maps.difference(asiaCity1, asiaCity2, eq); + assertTrue(diff.areEqual()); + + diff = Maps.difference(asiaCity1, asiaCity3, eq); + assertFalse(diff.areEqual()); + } + + // =========================================================================== + + private boolean areEqual(Map first, Map second) { + if (first.size() != second.size()) { + return false; + } + + return first.entrySet() + .stream() + .allMatch(e -> e.getValue() + .equals(second.get(e.getKey()))); + } + + private boolean areEqualWithArrayValue(Map first, Map second) { + if (first.size() != second.size()) { + return false; + } + + return first.entrySet() + .stream() + .allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey()))); + } + + private Map areEqualKeyValues(Map first, Map second) { + return first.entrySet() + .stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey())))); + } + +} diff --git a/java-streams/pom.xml b/java-streams/pom.xml index e4670c268d..2b52ebb4b3 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-streams 0.1.0-SNAPSHOT @@ -74,6 +74,11 @@ aspectjweaver ${asspectj.version} + + pl.touk + throwing-function + ${throwing-function.version} + @@ -108,8 +113,9 @@ 1.15 0.6.5 2.10 + 1.3 - 3.6.1 + 3.11.1 1.8.9 diff --git a/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java new file mode 100644 index 0000000000..49da6e7175 --- /dev/null +++ b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java @@ -0,0 +1,55 @@ +package com.baeldung.stream.filter; + +import javax.net.ssl.HttpsURLConnection; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +public class Customer { + private String name; + private int points; + private String profilePhotoUrl; + + public Customer(String name, int points) { + this(name, points, ""); + } + + public Customer(String name, int points, String profilePhotoUrl) { + this.name = name; + this.points = points; + this.profilePhotoUrl = profilePhotoUrl; + } + + public String getName() { + return name; + } + + public int getPoints() { + return points; + } + + public boolean hasOver(int points) { + return this.points > points; + } + + public boolean hasOverThousandPoints() { + return this.points > 100; + } + + public boolean hasValidProfilePhoto() throws IOException { + URL url = new URL(this.profilePhotoUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + return connection.getResponseCode() == HttpURLConnection.HTTP_OK; + } + + public boolean hasValidProfilePhotoWithoutCheckedException() { + try { + URL url = new URL(this.profilePhotoUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + return connection.getResponseCode() == HttpURLConnection.HTTP_OK; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java new file mode 100644 index 0000000000..cf82802940 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java @@ -0,0 +1,159 @@ +package com.baeldung.stream.filter; + +import org.junit.jupiter.api.Test; +import pl.touk.throwing.ThrowingPredicate; +import pl.touk.throwing.exception.WrappedException; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +public class StreamFilterUnitTest { + + @Test + public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); + + List customersWithMoreThan100Points = customers + .stream() + .filter(c -> c.getPoints() > 100) + .collect(Collectors.toList()); + + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah, charles); + } + + @Test + public void givenListOfCustomers_whenFilterByPointsAndName_thenGetOne() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); + + List charlesWithMoreThan100Points = customers + .stream() + .filter(c -> c.getPoints() > 100 && c + .getName() + .startsWith("Charles")) + .collect(Collectors.toList()); + + assertThat(charlesWithMoreThan100Points).hasSize(1); + assertThat(charlesWithMoreThan100Points).contains(charles); + } + + @Test + public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); + + List customersWithMoreThan100Points = customers + .stream() + .filter(Customer::hasOverThousandPoints) + .collect(Collectors.toList()); + + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah, charles); + } + + @Test + public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() { + Optional john = Optional.of(new Customer("John P.", 15)); + Optional sarah = Optional.of(new Customer("Sarah M.", 200)); + Optional mary = Optional.of(new Customer("Mary T.", 300)); + List> customers = Arrays.asList(john, sarah, Optional.empty(), mary, Optional.empty()); + + List customersWithMoreThan100Points = customers + .stream() + .flatMap(c -> c + .map(Stream::of) + .orElseGet(Stream::empty)) + .filter(Customer::hasOverThousandPoints) + .collect(Collectors.toList()); + + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah.get(), mary.get()); + } + + @Test + public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() { + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); + + assertThatThrownBy(() -> customers + .stream() + .filter(Customer::hasValidProfilePhotoWithoutCheckedException) + .count()).isInstanceOf(RuntimeException.class); + } + + @Test + public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() { + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); + + assertThatThrownBy(() -> customers + .stream() + .filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto))) + .collect(Collectors.toList())).isInstanceOf(WrappedException.class); + } + + @Test + public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() { + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); + + List customersWithValidProfilePhoto = customers + .stream() + .filter(c -> { + try { + return c.hasValidProfilePhoto(); + } catch (IOException e) { + //handle exception + } + return false; + }) + .collect(Collectors.toList()); + + assertThat(customersWithValidProfilePhoto).hasSize(2); + assertThat(customersWithValidProfilePhoto).contains(john, mary); + } + + @Test + public void givenListOfCustomers_whenFilterWithTryCatchAndRuntime_thenThrowException() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + assertThatThrownBy(() -> customers + .stream() + .filter(c -> { + try { + return c.hasValidProfilePhoto(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }) + .collect(Collectors.toList())).isInstanceOf(RuntimeException.class); + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java b/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java new file mode 100644 index 0000000000..688bf43b3c --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java @@ -0,0 +1,90 @@ +package com.baeldung.string; + +import java.util.HashSet; +import java.util.Set; + +public class SubstringPalindrome { + + public Set findAllPalindromesUsingCenter(String input) { + final Set palindromes = new HashSet<>(); + if (input == null || input.isEmpty()) { + return palindromes; + } + if (input.length() == 1) { + palindromes.add(input); + return palindromes; + } + for (int i = 0; i < input.length(); i++) { + palindromes.addAll(findPalindromes(input, i, i + 1)); + palindromes.addAll(findPalindromes(input, i, i)); + } + return palindromes; + } + + private Set findPalindromes(String input, int low, int high) { + Set result = new HashSet<>(); + while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) { + result.add(input.substring(low, high + 1)); + low--; + high++; + } + return result; + } + + public Set findAllPalindromesUsingBruteForceApproach(String input) { + Set palindromes = new HashSet<>(); + if (input == null || input.isEmpty()) { + return palindromes; + } + if (input.length() == 1) { + palindromes.add(input); + return palindromes; + } + for (int i = 0; i < input.length(); i++) { + for (int j = i + 1; j <= input.length(); j++) + if (isPalindrome(input.substring(i, j))) { + palindromes.add(input.substring(i, j)); + } + } + return palindromes; + } + + private boolean isPalindrome(String input) { + StringBuilder plain = new StringBuilder(input); + StringBuilder reverse = plain.reverse(); + return (reverse.toString()).equals(input); + } + + public Set findAllPalindromesUsingManachersAlgorithm(String input) { + Set palindromes = new HashSet<>(); + String formattedInput = "@" + input + "#"; + char inputCharArr[] = formattedInput.toCharArray(); + int max; + int radius[][] = new int[2][input.length() + 1]; + for (int j = 0; j <= 1; j++) { + radius[j][0] = max = 0; + int i = 1; + while (i <= input.length()) { + palindromes.add(Character.toString(inputCharArr[i])); + while (inputCharArr[i - max - 1] == inputCharArr[i + j + max]) + max++; + radius[j][i] = max; + int k = 1; + while ((radius[j][i - k] != max - k) && (k < max)) { + radius[j][i + k] = Math.min(radius[j][i - k], max - k); + k++; + } + max = Math.max(max - k, 0); + i += k; + } + } + for (int i = 1; i <= input.length(); i++) { + for (int j = 0; j <= 1; j++) { + for (max = radius[j][i]; max > 0; max--) { + palindromes.add(input.substring(i - max - 1, max + j + i - 1)); + } + } + } + return palindromes; + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java b/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java new file mode 100644 index 0000000000..b18a8d4a5f --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.string; + +import static org.junit.Assert.assertEquals; +import java.util.HashSet; +import java.util.Set; +import org.junit.Test; + +public class SubstringPalindromeUnitTest { + + private static final String INPUT_BUBBLE = "bubble"; + private static final String INPUT_CIVIC = "civic"; + private static final String INPUT_INDEED = "indeed"; + private static final String INPUT_ABABAC = "ababac"; + + Set EXPECTED_PALINDROME_BUBBLE = new HashSet() { + { + add("b"); + add("u"); + add("l"); + add("e"); + add("bb"); + add("bub"); + } + }; + + Set EXPECTED_PALINDROME_CIVIC = new HashSet() { + { + add("civic"); + add("ivi"); + add("i"); + add("c"); + add("v"); + } + }; + + Set EXPECTED_PALINDROME_INDEED = new HashSet() { + { + add("i"); + add("n"); + add("d"); + add("e"); + add("ee"); + add("deed"); + } + }; + + Set EXPECTED_PALINDROME_ABABAC = new HashSet() { + { + add("a"); + add("b"); + add("c"); + add("aba"); + add("bab"); + add("ababa"); + } + }; + + private SubstringPalindrome palindrome = new SubstringPalindrome(); + + @Test + public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() { + assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE)); + assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED)); + assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC)); + assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC)); + } + + @Test + public void whenUsingCenterApproach_thenFindsAllPalindromes() { + assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE)); + assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED)); + assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC)); + assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC)); + } + + @Test + public void whenUsingBruteForceApproach_thenFindsAllPalindromes() { + assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE)); + assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED)); + assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC)); + assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC)); + } +} diff --git a/json/pom.xml b/json/pom.xml index db98ec437e..fce2d26db5 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -33,6 +33,16 @@ org.json json 20171018 + + + com.google.code.gson + gson + 2.8.5 + + + com.fasterxml.jackson.core + jackson-databind + 2.9.7 javax.json.bind diff --git a/json/src/main/java/com/baeldung/escape/JsonEscape.java b/json/src/main/java/com/baeldung/escape/JsonEscape.java new file mode 100644 index 0000000000..1e5f0d87cb --- /dev/null +++ b/json/src/main/java/com/baeldung/escape/JsonEscape.java @@ -0,0 +1,41 @@ +package com.baeldung.escape; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonObject; +import org.json.JSONObject; + +class JsonEscape { + + String escapeJson(String input) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("message", input); + return jsonObject.toString(); + } + + String escapeGson(String input) { + JsonObject gsonObject = new JsonObject(); + gsonObject.addProperty("message", input); + return gsonObject.toString(); + } + + String escapeJackson(String input) throws JsonProcessingException { + return new ObjectMapper().writeValueAsString(new Payload(input)); + } + + static class Payload { + String message; + + Payload(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + } +} diff --git a/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java b/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java new file mode 100644 index 0000000000..e959fa227b --- /dev/null +++ b/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.escape; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class JsonEscapeUnitTest { + + private JsonEscape testedInstance; + private static final String EXPECTED = "{\"message\":\"Hello \\\"World\\\"\"}"; + + @BeforeEach + void setUp() { + testedInstance = new JsonEscape(); + } + + @Test + void escapeJson() { + String actual = testedInstance.escapeJson("Hello \"World\""); + assertEquals(EXPECTED, actual); + } + + @Test + void escapeGson() { + String actual = testedInstance.escapeGson("Hello \"World\""); + assertEquals(EXPECTED, actual); + } + + @Test + void escapeJackson() throws JsonProcessingException { + String actual = testedInstance.escapeJackson("Hello \"World\""); + assertEquals(EXPECTED, actual); + } +} \ No newline at end of file diff --git a/libraries/pom.xml b/libraries/pom.xml index fb1f1cd1b6..cb85a57304 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -717,6 +717,12 @@ ${suanshu.version} + + org.derive4j + derive4j + ${derive4j.version} + true + @@ -952,6 +958,7 @@ 4.5.1 3.3.0 3.0.2 + 1.1.0 diff --git a/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java b/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java new file mode 100644 index 0000000000..d22bb89fe2 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java @@ -0,0 +1,10 @@ +package com.baeldung.derive4j.adt; + +import org.derive4j.Data; + +import java.util.function.Function; + +@Data +interface Either{ + X match(Function left, Function right); +} diff --git a/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java b/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java new file mode 100644 index 0000000000..9f53f3d25b --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java @@ -0,0 +1,21 @@ +package com.baeldung.derive4j.lazy; + +import org.derive4j.Data; +import org.derive4j.Derive; +import org.derive4j.Make; + +@Data(value = @Derive( + inClass = "{ClassName}Impl", + make = {Make.lazyConstructor, Make.constructors} +)) +public interface LazyRequest { + interface Cases{ + R GET(String path); + R POST(String path, String body); + R PUT(String path, String body); + R DELETE(String path); + } + + R match(LazyRequest.Cases method); +} + diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java new file mode 100644 index 0000000000..04d630f1ef --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java @@ -0,0 +1,15 @@ +package com.baeldung.derive4j.pattern; + +import org.derive4j.Data; + +@Data +interface HTTPRequest { + interface Cases{ + R GET(String path); + R POST(String path, String body); + R PUT(String path, String body); + R DELETE(String path); + } + + R match(Cases method); +} diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java new file mode 100644 index 0000000000..593f94a8b7 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java @@ -0,0 +1,19 @@ +package com.baeldung.derive4j.pattern; + +public class HTTPResponse { + private int statusCode; + private String responseBody; + + public int getStatusCode() { + return statusCode; + } + + public String getResponseBody() { + return responseBody; + } + + public HTTPResponse(int statusCode, String responseBody) { + this.statusCode = statusCode; + this.responseBody = responseBody; + } +} diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java new file mode 100644 index 0000000000..53f4af628c --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java @@ -0,0 +1,17 @@ +package com.baeldung.derive4j.pattern; + + +public class HTTPServer { + public static String GET_RESPONSE_BODY = "Success!"; + public static String PUT_RESPONSE_BODY = "Resource Created!"; + public static String POST_RESPONSE_BODY = "Resource Updated!"; + public static String DELETE_RESPONSE_BODY = "Resource Deleted!"; + + public HTTPResponse acceptRequest(HTTPRequest request) { + return HTTPRequests.caseOf(request) + .GET((path) -> new HTTPResponse(200, GET_RESPONSE_BODY)) + .POST((path,body) -> new HTTPResponse(201, POST_RESPONSE_BODY)) + .PUT((path,body) -> new HTTPResponse(200, PUT_RESPONSE_BODY)) + .DELETE(path -> new HTTPResponse(200, DELETE_RESPONSE_BODY)); + } +} diff --git a/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java new file mode 100644 index 0000000000..511e24961f --- /dev/null +++ b/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.derive4j.adt; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Optional; +import java.util.function.Function; +@RunWith(MockitoJUnitRunner.class) +public class EitherUnitTest { + @Test + public void testEitherIsCreatedFromRight() { + Either either = Eithers.right("Okay"); + Optional leftOptional = Eithers.getLeft(either); + Optional rightOptional = Eithers.getRight(either); + Assertions.assertThat(leftOptional).isEmpty(); + Assertions.assertThat(rightOptional).hasValue("Okay"); + + } + + @Test + public void testEitherIsMatchedWithRight() { + Either either = Eithers.right("Okay"); + Function leftFunction = Mockito.mock(Function.class); + Function rightFunction = Mockito.mock(Function.class); + either.match(leftFunction, rightFunction); + Mockito.verify(rightFunction, Mockito.times(1)).apply("Okay"); + Mockito.verify(leftFunction, Mockito.times(0)).apply(Mockito.any(Exception.class)); + } + +} diff --git a/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java new file mode 100644 index 0000000000..3830bc52d0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.derive4j.lazy; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.function.Supplier; + +public class LazyRequestUnitTest { + + @Test + public void givenLazyContstructedRequest_whenRequestIsReferenced_thenRequestIsLazilyContructed() { + LazyRequestSupplier mockSupplier = Mockito.spy(new LazyRequestSupplier()); + + LazyRequest request = LazyRequestImpl.lazy(() -> mockSupplier.get()); + Mockito.verify(mockSupplier, Mockito.times(0)).get(); + Assert.assertEquals(LazyRequestImpl.getPath(request), "http://test.com/get"); + Mockito.verify(mockSupplier, Mockito.times(1)).get(); + + } + + class LazyRequestSupplier implements Supplier { + @Override + public LazyRequest get() { + return LazyRequestImpl.GET("http://test.com/get"); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java new file mode 100644 index 0000000000..0fc257742a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.derive4j.pattern; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class HTTPRequestUnitTest { + public static HTTPServer server; + + @BeforeClass + public static void setUp() { + server = new HTTPServer(); + } + + @Test + public void givenHttpGETRequest_whenRequestReachesServer_thenProperResponseIsReturned() { + HTTPRequest postRequest = HTTPRequests.POST("http://test.com/post", "Resource"); + HTTPResponse response = server.acceptRequest(postRequest); + Assert.assertEquals(201, response.getStatusCode()); + Assert.assertEquals(HTTPServer.POST_RESPONSE_BODY, response.getResponseBody()); + } +} diff --git a/micronaut/pom.xml b/micronaut/pom.xml index 7b722306b6..aa69c77f73 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -7,15 +7,10 @@ com.baeldung.micronaut.helloworld.server.ServerApplication - 1.0.0.M2 - 9 + 1.0.0.RC2 + 1.8 - - - jcenter.bintray.com - http://jcenter.bintray.com - - + diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java index d4051cef52..96bc51f235 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java @@ -1,7 +1,7 @@ package com.baeldung.micronaut.helloworld.client; import io.micronaut.http.HttpRequest; -import io.micronaut.http.client.Client; +import io.micronaut.http.client.annotation.Client; import io.micronaut.http.client.RxHttpClient; import io.reactivex.Single; diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java index 8a691d5b06..d29a97fd50 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java @@ -1,10 +1,7 @@ package com.baeldung.micronaut.helloworld.client; import io.micronaut.http.annotation.Get; -import io.micronaut.http.client.Client; -import io.micronaut.http.client.RxHttpClient; - -import javax.inject.Inject; +import io.micronaut.http.client.annotation.Client; @Client("/greet") public interface GreetingClient { diff --git a/parent-boot-2.0-temp/README.md b/parent-boot-2.0-temp/README.md new file mode 100644 index 0000000000..8134c8eafe --- /dev/null +++ b/parent-boot-2.0-temp/README.md @@ -0,0 +1,2 @@ +This pom will be ued only temporary until we migrate parent-boot-2 to 2.1.0 for ticket BAEL-10354 + diff --git a/parent-boot-2.0-temp/pom.xml b/parent-boot-2.0-temp/pom.xml new file mode 100644 index 0000000000..9284e4af13 --- /dev/null +++ b/parent-boot-2.0-temp/pom.xml @@ -0,0 +1,85 @@ + + 4.0.0 + parent-boot-2.0-temp + 0.0.1-SNAPSHOT + pom + Temporary Parent for all Spring Boot 2.0.x modules + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + io.rest-assured + rest-assured + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${start-class} + + + + + + + + + + thin-jar + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.springframework.boot.experimental + spring-boot-thin-layout + ${thin.version} + + + + + + + + + + 3.1.0 + + 1.0.11.RELEASE + 2.0.5.RELEASE + + + + diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 89afd79bf4..280d226e95 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -78,7 +78,7 @@ 3.1.0 1.0.11.RELEASE - 2.0.5.RELEASE + 2.1.1.RELEASE diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 363e2153b6..7e9a0ddb29 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -51,6 +51,11 @@ hibernate-testing 5.2.2.Final + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + @@ -69,6 +74,7 @@ 2.2.3 1.4.196 3.8.0 + 2.8.11.3 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java new file mode 100644 index 0000000000..d45daabe71 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java @@ -0,0 +1,114 @@ +package com.baeldung.hibernate.operations; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import com.baeldung.hibernate.pojo.Movie; + +/** + * + *Class to illustrate the usage of EntityManager API. + */ +public class HibernateOperations { + + private static final EntityManagerFactory emf; + + /** + * Static block for creating EntityManagerFactory. The Persistence class looks for META-INF/persistence.xml in the classpath. + */ + static { + emf = Persistence.createEntityManagerFactory("com.baeldung.movie_catalog"); + } + + /** + * Static method returning EntityManager. + * @return EntityManager + */ + public static EntityManager getEntityManager() { + return emf.createEntityManager(); + } + + /** + * Saves the movie entity into the database. Here we are using Application Managed EntityManager, hence should handle transactions by ourselves. + */ + public void saveMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + em.getTransaction() + .begin(); + Movie movie = new Movie(); + movie.setId(1L); + movie.setMovieName("The Godfather"); + movie.setReleaseYear(1972); + movie.setLanguage("English"); + em.persist(movie); + em.getTransaction() + .commit(); + } + + /** + * Method to illustrate the querying support in EntityManager when the result is a single object. + * @return Movie + */ + public Movie queryForMovieById() { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = (Movie) em.createQuery("SELECT movie from Movie movie where movie.id = ?1") + .setParameter(1, new Long(1L)) + .getSingleResult(); + return movie; + } + + /** + * Method to illustrate the querying support in EntityManager when the result is a list. + * @return + */ + public List queryForMovies() { + EntityManager em = HibernateOperations.getEntityManager(); + List movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1") + .setParameter(1, "English") + .getResultList(); + return movies; + } + + /** + * Method to illustrate the usage of find() method. + * @param movieId + * @return Movie + */ + public Movie getMovie(Long movieId) { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = em.find(Movie.class, new Long(movieId)); + return movie; + } + + /** + * Method to illustrate the usage of merge() function. + */ + public void mergeMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = getMovie(1L); + em.detach(movie); + movie.setLanguage("Italian"); + em.getTransaction() + .begin(); + em.merge(movie); + em.getTransaction() + .commit(); + } + + /** + * Method to illustrate the usage of remove() function. + */ + public void removeMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + em.getTransaction() + .begin(); + Movie movie = em.find(Movie.class, new Long(1L)); + em.remove(movie); + em.getTransaction() + .commit(); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java new file mode 100644 index 0000000000..6bd1c24869 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.Convert; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Entity +@Table(name = "Customers") +public class Customer { + + @Id + private int id; + + private String firstName; + + private String lastName; + + private String customerAttributeJSON; + + @Convert(converter = HashMapConverter.class) + private Map customerAttributes; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + 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 String getCustomerAttributeJSON() { + return customerAttributeJSON; + } + + public void setCustomerAttributeJSON(String customerAttributeJSON) { + this.customerAttributeJSON = customerAttributeJSON; + } + + public Map getCustomerAttributes() { + return customerAttributes; + } + + public void setCustomerAttributes(Map customerAttributes) { + this.customerAttributes = customerAttributes; + } + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public void serializeCustomerAttributes() throws JsonProcessingException { + this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes); + } + + public void deserializeCustomerAttributes() throws IOException { + this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java new file mode 100644 index 0000000000..b1c2d50480 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.AttributeConverter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hibernate.interceptors.CustomInterceptor; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HashMapConverter implements AttributeConverter, String> { + + private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class); + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public String convertToDatabaseColumn(Map customerInfo) { + + String customerInfoJson = null; + try { + customerInfoJson = objectMapper.writeValueAsString(customerInfo); + } catch (final JsonProcessingException e) { + logger.error("JSON writing error", e); + } + + return customerInfoJson; + } + + @Override + public Map convertToEntityAttribute(String customerInfoJSON) { + + Map customerInfo = null; + try { + customerInfo = objectMapper.readValue(customerInfoJSON, Map.class); + } catch (final IOException e) { + logger.error("JSON reading error", e); + } + + return customerInfo; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java new file mode 100644 index 0000000000..5fae7f6a97 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java @@ -0,0 +1,52 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "MOVIE") +public class Movie { + + @Id + private Long id; + + private String movieName; + + private Integer releaseYear; + + private String language; + + public String getMovieName() { + return movieName; + } + + public void setMovieName(String movieName) { + this.movieName = movieName; + } + + public Integer getReleaseYear() { + return releaseYear; + } + + public void setReleaseYear(Integer releaseYear) { + this.releaseYear = releaseYear; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..4dfade1af3 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,19 @@ + + + + Hibernate EntityManager Demo + com.baeldung.hibernate.pojo.Movie + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java new file mode 100644 index 0000000000..ecbb073e89 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java @@ -0,0 +1,111 @@ +package com.baeldung.hibernate.persistjson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class PersistJSONUnitTest { + + private Session session; + + @Before + public void init() { + try { + Configuration configuration = new Configuration(); + + Properties properties = new Properties(); + properties.load(Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("hibernate-persistjson.properties")); + + configuration.setProperties(properties); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Customer.class); + + SessionFactory factory = metadataSources.buildMetadata() + .buildSessionFactory(); + + session = factory.openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close() { + if (session != null) + session.close(); + } + + @Test + public void givenCustomer_whenCallingSerializeCustomerAttributes_thenAttributesAreConverted() throws IOException { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + customer.serializeCustomerAttributes(); + + String serialized = customer.getCustomerAttributeJSON(); + + customer.setCustomerAttributeJSON(serialized); + customer.deserializeCustomerAttributes(); + + Map deserialized = customer.getCustomerAttributes(); + + assertEquals("123 Main Street", deserialized.get("address")); + } + + @Test + public void givenCustomer_whenSaving_thenAttributesAreConverted() { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + session.beginTransaction(); + + int id = (int) session.save(customer); + + session.flush(); + session.clear(); + + Customer result = session.createNativeQuery("select * from Customers where Customers.id = :id", Customer.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(2, result.getCustomerAttributes() + .size()); + } + +} diff --git a/hibernate5/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties similarity index 52% rename from hibernate5/src/test/resources/hibernate-namedquery.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties index 457f965347..2cf8ac5b63 100644 --- a/hibernate5/src/test/resources/hibernate-namedquery.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties @@ -1,9 +1,7 @@ hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql' +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 hibernate.connection.username=sa -hibernate.connection.autocommit=true -jdbc.password= - hibernate.dialect=org.hibernate.dialect.H2Dialect + hibernate.show_sql=true hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java index 6f1e2ee5ca..2cb5679d4d 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java @@ -1,13 +1,12 @@ package com.baeldung.jpa.stringcast; -import com.sun.istack.internal.Nullable; - -import javax.persistence.EntityManager; -import javax.persistence.Query; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.persistence.Query; + public class QueryExecutor { public static List executeNativeQueryNoCastCheck(String statement, EntityManager em) { @@ -24,10 +23,7 @@ public class QueryExecutor { } if (results.get(0) instanceof String) { - return ((List) results) - .stream() - .map(s -> new String[] { s }) - .collect(Collectors.toList()); + return ((List) results).stream().map(s -> new String[] { s }).collect(Collectors.toList()); } else { return (List) results; } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java index 16407e510a..2bdd4e5451 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java @@ -1,13 +1,14 @@ package com.baeldung.config; -import com.baeldung.services.IBarService; -import com.baeldung.services.impl.BarSpringDataJpaService; -import com.google.common.base.Preconditions; -import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; -import com.baeldung.services.IFooService; -import com.baeldung.services.impl.FooService; +import java.util.Properties; + +import javax.sql.DataSource; + import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @@ -20,13 +21,15 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import javax.sql.DataSource; -import java.util.Properties; +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; +import com.baeldung.services.IBarService; +import com.baeldung.services.impl.BarSpringDataJpaService; +import com.google.common.base.Preconditions; @Configuration -@ComponentScan({"com.baeldung.dao", "com.baeldung.services"}) +@ComponentScan({ "com.baeldung.dao", "com.baeldung.services" }) @EnableTransactionManagement -@EnableJpaRepositories(basePackages = {"com.baeldung.dao"}, repositoryBaseClass = ExtendedRepositoryImpl.class) +@EnableJpaRepositories(basePackages = { "com.baeldung.dao" }, repositoryBaseClass = ExtendedRepositoryImpl.class) @EnableJpaAuditing @PropertySource("classpath:persistence.properties") public class PersistenceConfiguration { @@ -79,11 +82,6 @@ public class PersistenceConfiguration { return new BarSpringDataJpaService(); } - @Bean - public IFooService fooService() { - return new FooService(); - } - private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); @@ -94,7 +92,8 @@ public class PersistenceConfiguration { // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); // Envers properties - hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", + env.getProperty("envers.audit_table_suffix")); return hibernateProperties; } diff --git a/persistence-modules/spring-data-jpa/src/main/resources/application.properties b/persistence-modules/spring-data-jpa/src/main/resources/application.properties index 73d72bc7d6..37fb9ca9c4 100644 --- a/persistence-modules/spring-data-jpa/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa/src/main/resources/application.properties @@ -12,4 +12,6 @@ hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory -spring.datasource.data=import_entities.sql \ No newline at end of file +spring.datasource.data=import_entities.sql + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/test/resources/import_entities.sql b/persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql similarity index 100% rename from persistence-modules/spring-data-jpa/src/test/resources/import_entities.sql rename to persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 0a60412813..7f906bdbcd 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -2,17 +2,12 @@ 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 { diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java new file mode 100644 index 0000000000..66b5b20b97 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java @@ -0,0 +1,25 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ContextConfiguration; +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 }) +@ContextConfiguration(classes = Application.class) +public class SpringJpaContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 683f874b6c..fb80b0413f 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -47,21 +47,9 @@ 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 @@ -97,8 +85,6 @@ 0.10.0 2.0.3.RELEASE 0.6 - 1.0.0 - 5.0.2 diff --git a/persistence-modules/spring-hibernate-3/README.md b/persistence-modules/spring-hibernate-3/README.md index f9839e34bf..ac840b6f66 100644 --- a/persistence-modules/spring-hibernate-3/README.md +++ b/persistence-modules/spring-hibernate-3/README.md @@ -5,6 +5,7 @@ ### Relevant ArticleS: - [Hibernate 3 with Spring](http://www.baeldung.com/hibernate3-spring) +- [HibernateException: No Hibernate Session Bound to Thread in Hibernate 3](http://www.baeldung.com/no-hibernate-session-bound-to-thread-exception) ### Quick Start diff --git a/persistence-modules/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java similarity index 100% rename from persistence-modules/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java diff --git a/persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java similarity index 98% rename from persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java index bbbf074c1a..08032660c0 100644 --- a/persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java @@ -1,7 +1,5 @@ package org.baeldung.persistence.service; -import java.util.List; - import org.baeldung.persistence.model.Event; import org.baeldung.spring.PersistenceConfigHibernate3; import org.hamcrest.core.IsInstanceOf; diff --git a/persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java similarity index 98% rename from persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java index d8810f0e90..44cc6ca010 100644 --- a/persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java @@ -1,7 +1,5 @@ package org.baeldung.persistence.service; -import java.util.List; - import org.baeldung.persistence.model.Event; import org.baeldung.spring.PersistenceConfig; import org.hamcrest.core.IsInstanceOf; diff --git a/persistence-modules/spring-hibernate3/README.md b/persistence-modules/spring-hibernate3/README.md deleted file mode 100644 index 02928dfb51..0000000000 --- a/persistence-modules/spring-hibernate3/README.md +++ /dev/null @@ -1,2 +0,0 @@ -## Relevant articles: -- [HibernateException: No Hibernate Session Bound to Thread in Hibernate 3](http://www.baeldung.com/no-hibernate-session-bound-to-thread-exception) diff --git a/pom.xml b/pom.xml index dabb4a9628..4e1e61961e 100644 --- a/pom.xml +++ b/pom.xml @@ -324,169 +324,241 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java parent-kotlin - asm - atomix - aws - aws-lambda akka-streams algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-sorting + animal-sniffer-mvn-plugin annotations + antlr + apache-avro + apache-bval + apache-curator apache-cxf apache-fop - apache-poi - apache-tika - apache-thrift - apache-curator - apache-zookeeper + apache-geode + apache-meecrowave apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix autovalue + aws + aws-lambda axon azure - apache-velocity - apache-solrj - apache-meecrowave - antlr - - bootique - - cdi - core-java-collections - core-java-io - core-java-8 - core-groovy - couchbase - - - core-java - core-java-net - dozer - disruptor - drools + bootique + + cas/cas-secured-app + cas/cas-server + cdi + checker-plugin + core-groovy + + + core-java-8 + + core-java-arrays + core-java-collections + core-java-concurrency-collections + core-java-io + core-java-lang + core-java-networking + core-java-sun + core-scala + couchbase + custom-pmd + + dagger + data-structures + ddd deeplearning4j + disruptor + dozer + drools + dubbo ethereum feign flips + flyway-cdi-extension + geotools google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc gson guava guava-collections guava-modules/guava-18 guava-modules/guava-19 guava-modules/guava-21 + guice hazelcast - hystrix + helidon httpclient + hystrix image-processing immutables - + jackson - java-strings - java-collections-conversions java-collections-maps - java-streams + + java-ee-8-security-api java-lite java-numbers java-rmi + java-spi + java-streams + java-strings java-vavr-stream + java-websocket + javafx javax-servlets javaxval jaxb - javafx - jgroups jee-7-security + jersey + JGit + jgroups + jhipster + jib jjwt + jmeter + jmh + jni + jooby jsf - json-path json + json-path jsoup jta - jws - jersey - java-spi - java-ee-8-security-api + + + kotlin-libraries - + libraries-data + libraries-security + libraries-server linkrest - logging-modules/log-mdc logging-modules/log4j + logging-modules/log4j2 logging-modules/logback + logging-modules/log-mdc lombok lucene - + mapstruct maven + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + mesos-marathon + metrics + + microprofile msf4j + mustache mvn-wrapper mybatis - metrics - maven-archetype noexception - osgi + optaplanner orika - + osgi + patterns pdf - protobuffer performance-tests + + protobuffer + persistence-modules/activejdbc + persistence-modules/apache-cayenne + persistence-modules/core-java-persistence + persistence-modules/deltaspike + persistence-modules/flyway + persistence-modules/hbase + persistence-modules/hibernate5 + persistence-modules/influxdb + persistence-modules/java-cassandra + persistence-modules/java-cockroachdb persistence-modules/java-jdbi - persistence-modules/redis + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql + persistence-modules/liquibase persistence-modules/orientdb persistence-modules/querydsl - persistence-modules/apache-cayenne + persistence-modules/redis persistence-modules/solr - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-solr - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - persistence-modules/spring-jpa - persistence-modules/spring-hibernate-3 - persistence-modules/spring-data-gemfire + persistence-modules/spring-boot-h2/spring-boot-h2-database persistence-modules/spring-boot-persistence - persistence-modules/liquibase - persistence-modules/java-cockroachdb - persistence-modules/deltaspike - persistence-modules/hbase - persistence-modules/influxdb - persistence-modules/spring-hibernate4 - persistence-modules/spring-data-mongodb - persistence-modules/java-cassandra + persistence-modules/spring-boot-persistence-mongodb persistence-modules/spring-data-cassandra + persistence-modules/spring-data-cassandra-reactive persistence-modules/spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb + persistence-modules/spring-data-eclipselink + persistence-modules/spring-data-elasticsearch + persistence-modules/spring-data-gemfire + persistence-modules/spring-data-jpa + persistence-modules/spring-data-keyvalue + persistence-modules/spring-data-mongodb + persistence-modules/spring-data-neo4j persistence-modules/spring-data-redis - persistence-modules/spring-boot-persistence-mongodb - - reactor-core - resteasy - rxjava - rxjava-2 + persistence-modules/spring-data-solr + persistence-modules/spring-hibernate-3 + persistence-modules/spring-hibernate-5 + persistence-modules/spring-hibernate4 + persistence-modules/spring-jpa + rabbitmq - + + ratpack + reactor-core + rest-with-spark-java + resteasy + restx + + rule-engines/easy-rules + rule-engines/openl-tablets + rule-engines/rulebook + rsocket + rxjava + rxjava-2 + @@ -520,103 +592,126 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java parent-kotlin - spring-4 - spring-5 - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client - spring-5-mvc - spring-5-security - spring-5-security-oauth + saas + spark-java + + spring-4 + + spring-5 + spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth - spring-aop spring-activiti spring-akka - spring-amqp spring-all + spring-amqp + spring-aop spring-apache-camel spring-batch spring-bom - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-camel - spring-boot-security - spring-boot-mvc - spring-boot-logging-log4j2 - spring-boot-disable-console-logging - spring-boot-property-exp - spring-boot-ctx-fluent - spring-boot - spring-boot-ops - spring-cloud-data-flow + spring-boot + spring-boot-admin + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-ops + spring-boot-property-exp + spring-boot-security + spring-boot-vue + spring-cloud spring-cloud-bus + + spring-cloud-data-flow + spring-core spring-cucumber + spring-data-rest - spring-drools + spring-data-rest-querydsl spring-dispatcher-servlet + spring-drools + spring-ejb spring-exceptions spring-freemarker + + spring-groovy + spring-integration - spring-jinq spring-jenkins-pipeline spring-jersey + spring-jinq spring-jms spring-jooq + spring-kafka spring-katharsis + spring-ldap + spring-mobile spring-mockito + spring-mustache spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple spring-mvc-velocity spring-mvc-webflow spring-mvc-xml - spring-mvc-kotlin + spring-mybatis spring-protobuf + spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - spring-rest - spring-resttemplate - spring-rest-simple - spring-remoting - spring-session - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-thymeleaf - spring-userservice - - spring-zuul + spring-reactive-kotlin spring-reactor - spring-vertx - spring-vault + spring-remoting + spring-rest + spring-rest-angular spring-rest-embedded-tomcat - spring-swagger-codegen - spring-webflux-amqp + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-rest-template + spring-resttemplate + spring-roo - spring-static-resources - spring-security-thymeleaf spring-security-acl + spring-security-angular/server 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 @@ -624,8 +719,10 @@ 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-login @@ -634,65 +731,73 @@ spring-security-mvc-socket spring-security-openid + spring-security-rest spring-security-rest-basic-auth spring-security-rest-custom - spring-security-rest spring-security-sso + spring-security-stormpath + spring-security-thymeleaf spring-security-x509 - spring-security-mvc-custom + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spark-java - saas + spring-thymeleaf + + spring-userservice + + spring-vault + spring-vertx + + spring-webflux-amqp + + spring-zuul + + sse-jaxrs + static-analysis + stripe + structurizr struts-2 - testing-modules/selenium-junit-testng + testing-modules/gatling testing-modules/groovy-spock + testing-modules/junit-5 + testing-modules/junit5-migration + testing-modules/load-testing-comparison testing-modules/mockito testing-modules/mockito-2 testing-modules/mocks + testing-modules/mockserver + testing-modules/parallel-tests-junit testing-modules/rest-assured testing-modules/rest-testing - testing-modules/junit-5 - testing-modules/junit5-migration + + testing-modules/selenium-junit-testng + testing-modules/spring-testing + testing-modules/test-containers testing-modules/testing testing-modules/testng - testing-modules/mockserver - testing-modules/test-containers + twilio + Twitter4J undertow - video-tutorials - vaadin - vertx-and-rxjava - vraptor - vertx vavr + vertx + vertx-and-rxjava + video-tutorials + vraptor + + wicket - xmlunit-2 xml - - - - - - - - - + xmlunit-2 + xstream @@ -842,7 +947,7 @@ spring-swagger-codegen/spring-swagger-codegen-app spring-thymeleaf spring-userservice - spring-vault + spring-vault spring-vertx spring-zuul/spring-zuul-foos-resource persistence-modules/spring-data-dynamodb @@ -853,6 +958,61 @@ + + default-heavy + + + + + 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 + + + + + + + + + parent-boot-1 + parent-boot-2 + parent-boot-2.0-temp + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + core-java + core-java-concurrency + core-kotlin + + jenkins/hello-world + jws + + libraries + + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/jnosql + + spring-5-data-reactive + spring-amqp-simple + + vaadin + + + integration-lite-first @@ -878,169 +1038,242 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java parent-kotlin - asm - atomix - aws - aws-lambda akka-streams algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-sorting + animal-sniffer-mvn-plugin annotations + antlr + apache-avro + apache-bval + apache-curator apache-cxf apache-fop - apache-poi - apache-tika - apache-thrift - apache-curator - apache-zookeeper + apache-geode + apache-meecrowave apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix autovalue + aws + aws-lambda axon azure - apache-velocity - apache-solrj - apache-meecrowave - antlr - + bootique - + + cas/cas-secured-app + cas/cas-server cdi - core-java-collections - core-java-io - core-java-8 + checker-plugin core-groovy + + + core-java-8 + + core-java-arrays + core-java-collections + core-java-concurrency-collections + core-java-io + core-java-lang + core-java-networking + core-java-sun + core-scala couchbase - - - core-java - core-java-net - - dozer - disruptor - drools + custom-pmd + + dagger + data-structures + ddd deeplearning4j + disruptor + dozer + drools + dubbo ethereum feign flips + flyway-cdi-extension + geotools google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc gson guava guava-collections guava-modules/guava-18 guava-modules/guava-19 guava-modules/guava-21 + guice hazelcast - hystrix + helidon httpclient + hystrix image-processing immutables - + jackson - java-strings - java-collections-conversions java-collections-maps - java-streams + + java-ee-8-security-api java-lite java-numbers java-rmi + java-spi + java-streams + java-strings java-vavr-stream + java-websocket + javafx javax-servlets javaxval jaxb - javafx - jgroups jee-7-security + jersey + JGit + jgroups + jhipster + jib jjwt + jmeter + jmh + jni + jooby jsf - json-path json + json-path jsoup jta - jws - jersey - java-spi - java-ee-8-security-api + + + kotlin-libraries - + libraries-data + libraries-security + libraries-server linkrest - logging-modules/log-mdc logging-modules/log4j + logging-modules/log4j2 logging-modules/logback + logging-modules/log-mdc lombok lucene - + mapstruct maven + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + mesos-marathon + metrics + + microprofile msf4j + mustache mvn-wrapper mybatis - metrics - maven-archetype noexception - osgi + optaplanner orika - + osgi + patterns pdf - protobuffer performance-tests + + protobuffer + persistence-modules/activejdbc + persistence-modules/apache-cayenne + persistence-modules/core-java-persistence + persistence-modules/deltaspike + persistence-modules/flyway + persistence-modules/hbase + persistence-modules/hibernate5 + persistence-modules/influxdb + persistence-modules/java-cassandra + persistence-modules/java-cockroachdb persistence-modules/java-jdbi - persistence-modules/redis + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql + persistence-modules/liquibase persistence-modules/orientdb persistence-modules/querydsl - persistence-modules/apache-cayenne + persistence-modules/redis persistence-modules/solr - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-solr - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - persistence-modules/spring-jpa - persistence-modules/spring-hibernate-3 - persistence-modules/spring-data-gemfire + persistence-modules/spring-boot-h2/spring-boot-h2-database persistence-modules/spring-boot-persistence - persistence-modules/liquibase - persistence-modules/java-cockroachdb - persistence-modules/deltaspike - persistence-modules/hbase - persistence-modules/influxdb - persistence-modules/spring-hibernate4 - persistence-modules/spring-data-mongodb - persistence-modules/java-cassandra + persistence-modules/spring-boot-persistence-mongodb persistence-modules/spring-data-cassandra + persistence-modules/spring-data-cassandra-reactive persistence-modules/spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb + persistence-modules/spring-data-eclipselink + persistence-modules/spring-data-elasticsearch + persistence-modules/spring-data-gemfire + persistence-modules/spring-data-jpa + persistence-modules/spring-data-keyvalue + persistence-modules/spring-data-mongodb + persistence-modules/spring-data-neo4j persistence-modules/spring-data-redis - - reactor-core - resteasy - rxjava - rxjava-2 + persistence-modules/spring-data-solr + persistence-modules/spring-hibernate-3 + persistence-modules/spring-hibernate-5 + persistence-modules/spring-hibernate4 + persistence-modules/spring-jpa + rabbitmq - - + + ratpack + reactor-core + rest-with-spark-java + resteasy + restx + + rule-engines/easy-rules + rule-engines/openl-tablets + rule-engines/rulebook + rsocket + rxjava + rxjava-2 + + @@ -1069,103 +1302,126 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java parent-kotlin - spring-4 - spring-5 - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client - spring-5-mvc - spring-5-security - spring-5-security-oauth + saas + spark-java + + spring-4 + + spring-5 + spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth - spring-aop spring-activiti spring-akka - spring-amqp spring-all + spring-amqp + spring-aop spring-apache-camel spring-batch spring-bom - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-camel - spring-boot-security - spring-boot-mvc - spring-boot-logging-log4j2 - spring-boot-disable-console-logging - spring-boot-property-exp - spring-boot-ctx-fluent - spring-boot - spring-boot-ops - spring-cloud-data-flow + spring-boot + spring-boot-admin + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-ops + spring-boot-property-exp + spring-boot-security + spring-boot-vue + spring-cloud spring-cloud-bus + + spring-cloud-data-flow + spring-core spring-cucumber + spring-data-rest - spring-drools + spring-data-rest-querydsl spring-dispatcher-servlet + spring-drools + spring-ejb spring-exceptions spring-freemarker + + spring-groovy + spring-integration - spring-jinq spring-jenkins-pipeline spring-jersey + spring-jinq spring-jms spring-jooq + spring-kafka spring-katharsis + spring-ldap + spring-mobile spring-mockito + spring-mustache spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple spring-mvc-velocity spring-mvc-webflow spring-mvc-xml - spring-mvc-kotlin + spring-mybatis spring-protobuf + spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - spring-rest - spring-resttemplate - spring-rest-simple - spring-remoting - spring-session - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-thymeleaf - spring-userservice - - spring-zuul + spring-reactive-kotlin spring-reactor - spring-vertx - spring-vault + spring-remoting + spring-rest + spring-rest-angular spring-rest-embedded-tomcat - spring-swagger-codegen - spring-webflux-amqp + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-rest-template + spring-resttemplate + spring-roo - spring-static-resources - spring-security-thymeleaf spring-security-acl + spring-security-angular/server 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 @@ -1173,8 +1429,10 @@ 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-login @@ -1183,65 +1441,73 @@ spring-security-mvc-socket spring-security-openid + spring-security-rest spring-security-rest-basic-auth spring-security-rest-custom - spring-security-rest spring-security-sso + spring-security-stormpath + spring-security-thymeleaf spring-security-x509 - spring-security-mvc-custom + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spark-java - saas + spring-thymeleaf + + spring-userservice + + spring-vault + spring-vertx + + spring-webflux-amqp + + spring-zuul + + sse-jaxrs + static-analysis + stripe + structurizr struts-2 - testing-modules/selenium-junit-testng + testing-modules/gatling testing-modules/groovy-spock + testing-modules/junit-5 + testing-modules/junit5-migration + testing-modules/load-testing-comparison testing-modules/mockito testing-modules/mockito-2 testing-modules/mocks + testing-modules/mockserver + testing-modules/parallel-tests-junit testing-modules/rest-assured testing-modules/rest-testing - testing-modules/junit-5 - testing-modules/junit5-migration + + testing-modules/selenium-junit-testng + testing-modules/spring-testing + testing-modules/test-containers testing-modules/testing testing-modules/testng - testing-modules/mockserver - testing-modules/test-containers + twilio + Twitter4J undertow - video-tutorials - vaadin - vertx-and-rxjava - vraptor - vertx vavr + vertx + vertx-and-rxjava + video-tutorials + vraptor + + wicket - xmlunit-2 xml - - - - - - - - - + xmlunit-2 + xstream @@ -1272,12 +1538,29 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java - parent-kotlin + parent-kotlin - + core-java + core-java-concurrency + core-kotlin + + jenkins/hello-world + jws + + libraries + + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/jnosql + + spring-5-data-reactive + spring-amqp-simple + + vaadin diff --git a/rmi/README.md b/rmi/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/rmi/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/rmi/client.policy b/rmi/client.policy deleted file mode 100644 index 5d74bde76d..0000000000 --- a/rmi/client.policy +++ /dev/null @@ -1,3 +0,0 @@ -grant { - permission java.security.AllPermission; -}; \ No newline at end of file diff --git a/rmi/server.policy b/rmi/server.policy deleted file mode 100644 index 5d74bde76d..0000000000 --- a/rmi/server.policy +++ /dev/null @@ -1,3 +0,0 @@ -grant { - permission java.security.AllPermission; -}; \ No newline at end of file diff --git a/rmi/src/org/baeldung/Client.java b/rmi/src/org/baeldung/Client.java deleted file mode 100644 index 0376952bab..0000000000 --- a/rmi/src/org/baeldung/Client.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung; - -import java.rmi.NotBoundException; -import java.rmi.RemoteException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; - -public class Client { - public static void main(String[] args) throws RemoteException, NotBoundException { - System.setProperty("java.security.policy", "file:./client.policy"); - if (System.getSecurityManager() == null) { - System.setSecurityManager(new SecurityManager()); - } - String name = "RandomNumberGenerator"; - Registry registry = LocateRegistry.getRegistry(); - RandomNumberGenerator randomNumberGenerator = (RandomNumberGenerator) registry.lookup(name); - int number = randomNumberGenerator.get(); - System.out.println("Received random number:" + number); - } -} diff --git a/rmi/src/org/baeldung/RandomNumberGenerator.java b/rmi/src/org/baeldung/RandomNumberGenerator.java deleted file mode 100644 index 50e49d2652..0000000000 --- a/rmi/src/org/baeldung/RandomNumberGenerator.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung; - -import java.rmi.Remote; -import java.rmi.RemoteException; - -public interface RandomNumberGenerator extends Remote{ - int get() throws RemoteException; -} diff --git a/rmi/src/org/baeldung/RandomNumberGeneratorEngine.java b/rmi/src/org/baeldung/RandomNumberGeneratorEngine.java deleted file mode 100644 index 04d90b2ff9..0000000000 --- a/rmi/src/org/baeldung/RandomNumberGeneratorEngine.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung; - -import java.rmi.RemoteException; - -public class RandomNumberGeneratorEngine implements RandomNumberGenerator { - @Override - public int get() throws RemoteException { - return (int) (100 * Math.random()); - } -} diff --git a/rmi/src/org/baeldung/Server.java b/rmi/src/org/baeldung/Server.java deleted file mode 100644 index 8e613cb6bb..0000000000 --- a/rmi/src/org/baeldung/Server.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung; - -import java.rmi.RemoteException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; -import java.rmi.server.UnicastRemoteObject; - -public class Server { - public static void main(String[] args) throws RemoteException { - System.setProperty("java.security.policy", "file:./server.policy"); - if (System.getSecurityManager() == null) { - System.setSecurityManager(new SecurityManager()); - } - String name = "RandomNumberGenerator"; - RandomNumberGenerator randomNumberGenerator = new RandomNumberGeneratorEngine(); - RandomNumberGenerator stub = - (RandomNumberGenerator) UnicastRemoteObject.exportObject(randomNumberGenerator, 0); - Registry registry = LocateRegistry.getRegistry(); - registry.rebind(name, stub); - System.out.println("RandomNumberGenerator bound"); - } -} diff --git a/rsocket/pom.xml b/rsocket/pom.xml new file mode 100644 index 0000000000..8b04a31583 --- /dev/null +++ b/rsocket/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + rsocket + 0.0.1-SNAPSHOT + rsocket + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + jar + + + + io.rsocket + rsocket-core + 0.11.13 + + + io.rsocket + rsocket-transport-netty + 0.11.13 + + + junit + junit + 4.12 + test + + + org.hamcrest + hamcrest-core + 1.3 + test + + + ch.qos.logback + logback-classic + 1.2.3 + + + ch.qos.logback + logback-core + 1.2.3 + + + org.slf4j + slf4j-api + 1.7.25 + + + \ No newline at end of file diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java new file mode 100644 index 0000000000..f35d337427 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java @@ -0,0 +1,33 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import com.baeldung.rsocket.support.GameController; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import reactor.core.publisher.Flux; + +public class ChannelClient { + + private final RSocket socket; + private final GameController gameController; + + public ChannelClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + + this.gameController = new GameController("Client Player"); + } + + public void playGame() { + socket.requestChannel(Flux.from(gameController)) + .doOnNext(gameController::processPayload) + .blockLast(); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java new file mode 100644 index 0000000000..496b3fc5c9 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java @@ -0,0 +1,85 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; + +public class FireNForgetClient { + + private static final Logger LOG = LoggerFactory.getLogger(FireNForgetClient.class); + + private final RSocket socket; + private final List data; + + public FireNForgetClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + this.data = Collections.unmodifiableList(generateData()); + } + + /** + * Send binary velocity (float) every 50ms + */ + public void sendData() { + Flux.interval(Duration.ofMillis(50)) + .take(data.size()) + .map(this::createFloatPayload) + .flatMap(socket::fireAndForget) + .blockLast(); + } + + /** + * Create a binary payload containing a single float value + * + * @param index Index into the data list + * @return Payload ready to send to the server + */ + private Payload createFloatPayload(Long index) { + float velocity = data.get(index.intValue()); + ByteBuffer buffer = ByteBuffer.allocate(4).putFloat(velocity); + buffer.rewind(); + return DefaultPayload.create(buffer); + } + + /** + * Generate sample data + * + * @return List of random floats + */ + private List generateData() { + List dataList = new ArrayList<>(WIND_DATA_LENGTH); + float velocity = 0; + for (int i = 0; i < WIND_DATA_LENGTH; i++) { + velocity += Math.random(); + dataList.add(velocity); + } + return dataList; + } + + /** + * Get the data used for this client. + * + * @return list of data values + */ + public List getData() { + return data; + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java new file mode 100644 index 0000000000..fff196a580 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java @@ -0,0 +1,32 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; + +public class ReqResClient { + + private final RSocket socket; + + public ReqResClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + } + + public String callBlocking(String string) { + return socket + .requestResponse(DefaultPayload.create(string)) + .map(Payload::getDataUtf8) + .onErrorReturn(ERROR_MSG) + .block(); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java new file mode 100644 index 0000000000..e97192bdf0 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java @@ -0,0 +1,33 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; +import reactor.core.publisher.Flux; + +public class ReqStreamClient { + + private final RSocket socket; + + public ReqStreamClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + } + + public Flux getDataStream() { + return socket + .requestStream(DefaultPayload.create(WIND_DATA_STREAM_NAME)) + .map(Payload::getData) + .map(buf -> buf.getFloat()) + .onErrorReturn(null); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/Server.java b/rsocket/src/main/java/com/baeldung/rsocket/Server.java new file mode 100644 index 0000000000..b5718ab36d --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/Server.java @@ -0,0 +1,107 @@ +package com.baeldung.rsocket; + +import com.baeldung.rsocket.support.WindDataPublisher; +import static com.baeldung.rsocket.support.Constants.*; +import com.baeldung.rsocket.support.GameController; +import io.rsocket.AbstractRSocket; +import io.rsocket.Payload; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.server.TcpServerTransport; +import org.reactivestreams.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.Disposable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class Server { + + private static final Logger LOG = LoggerFactory.getLogger(Server.class); + + private final Disposable server; + private final WindDataPublisher windDataPublisher = new WindDataPublisher(); + private final GameController gameController; + + public Server() { + this.server = RSocketFactory.receive() + .acceptor((setupPayload, reactiveSocket) -> Mono.just(new RSocketImpl())) + .transport(TcpServerTransport.create("localhost", TCP_PORT)) + .start() + .doOnNext(x -> LOG.info("Server started")) + .subscribe(); + + this.gameController = new GameController("Server Player"); + } + + public void dispose() { + windDataPublisher.complete(); + this.server.dispose(); + } + + /** + * RSocket implementation + */ + private class RSocketImpl extends AbstractRSocket { + + /** + * Handle Request/Response messages + * + * @param payload Message payload + * @return payload response + */ + @Override + public Mono requestResponse(Payload payload) { + try { + return Mono.just(payload); // reflect the payload back to the sender + } catch (Exception x) { + return Mono.error(x); + } + } + + /** + * Handle Fire-and-Forget messages + * + * @param payload Message payload + * @return nothing + */ + @Override + public Mono fireAndForget(Payload payload) { + try { + windDataPublisher.publish(payload); // forward the payload + return Mono.empty(); + } catch (Exception x) { + return Mono.error(x); + } + } + + /** + * Handle Request/Stream messages. Each request returns a new stream. + * + * @param payload Payload that can be used to determine which stream to return + * @return Flux stream containing simulated wind speed data + */ + @Override + public Flux requestStream(Payload payload) { + String streamName = payload.getDataUtf8(); + if (WIND_DATA_STREAM_NAME.equals(streamName)) { + return Flux.from(windDataPublisher); + } + return Flux.error(new IllegalArgumentException(streamName)); + } + + /** + * Handle request for bidirectional channel + * + * @param payloads Stream of payloads delivered from the client + * @return + */ + @Override + public Flux requestChannel(Publisher payloads) { + Flux.from(payloads) + .subscribe(gameController::processPayload); + Flux channel = Flux.from(gameController); + return channel; + } + } + +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java new file mode 100644 index 0000000000..01bb374b4e --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java @@ -0,0 +1,10 @@ +package com.baeldung.rsocket.support; + +public interface Constants { + + int TCP_PORT = 7101; + String ERROR_MSG = "error"; + int WIND_DATA_LENGTH = 30; + String WIND_DATA_STREAM_NAME = "wind-data"; + int SHOT_COUNT = 10; +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java new file mode 100644 index 0000000000..bc1bc0f861 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java @@ -0,0 +1,84 @@ +package com.baeldung.rsocket.support; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.util.DefaultPayload; +import java.util.List; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; + +public class GameController implements Publisher { + + private static final Logger LOG = LoggerFactory.getLogger(GameController.class); + + private final String playerName; + private final List shots; + private Subscriber subscriber; + private boolean truce = false; + + public GameController(String playerName) { + this.playerName = playerName; + this.shots = generateShotList(); + } + + /** + * Create a random list of time intervals, 0-1000ms + * + * @return List of time intervals + */ + private List generateShotList() { + return Flux.range(1, SHOT_COUNT) + .map(x -> (long) Math.ceil(Math.random() * 1000)) + .collectList() + .block(); + } + + @Override + public void subscribe(Subscriber subscriber) { + this.subscriber = subscriber; + fireAtWill(); + } + + /** + * Publish game events asynchronously + */ + private void fireAtWill() { + new Thread(() -> { + for (Long shotDelay : shots) { + try { Thread.sleep(shotDelay); } catch (Exception x) {} + if (truce) { + break; + } + LOG.info("{}: bang!", playerName); + subscriber.onNext(DefaultPayload.create("bang!")); + } + if (!truce) { + LOG.info("{}: I give up!", playerName); + subscriber.onNext(DefaultPayload.create("I give up")); + } + subscriber.onComplete(); + }).start(); + } + + /** + * Process events from the opponent + * + * @param payload Payload received from the rSocket + */ + public void processPayload(Payload payload) { + String message = payload.getDataUtf8(); + switch (message) { + case "bang!": + String result = Math.random() < 0.5 ? "Haha missed!" : "Ow!"; + LOG.info("{}: {}", playerName, result); + break; + case "I give up": + truce = true; + LOG.info("{}: OK, truce", playerName); + break; + } + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java b/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java new file mode 100644 index 0000000000..2ad5b5144b --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java @@ -0,0 +1,31 @@ +package com.baeldung.rsocket.support; + +import io.rsocket.Payload; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; + +/** + * Simple PUblisher to provide async data to Flux stream + */ +public class WindDataPublisher implements Publisher { + + private Subscriber subscriber; + + @Override + public void subscribe(Subscriber subscriber) { + this.subscriber = subscriber; + } + + public void publish(Payload payload) { + if (subscriber != null) { + subscriber.onNext(payload); + } + } + + public void complete() { + if (subscriber != null) { + subscriber.onComplete(); + } + } + +} diff --git a/ethereumj/src/main/resources/logback.xml b/rsocket/src/main/resources/logback.xml similarity index 100% rename from ethereumj/src/main/resources/logback.xml rename to rsocket/src/main/resources/logback.xml diff --git a/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java b/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java new file mode 100644 index 0000000000..afa3960eac --- /dev/null +++ b/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java @@ -0,0 +1,84 @@ +package com.baeldung.rsocket; + +import java.util.ArrayList; +import java.util.List; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.Disposable; + +public class RSocketIntegrationTest { + + private static final Logger LOG = LoggerFactory.getLogger(RSocketIntegrationTest.class); + + private static Server server; + + public RSocketIntegrationTest() { + } + + @BeforeClass + public static void setUpClass() { + server = new Server(); + } + + @AfterClass + public static void tearDownClass() { + server.dispose(); + } + + @Test + public void whenSendingAString_thenRevceiveTheSameString() { + ReqResClient client = new ReqResClient(); + String string = "Hello RSocket"; + + assertEquals(string, client.callBlocking(string)); + + client.dispose(); + } + + @Test + public void whenSendingStream_thenReceiveTheSameStream() { + // create the client that pushes data to the server and start sending + FireNForgetClient fnfClient = new FireNForgetClient(); + // create a client to read a stream from the server and subscribe to events + ReqStreamClient streamClient = new ReqStreamClient(); + + // get the data that is used by the client + List data = fnfClient.getData(); + // create a place to count the results + List dataReceived = new ArrayList<>(); + + // assert that the data received is the same as the data sent + Disposable subscription = streamClient.getDataStream() + .index() + .subscribe( + tuple -> { + assertEquals("Wrong value", data.get(tuple.getT1().intValue()), tuple.getT2()); + dataReceived.add(tuple.getT2()); + }, + err -> LOG.error(err.getMessage()) + ); + + // start sending the data + fnfClient.sendData(); + + // wait a short time for the data to complete then dispose everything + try { Thread.sleep(500); } catch (Exception x) {} + subscription.dispose(); + fnfClient.dispose(); + + // verify the item count + assertEquals("Wrong data count received", data.size(), dataReceived.size()); + } + + @Test + public void whenRunningChannelGame_thenLogTheResults() { + ChannelClient client = new ChannelClient(); + client.playGame(); + client.dispose(); + } + +} diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml index 3b4c167f3a..3038c20037 100644 --- a/rxjava-2/pom.xml +++ b/rxjava-2/pom.xml @@ -1,45 +1,53 @@ - - 4.0.0 - rxjava-2 - 1.0-SNAPSHOT - rxjava-2 - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + 4.0.0 - - - io.reactivex.rxjava2 - rxjava - ${rx.java2.version} - - - com.jayway.awaitility - awaitility - ${awaitility.version} - - - org.assertj - assertj-core - ${assertj.version} - - - com.jakewharton.rxrelay2 - rxrelay - ${rxrelay.version} - - + rxjava-2 + 1.0-SNAPSHOT - - 3.8.0 - 2.2.2 - 1.7.0 - 2.0.0 - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} + + + com.jayway.awaitility + awaitility + ${awaitility.version} + + + org.assertj + assertj-core + ${assertj.version} + + + com.jakewharton.rxrelay2 + rxrelay + ${rxrelay.version} + + + + com.github.akarnokd + rxjava2-extensions + ${rxjava2.ext.version} + + + + + 3.8.0 + 2.2.2 + 1.7.0 + 2.0.0 + 0.20.4 + \ No newline at end of file diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java new file mode 100644 index 0000000000..90f4fe94ae --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java @@ -0,0 +1,107 @@ +package com.baeldung.rxjava; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import hu.akarnokd.rxjava2.async.AsyncObservable; +import io.reactivex.Observable; + +public class AsyncAndSyncToObservableIntegrationTest { + + AtomicInteger counter = new AtomicInteger(); + Callable callable = () -> counter.incrementAndGet(); + + /* Method will execute every time it gets subscribed*/ + @Test + public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() { + + Observable source = Observable.fromCallable(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + } + + /* Method will execute only once and cache its result.*/ + @Test + public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() { + + Observable source = AsyncObservable.start(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + } + + /* Method will execute only once and cache its result.*/ + @Test + public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() { + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future future = executor.submit(callable); + Observable source = Observable.fromFuture(future); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + + executor.shutdown(); + } + + /* Method will execute every time it gets subscribed*/ + @Test + public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() { + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Observable source = AsyncObservable.startFuture(() -> executor.submit(callable)); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + + executor.shutdown(); + } + + /*Method will execute only once and cache its result.*/ + @Test + public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { + List list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() }); + ExecutorService exec = Executors.newSingleThreadExecutor(); + Callable> callable = () -> Observable.fromIterable(list); + Observable source = AsyncObservable.deferFuture(() -> exec.submit(callable)); + for (int i = 1; i < 4; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1, 2, 3); + } + + exec.shutdown(); + } + +} diff --git a/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt index af29a429a4..5a59d11de0 100644 --- a/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt +++ b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt @@ -2,8 +2,9 @@ package com.baeldung import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration -@SpringBootApplication +@SpringBootApplication(exclude = arrayOf(MongoReactiveDataAutoConfiguration::class)) class Application fun main(args: Array) { diff --git a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java index 8251467122..74a348dea6 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java @@ -4,10 +4,11 @@ import javax.servlet.Filter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@SpringBootApplication +@SpringBootApplication( exclude = SecurityAutoConfiguration.class) public class Spring5Application { public static void main(String[] args) { diff --git a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt index f95586af80..8904d8d805 100644 --- a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt +++ b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt @@ -2,8 +2,9 @@ package com.baeldung.springbootkotlin import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration -@SpringBootApplication(scanBasePackages = arrayOf("com.baeldung.springbootkotlin")) +@SpringBootApplication(scanBasePackages = arrayOf("com.baeldung.springbootkotlin"), exclude = arrayOf(SecurityAutoConfiguration::class)) class KotlinDemoApplication fun main(args: Array) { diff --git a/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java b/spring-5-mvc/src/test/java/com/baeldung/LiveTest.java similarity index 100% rename from spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java rename to spring-5-mvc/src/test/java/com/baeldung/LiveTest.java diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java index f07ddfb0f7..03943d436d 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java @@ -1,9 +1,7 @@ package com.baeldung.reactive.actuator; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; @SpringBootApplication public class Spring5ReactiveApplication{ diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java index f2963c4fa5..325923f577 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java @@ -8,8 +8,9 @@ import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.config.EnableWebFlux; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import reactor.ipc.netty.NettyContext; -import reactor.ipc.netty.http.server.HttpServer; + +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; @ComponentScan(basePackages = {"com.baeldung.reactive.security"}) @EnableWebFlux @@ -18,17 +19,19 @@ public class SpringSecurity5Application { public static void main(String[] args) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringSecurity5Application.class)) { - context.getBean(NettyContext.class).onClose().block(); + context.getBean(DisposableServer.class).onDispose().block(); } } @Bean - public NettyContext nettyContext(ApplicationContext context) { + public DisposableServer disposableServer(ApplicationContext context) { HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context) .build(); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); - HttpServer httpServer = HttpServer.create("localhost", 8080); - return httpServer.newHandler(adapter).block(); + HttpServer httpServer = HttpServer.create(); + httpServer.host("localhost"); + httpServer.port(8080); + return httpServer.handle(adapter).bindNow(); } } diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index e903b57c4e..ab64d1e2fa 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -75,6 +75,11 @@ spring-boot-starter-test test + + org.springframework.security + spring-security-test + test + @@ -116,12 +121,6 @@ ${project-reactor-test} test - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - @@ -145,7 +144,6 @@ 1.0 4.1 3.1.6.RELEASE - 1.2.0 diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerDebuggingApplication.java similarity index 80% rename from spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerSSEApplication.java rename to spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerDebuggingApplication.java index 55db3d7392..486c5e77eb 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerDebuggingApplication.java @@ -14,17 +14,17 @@ import reactor.core.publisher.Hooks; @SpringBootApplication(exclude = MongoReactiveAutoConfiguration.class) @EnableScheduling -public class ConsumerSSEApplication { +public class ConsumerDebuggingApplication { public static void main(String[] args) { Hooks.onOperatorDebug(); - SpringApplication app = new SpringApplication(ConsumerSSEApplication.class); + SpringApplication app = new SpringApplication(ConsumerDebuggingApplication.class); app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); app.run(args); } @Bean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + public SecurityWebFilterChain debuggingConsumerSpringSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange() .anyExchange() .permitAll(); diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerDebuggingApplication.java similarity index 77% rename from spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerSSEApplication.java rename to spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerDebuggingApplication.java index 6b24ee39f0..4fdc1dd137 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerDebuggingApplication.java @@ -11,16 +11,16 @@ import org.springframework.web.reactive.config.EnableWebFlux; @EnableWebFlux @SpringBootApplication -public class ServerSSEApplication { +public class ServerDebuggingApplication { public static void main(String[] args) { - SpringApplication app = new SpringApplication(ServerSSEApplication.class); + SpringApplication app = new SpringApplication(ServerDebuggingApplication.class); app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); app.run(args); } @Bean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + public SecurityWebFilterChain debuggingServerSpringSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange() .anyExchange() .permitAll(); diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java index a1d5d87d5c..9cbc1b7669 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -17,8 +17,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; import org.springframework.core.io.ClassPathResource; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.web.reactive.function.server.RouterFunction; @@ -40,11 +38,14 @@ public class FunctionalSpringBootApplication { private RouterFunction routingFunction() { FormHandler formHandler = new FormHandler(); - RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) - .doOnNext(actors::add) - .then(ok().build())); + RouterFunction restfulRouter = route(GET("/"), + serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), + serverRequest -> serverRequest.bodyToMono(Actor.class) + .doOnNext(actors::add) + .then(ok().build())); - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) + return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) + .andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), restfulRouter) @@ -68,5 +69,4 @@ public class FunctionalSpringBootApplication { public static void main(String[] args) { SpringApplication.run(FunctionalSpringBootApplication.class, args); } - } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java index 1656f70221..a8cd18c470 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java @@ -1,9 +1,7 @@ package com.baeldung.reactive; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; @SpringBootApplication public class Spring5ReactiveApplication{ diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java index d990928abe..69ae24b849 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java @@ -4,6 +4,9 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication public class CorsOnAnnotatedElementsApplication { @@ -14,4 +17,9 @@ public class CorsOnAnnotatedElementsApplication { app.run(args); } + @Bean + public SecurityWebFilterChain corsAnnotatedSpringSecurityFilterChain(ServerHttpSecurity http) { + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java index 8228944569..a70f937980 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java @@ -8,6 +8,9 @@ import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfigurat import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -22,4 +25,9 @@ public class CorsGlobalConfigApplication { app.run(args); } + @Bean + public SecurityWebFilterChain corsGlobalSpringSecurityFilterChain(ServerHttpSecurity http) { + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java similarity index 93% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java index e6e32d7cc8..d2b7af29a6 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java @@ -7,7 +7,7 @@ import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; @Component -public class FunctionalHandler { +public class CorsGlobalFunctionalHandler { public Mono useHandler(final ServerRequest request) { final String responseMessage = "CORS GLOBAL CONFIG IS NOT EFFECTIVE ON FUNCTIONAL ENDPOINTS!!!"; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java index 19621a9e97..0a520828b9 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java @@ -8,13 +8,13 @@ import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; -import com.baeldung.reactive.cors.global.functional.handlers.FunctionalHandler; +import com.baeldung.reactive.cors.global.functional.handlers.CorsGlobalFunctionalHandler; @Configuration public class CorsRouterFunctions { @Bean - public RouterFunction responseHeaderRoute(@Autowired FunctionalHandler handler) { + public RouterFunction corsGlobalRouter(@Autowired CorsGlobalFunctionalHandler handler) { return RouterFunctions.route(RequestPredicates.PUT("/global-config-on-functional/cors-disabled-functional-endpoint"), handler::useHandler); } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java index 38140c0d71..7792975768 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java @@ -8,6 +8,9 @@ import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfigurat import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -21,5 +24,11 @@ public class CorsWebFilterApplication { app.setDefaultProperties(Collections.singletonMap("server.port", "8083")); app.run(args); } + + @Bean + public SecurityWebFilterChain corsWebfilterSpringSecurityFilterChain(ServerHttpSecurity http) { + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java index a3905bb79f..6056b9bf5a 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java @@ -14,7 +14,7 @@ import com.baeldung.reactive.cors.webfilter.functional.handlers.CorsWithWebFilte public class CorsWithWebFilterRouterFunctions { @Bean - public RouterFunction responseHeaderRoute(@Autowired CorsWithWebFilterHandler handler) { + public RouterFunction corsWebfilterRouter(@Autowired CorsWithWebFilterHandler handler) { return RouterFunctions.route(RequestPredicates.PUT("/web-filter-on-functional/functional-endpoint"), handler::useHandler); } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java index 3997607ef0..d8edaf7fd5 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java @@ -4,9 +4,13 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; -@SpringBootApplication +@SpringBootApplication(exclude = { RedisReactiveAutoConfiguration.class }) @EnableAsync public class ConsumerSSEApplication { @@ -15,5 +19,13 @@ public class ConsumerSSEApplication { app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); app.run(args); } + + @Bean + public SecurityWebFilterChain sseConsumerSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java index 2750e6616d..c040b83da0 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java @@ -4,14 +4,26 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; -@SpringBootApplication +@SpringBootApplication(exclude = { RedisReactiveAutoConfiguration.class }) public class ServerSSEApplication { - + public static void main(String[] args) { SpringApplication app = new SpringApplication(ServerSSEApplication.class); app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); app.run(args); } + @Bean + public SecurityWebFilterChain sseServerSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } + } diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java index e548e33c85..4cbb65dc60 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java @@ -2,6 +2,9 @@ package com.baeldung.validations.functional; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication public class FunctionalValidationsApplication { @@ -9,4 +12,13 @@ public class FunctionalValidationsApplication { public static void main(String[] args) { SpringApplication.run(FunctionalValidationsApplication.class, args); } + + @Bean + public SecurityWebFilterChain functionalValidationsSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java index efbdbe3f99..29582a0b0f 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java @@ -17,7 +17,7 @@ import com.baeldung.validations.functional.handlers.impl.OtherEntityValidationHa public class ValidationsRouters { @Bean - public RouterFunction responseHeaderRoute(@Autowired CustomRequestEntityValidationHandler dryHandler, + public RouterFunction validationsRouter(@Autowired CustomRequestEntityValidationHandler dryHandler, @Autowired FunctionalHandler complexHandler, @Autowired OtherEntityValidationHandler otherHandler, @Autowired AnnotatedRequestEntityValidationHandler annotatedEntityHandler) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java b/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java index 452bcac8ab..61927e47ab 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java @@ -34,9 +34,8 @@ public class WebFluxSecurityConfig { } @Bean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http - .authorizeExchange() + public SecurityWebFilterChain webSessionSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() .anyExchange().authenticated() .and() .httpBasic() @@ -44,8 +43,7 @@ public class WebFluxSecurityConfig { .and() .formLogin(); - http - .csrf().disable(); + http.csrf().disable(); return http.build(); diff --git a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index 4dea2a05cf..1256d5f129 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -10,6 +10,7 @@ import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java index 5ebfa39358..b8dd9c9509 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java @@ -1,6 +1,10 @@ package com.baeldung.reactive; -import com.baeldung.web.reactive.Task; +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RequestPredicates.POST; + +import java.time.Duration; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.springframework.http.server.reactive.HttpHandler; @@ -8,22 +12,22 @@ import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.web.reactive.Task; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import reactor.ipc.netty.NettyContext; -import reactor.ipc.netty.http.server.HttpServer; - -import java.time.Duration; - -import static org.springframework.web.reactive.function.server.RequestPredicates.GET; -import static org.springframework.web.reactive.function.server.RequestPredicates.POST; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; public class Spring5ReactiveServerClientIntegrationTest { - private static NettyContext nettyContext; + private static DisposableServer disposableServer; @BeforeAll public static void setUp() throws Exception { - HttpServer server = HttpServer.create("localhost", 8080); + HttpServer server = HttpServer.create() + .host("localhost") + .port(8080); RouterFunction route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok() .body(request.bodyToFlux(Task.class) .map(ll -> new Task("TaskName", 1)), Task.class)) @@ -31,13 +35,13 @@ public class Spring5ReactiveServerClientIntegrationTest { .body(Mono.just("server is alive"), String.class))); HttpHandler httpHandler = RouterFunctions.toHttpHandler(route); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); - nettyContext = server.newHandler(adapter) - .block(); + disposableServer = server.handle(adapter) + .bindNow(); } @AfterAll public static void shutDown() { - nettyContext.dispose(); + disposableServer.disposeNow(); } // @Test diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java index 0043d62e5a..e6847e63da 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.cors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnAnnotatedElementsLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java index 39927af4c3..008f1a16f2 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.cors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnGlobalConfigLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java index e5a3c8a99a..f8a4f34e29 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.cors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnWebFilterLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java index bea2eaa75f..10cfaffce4 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java @@ -8,11 +8,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) +@WithMockUser public class ErrorHandlingIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java index bb2408ea79..fbf46a93cc 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java @@ -4,6 +4,7 @@ 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.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; @@ -12,6 +13,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WithMockUser public class PlayerHandlerIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java index e7d289e5c4..22991b298f 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java @@ -4,6 +4,7 @@ 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.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; @@ -12,6 +13,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WithMockUser public class UserControllerIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java index db563e27d1..927c52e7e6 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.responseheaders; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class ResponseHeaderLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java index 53f4a3b1bb..547cd99034 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java @@ -3,14 +3,13 @@ package com.baeldung.reactive.serversentsevents; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; -@RunWith(JUnitPlatform.class) @SpringBootTest +@WithMockUser public class ServiceSentEventLiveTest { private WebTestClient client = WebTestClient.bindToServer() diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java index 9f31608ff7..d4c1cfe4c8 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java @@ -4,6 +4,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @@ -12,6 +13,7 @@ import com.baeldung.reactive.controller.PathPatternController; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5ReactiveApplication.class) +@WithMockUser public class PathPatternsUsingHandlerMethodIntegrationTest { private static WebTestClient client; diff --git a/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java index 5fe764bf8f..73968cdf05 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java @@ -2,9 +2,7 @@ package com.baeldung.validations.functional; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; @@ -13,7 +11,6 @@ import com.baeldung.validations.functional.model.CustomRequestEntity; import reactor.core.publisher.Mono; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class FunctionalEndpointValidationsLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java index 08bd883b0b..2e37f2ffbd 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java @@ -1,10 +1,10 @@ package com.baeldung.web.client; -import com.baeldung.reactive.Spring5ReactiveApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.server.RequestPredicates; @@ -12,10 +12,14 @@ import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.WebHandler; + +import com.baeldung.reactive.Spring5ReactiveApplication; + import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5ReactiveApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WithMockUser public class WebTestClientIntegrationTest { @LocalServerPort diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index 763e505e51..c26e370381 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -31,7 +31,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 org.springframework diff --git a/spring-5-security/src/main/resources/templatesextrafields/index.html b/spring-5-security/src/main/resources/templatesextrafields/index.html index 37833ff0d2..1dd9c12d42 100644 --- a/spring-5-security/src/main/resources/templatesextrafields/index.html +++ b/spring-5-security/src/main/resources/templatesextrafields/index.html @@ -1,5 +1,5 @@ - + Spring Security with Extra Fields diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 293edb5bda..58c14475e0 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -135,7 +135,8 @@ - + org.apache.maven.plugins maven-surefire-plugin @@ -143,14 +144,6 @@ methods true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - diff --git a/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java index ed163f7fa7..82a5fe083b 100644 --- a/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java +++ b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java @@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfi import org.springframework.context.annotation.ComponentScan; @SpringBootApplication(exclude = SecurityAutoConfiguration.class) -@ComponentScan(basePackages = { "com.baeldung.execption" }) +@ComponentScan(basePackages = { "com.baeldung.exception" }) public class SpringExceptionApplication { public static void main(String[] args) { SpringApplication.run(SpringExceptionApplication.class, args); diff --git a/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java b/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java index 00fce06834..540992b4bc 100644 --- a/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java +++ b/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java @@ -6,12 +6,13 @@ import java.util.Collection; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.JsonbHttpMessageConverter; -@SpringBootApplication +@SpringBootApplication(exclude = SecurityAutoConfiguration.class) @ComponentScan(basePackages = { "com.baeldung.jsonb" }) public class Spring5Application { diff --git a/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java b/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java index 02332ee7b6..f512b52af4 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java @@ -2,8 +2,9 @@ package com.baeldung.restdocs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -@SpringBootApplication +@SpringBootApplication(exclude = SecurityAutoConfiguration.class) public class SpringRestDocsApplication { public static void main(String[] args) { diff --git a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java index ecc677465e..8b9e66213f 100644 --- a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java @@ -3,12 +3,10 @@ package com.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; @RunWith(SpringRunner.class) @SpringBootTest -@EnableJpaRepositories("com.baeldung.persistence") public class Example1IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java index e1d56c2fc3..6ed53ca4e9 100644 --- a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java @@ -3,12 +3,10 @@ package com.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; @RunWith(SpringRunner.class) @SpringBootTest -@EnableJpaRepositories("com.baeldung.persistence") public class Example2IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java index fba01726f4..9c462e0412 100644 --- a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java @@ -1,12 +1,11 @@ package com.baeldung.functional; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; 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.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.support.GenericWebApplicationContext; @@ -14,7 +13,6 @@ import com.baeldung.Spring5Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class) -@EnableJpaRepositories("com.baeldung.persistence") public class BeanRegistrationIntegrationTest { @Autowired diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 2dc4915bab..77c7e74e08 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -155,6 +155,18 @@ org.apache.logging.log4j log4j-core + + + + net.javacrumbs.shedlock + shedlock-spring + 2.1.0 + + + net.javacrumbs.shedlock + shedlock-provider-jdbc-template + 2.1.0 + diff --git a/spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java new file mode 100644 index 0000000000..74ea39683d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java @@ -0,0 +1,12 @@ +package com.baeldung.scheduling.shedlock; + +import org.springframework.context.annotation.Configuration; +import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; +import org.springframework.scheduling.annotation.EnableScheduling; + +@Configuration +@EnableScheduling +@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") +public class SchedulerConfiguration { + +} \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java new file mode 100644 index 0000000000..b1b1ad921f --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java @@ -0,0 +1,15 @@ +package com.baeldung.scheduling.shedlock; + +import net.javacrumbs.shedlock.core.SchedulerLock; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +class TaskScheduler { + + @Scheduled(cron = "*/15 * * * * *") + @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") + public void scheduledTask() { + System.out.println("Running ShedLock task"); + } +} \ No newline at end of file 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 d6fc1836c7..295e0d74c9 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 @@ -47,7 +47,7 @@ public class MySQLAutoconfiguration { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true"); + dataSource.setUrl("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true&&serverTimezone=UTC"); dataSource.setUsername("mysqluser"); dataSource.setPassword("mysqlpass"); diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java similarity index 95% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java rename to spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java index 30ba397b46..df4c1fcd14 100644 --- a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AutoconfigurationApplication.class) @EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) -public class AutoconfigurationIntegrationTest { +public class AutoconfigurationLiveTest { @Autowired private MyUserRepository userRepository; diff --git a/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java similarity index 88% rename from spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java index 136ea2481f..acd4b10ae9 100644 --- a/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung.autoconfiguration; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,7 +11,7 @@ import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = AutoconfigurationApplication.class) @EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) -public class SpringContextIntegrationTest { +public class SpringContextLiveTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index b5bf4bc7b6..7cafc5aa24 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-boot-bootstrap jar spring-boot-bootstrap diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/Application.java b/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java similarity index 78% rename from spring-boot-bootstrap/src/main/java/org/baeldung/Application.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/Application.java index ba1b444e44..567e9b2678 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/Application.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -9,9 +9,9 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @ServletComponentScan @SpringBootApplication -@ComponentScan("org.baeldung") -@EnableJpaRepositories("org.baeldung.persistence.repo") -@EntityScan("org.baeldung.persistence.model") +@ComponentScan("com.baeldung") +@EnableJpaRepositories("com.baeldung.persistence.repo") +@EntityScan("com.baeldung.persistence.model") public class Application { public static void main(String[] args) { diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java b/spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java similarity index 93% rename from spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java index b9f9598ca3..7afc036be5 100755 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.cloud.config; +package com.baeldung.cloud.config; import org.springframework.cloud.config.java.AbstractCloudConfig; import org.springframework.context.annotation.Bean; diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java similarity index 95% rename from spring-boot-bootstrap/src/main/java/org/baeldung/config/SecurityConfig.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java index fd37d2ad54..8e403f3976 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/persistence/model/Book.java b/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java similarity index 98% rename from spring-boot-bootstrap/src/main/java/org/baeldung/persistence/model/Book.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java index 745a1d0460..6be27d4cf0 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/persistence/model/Book.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package com.baeldung.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/persistence/repo/BookRepository.java b/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java similarity index 72% rename from spring-boot-bootstrap/src/main/java/org/baeldung/persistence/repo/BookRepository.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java index 011f3dcb60..cfd0018145 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/persistence/repo/BookRepository.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java @@ -1,8 +1,9 @@ -package org.baeldung.persistence.repo; +package com.baeldung.persistence.repo; -import org.baeldung.persistence.model.Book; import org.springframework.data.repository.CrudRepository; +import com.baeldung.persistence.model.Book; + import java.util.List; import java.util.Optional; diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/BookController.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java similarity index 89% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/BookController.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java index 44129fc7f8..7c86bb833f 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/BookController.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java @@ -1,9 +1,5 @@ -package org.baeldung.web; +package com.baeldung.web; -import org.baeldung.persistence.model.Book; -import org.baeldung.persistence.repo.BookRepository; -import org.baeldung.web.exception.BookIdMismatchException; -import org.baeldung.web.exception.BookNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.CrossOrigin; @@ -17,6 +13,11 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.persistence.model.Book; +import com.baeldung.persistence.repo.BookRepository; +import com.baeldung.web.exception.BookIdMismatchException; +import com.baeldung.web.exception.BookNotFoundException; + import java.util.List; @RestController diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/RestExceptionHandler.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java similarity index 90% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/RestExceptionHandler.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java index cc5b8ee394..dca2e33c52 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/RestExceptionHandler.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java @@ -1,7 +1,5 @@ -package org.baeldung.web; +package com.baeldung.web; -import org.baeldung.web.exception.BookIdMismatchException; -import org.baeldung.web.exception.BookNotFoundException; import org.hibernate.exception.ConstraintViolationException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpHeaders; @@ -12,6 +10,9 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import com.baeldung.web.exception.BookIdMismatchException; +import com.baeldung.web.exception.BookNotFoundException; + @ControllerAdvice public class RestExceptionHandler extends ResponseEntityExceptionHandler { diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/SimpleController.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java similarity index 94% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/SimpleController.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java index 809d6c1094..ee0ba75443 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/SimpleController.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookIdMismatchException.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java similarity index 92% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookIdMismatchException.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java index 23c55e2d38..bafecd59b6 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookIdMismatchException.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.exception; +package com.baeldung.web.exception; public class BookIdMismatchException extends RuntimeException { diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookNotFoundException.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java similarity index 92% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookNotFoundException.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java index 3ff416b3f3..42f49e58a3 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookNotFoundException.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.exception; +package com.baeldung.web.exception; public class BookNotFoundException extends RuntimeException { diff --git a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapIntegrationTest.java b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java similarity index 89% rename from spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapIntegrationTest.java rename to spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java index 8993617d5c..3af7f2104d 100644 --- a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapIntegrationTest.java +++ b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java @@ -1,28 +1,24 @@ -package org.baeldung; +package com.baeldung; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import io.restassured.RestAssured; -import io.restassured.response.Response; import java.util.List; -import org.baeldung.persistence.model.Book; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) -public class SpringBootBootstrapIntegrationTest { +import com.baeldung.persistence.model.Book; - private static final String API_ROOT = "http://localhost:8081/api/books"; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +public class SpringBootBootstrapLiveTest { + + private static final String API_ROOT = "http://localhost:8080/api/books"; @Test public void whenGetAllBooks_thenOK() { diff --git a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 93% rename from spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 9ae417a546..08c6692689 100644 --- a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java index 71fb330663..d423300b85 100644 --- a/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java @@ -10,7 +10,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; -import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; @@ -18,8 +17,7 @@ import org.springframework.test.web.client.MockRestServiceServer; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@RestClientTest(DetailsServiceClient.class) +@RestClientTest({ DetailsServiceClient.class, Application.class }) public class DetailsServiceClientIntegrationTest { @Autowired @@ -34,7 +32,8 @@ public class DetailsServiceClientIntegrationTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")) + .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-boot-disable-console-logging/disabling-console-jul/.gitignore b/spring-boot-disable-console-logging/disabling-console-jul/.gitignore new file mode 100644 index 0000000000..ff56635e49 --- /dev/null +++ b/spring-boot-disable-console-logging/disabling-console-jul/.gitignore @@ -0,0 +1 @@ +baeldung.log diff --git a/spring-boot-disable-console-logging/disabling-console-jul/pom.xml b/spring-boot-disable-console-logging/disabling-console-jul/pom.xml index fbcd0768f9..9ccbd56231 100644 --- a/spring-boot-disable-console-logging/disabling-console-jul/pom.xml +++ b/spring-boot-disable-console-logging/disabling-console-jul/pom.xml @@ -8,7 +8,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.5.RELEASE + 2.1.1.RELEASE diff --git a/spring-boot-disable-console-logging/disabling-console-log4j2/.gitignore b/spring-boot-disable-console-logging/disabling-console-log4j2/.gitignore new file mode 100644 index 0000000000..d3ae44ddfc --- /dev/null +++ b/spring-boot-disable-console-logging/disabling-console-log4j2/.gitignore @@ -0,0 +1 @@ +all.log diff --git a/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml b/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml index 6f3f01669e..0b360bb366 100644 --- a/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml +++ b/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml @@ -8,7 +8,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.5.RELEASE + 2.1.1.RELEASE diff --git a/spring-boot-disable-console-logging/disabling-console-logback/.gitignore b/spring-boot-disable-console-logging/disabling-console-logback/.gitignore new file mode 100644 index 0000000000..4e6aa917ed --- /dev/null +++ b/spring-boot-disable-console-logging/disabling-console-logback/.gitignore @@ -0,0 +1 @@ +disabled-console.log diff --git a/spring-boot-disable-console-logging/disabling-console-logback/pom.xml b/spring-boot-disable-console-logging/disabling-console-logback/pom.xml index fef0a1f4c6..4b64885c66 100644 --- a/spring-boot-disable-console-logging/disabling-console-logback/pom.xml +++ b/spring-boot-disable-console-logging/disabling-console-logback/pom.xml @@ -1,19 +1,22 @@ - - 4.0.0 - disabling-console-logback - disabling-console-logback + + 4.0.0 + disabling-console-logback + disabling-console-logback + + + spring-boot-disable-console-logging + com.baeldung + 0.0.1-SNAPSHOT + ../ + + + + + org.springframework.boot + spring-boot-starter-web + + - - com.baeldung - spring-boot-disable-console-logging - 0.0.1-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java index ab90d8cef2..9ace79c085 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java @@ -3,11 +3,11 @@ package com.baeldung.annotations; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -// @SpringBootApplication + @SpringBootApplication public class VehicleFactoryApplication { -// public static void main(String[] args) { -// SpringApplication.run(VehicleFactoryApplication.class, args); -// } + public static void main(String[] args) { + SpringApplication.run(VehicleFactoryApplication.class, args); + } } diff --git a/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java similarity index 95% rename from spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java rename to spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java index 567b239ed2..7d8accf813 100644 --- a/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java +++ b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java @@ -16,7 +16,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -public class SpringBootMvcApplicationUnitTest { +public class SpringBootMvcApplicationIntegrationTest { @Autowired private MockMvc mockMvc; diff --git a/spring-boot/src/main/resources/templates/customer.html b/spring-boot/src/main/resources/templates/customer.html new file mode 100644 index 0000000000..c8f5a25d5e --- /dev/null +++ b/spring-boot/src/main/resources/templates/customer.html @@ -0,0 +1,16 @@ + + + +Customer Page + + + +
+
+Contact Info:
+ +
+

+
+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/customers.html b/spring-boot/src/main/resources/templates/customers.html new file mode 100644 index 0000000000..5a060d31da --- /dev/null +++ b/spring-boot/src/main/resources/templates/customers.html @@ -0,0 +1,33 @@ + + + + + +
+

+ Hello, --name--. +

+ + + + + + + + + + + + + + + + + +
IDNameAddressService Rendered
Text ...Text ...Text ...Text...
+ +
+ + + diff --git a/spring-boot/src/main/resources/templates/displayallbeans.html b/spring-boot/src/main/resources/templates/displayallbeans.html new file mode 100644 index 0000000000..5fc78a7fca --- /dev/null +++ b/spring-boot/src/main/resources/templates/displayallbeans.html @@ -0,0 +1,10 @@ + + + + Baeldung + + +

+

+ + diff --git a/spring-boot/src/main/resources/templates/error-404.html b/spring-boot/src/main/resources/templates/error-404.html new file mode 100644 index 0000000000..cf68032596 --- /dev/null +++ b/spring-boot/src/main/resources/templates/error-404.html @@ -0,0 +1,14 @@ + + + + + + + +
+
+

Sorry, we couldn't find the page you were looking for.

+

Go Home

+
+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/error-500.html b/spring-boot/src/main/resources/templates/error-500.html new file mode 100644 index 0000000000..5ddf458229 --- /dev/null +++ b/spring-boot/src/main/resources/templates/error-500.html @@ -0,0 +1,16 @@ + + + + + + + +
+
+

Sorry, something went wrong!

+ +

We're fixing it.

+

Go Home

+
+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/error.html b/spring-boot/src/main/resources/templates/error.html new file mode 100644 index 0000000000..bc517913b2 --- /dev/null +++ b/spring-boot/src/main/resources/templates/error.html @@ -0,0 +1,16 @@ + + + + + + + +
+
+

Something went wrong!

+ +

Our Engineers are on it.

+

Go Home

+
+ + diff --git a/spring-boot/src/main/resources/templates/error/404.html b/spring-boot/src/main/resources/templates/error/404.html new file mode 100644 index 0000000000..df83ce219b --- /dev/null +++ b/spring-boot/src/main/resources/templates/error/404.html @@ -0,0 +1,8 @@ + + + RESOURCE NOT FOUND + + +

404 RESOURCE NOT FOUND

+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/external.html b/spring-boot/src/main/resources/templates/external.html new file mode 100644 index 0000000000..2f9cc76961 --- /dev/null +++ b/spring-boot/src/main/resources/templates/external.html @@ -0,0 +1,31 @@ + + + + + +
+
+

Customer Portal

+
+
+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam + erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras + arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit + amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non + id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit + amet varius mauris. Nulla eu eros pharetra, tristique dui quis, + vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec + at leo.

+ +

Existing Customers

+
+ Enter the intranet: customers +
+
+ +
+ + + + diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot/src/main/resources/templates/index.html new file mode 100644 index 0000000000..c1314558f6 --- /dev/null +++ b/spring-boot/src/main/resources/templates/index.html @@ -0,0 +1,19 @@ + + + WebJars Demo + + + +

Welcome Home

+

+
+ × + Success! It is working as we expected. +
+
+ + + + + + diff --git a/spring-boot/src/main/resources/templates/international.html b/spring-boot/src/main/resources/templates/international.html new file mode 100644 index 0000000000..e0cfb5143b --- /dev/null +++ b/spring-boot/src/main/resources/templates/international.html @@ -0,0 +1,20 @@ + + + + +Home + + + + +

+ +

+: + + + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/layout.html b/spring-boot/src/main/resources/templates/layout.html new file mode 100644 index 0000000000..bab0c2982b --- /dev/null +++ b/spring-boot/src/main/resources/templates/layout.html @@ -0,0 +1,18 @@ + + + +Customer Portal + + + + + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/other.html b/spring-boot/src/main/resources/templates/other.html new file mode 100644 index 0000000000..d13373f9fe --- /dev/null +++ b/spring-boot/src/main/resources/templates/other.html @@ -0,0 +1,16 @@ + + + + +Spring Utils Demo + + + + Parameter set by you:

+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/utils.html b/spring-boot/src/main/resources/templates/utils.html new file mode 100644 index 0000000000..93030f424f --- /dev/null +++ b/spring-boot/src/main/resources/templates/utils.html @@ -0,0 +1,23 @@ + + + + +Spring Utils Demo + + + +

+

Set Parameter:

+

+ + +

+
+Another Page + + \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index 44461c0cf6..2785054153 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -1,20 +1,19 @@ package com.baeldung.intro; +import static org.hamcrest.Matchers.equalTo; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; -import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc diff --git a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java index fba816c681..0541da3199 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java @@ -4,12 +4,11 @@ import org.baeldung.demo.DemoApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = DemoApplication.class) -@WebAppConfiguration +@SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class DemoApplicationIntegrationTest { @Test diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java index d76dbfc803..a4b35889d6 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java @@ -22,13 +22,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = DemoApplication.class) -@AutoConfigureMockMvc +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) +@AutoConfigureMockMvc // @TestPropertySource(locations = "classpath:application-integrationtest.properties") @AutoConfigureTestDatabase public class EmployeeRestControllerIntegrationTest { diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml index 779a4a803a..392244dc84 100644 --- a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml @@ -16,12 +16,12 @@ 0.0.1-SNAPSHOT ../../../parent-boot-2 - + UTF-8 UTF-8 1.8 - Finchley.SR1 + Greenwich.M3 @@ -70,5 +70,16 @@
+ + + spring-milestones + Spring Milestones + http://repo.spring.io/milestone + + false + + + + diff --git a/spring-cloud-data-flow/etl/customer-transform/pom.xml b/spring-cloud-data-flow/etl/customer-transform/pom.xml index c344b0fc57..0e429cb593 100644 --- a/spring-cloud-data-flow/etl/customer-transform/pom.xml +++ b/spring-cloud-data-flow/etl/customer-transform/pom.xml @@ -22,7 +22,7 @@ UTF-8 UTF-8 1.8 - Finchley.SR1 + Greenwich.M3 @@ -63,5 +63,15 @@ + + + spring-milestones + Spring Milestones + http://repo.spring.io/milestone + + false + + + diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 28db4a7a3d..39cda888c5 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -35,7 +35,7 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault - spring-cloud-security + spring-cloud-task spring-cloud-zuul diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile b/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile new file mode 100644 index 0000000000..0fc0a9bd64 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile @@ -0,0 +1,11 @@ +FROM openjdk:8-jdk-alpine + +# Create app directory +RUN mkdir -p /usr/opt/service + +# Copy app +COPY target/*.jar /usr/opt/service/service.jar + +EXPOSE 8080 + +ENTRYPOINT exec java -jar /usr/opt/service/service.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml new file mode 100644 index 0000000000..e963dafe67 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml @@ -0,0 +1,51 @@ + + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.17.RELEASE + + + + 4.0.0 + + liveness-example + 1.0-SNAPSHOT + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java new file mode 100644 index 0000000000..2cfa242965 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.liveness; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java new file mode 100644 index 0000000000..715c4cb178 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java @@ -0,0 +1,27 @@ +package com.baeldung.liveness.health; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +@Component +public class CustomHealthIndicator implements HealthIndicator { + + private boolean isHealthy = true; + + public CustomHealthIndicator() { + ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor(); + scheduled.schedule(() -> { + isHealthy = false; + }, 30, TimeUnit.SECONDS); + } + + @Override + public Health health() { + return isHealthy ? Health.up().build() : Health.down().build(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties new file mode 100644 index 0000000000..a3ac65cee5 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties @@ -0,0 +1 @@ +server.port=8080 \ No newline at end of file diff --git a/persistence-modules/spring-hibernate3/src/main/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml similarity index 100% rename from persistence-modules/spring-hibernate3/src/main/resources/logback.xml rename to spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml diff --git a/persistence-modules/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 54% rename from persistence-modules/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java index f48199d4e8..60b4a28aa6 100644 --- a/persistence-modules/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,17 +1,17 @@ -package org.baeldung; +package com.baeldung; +import com.baeldung.liveness.Application; 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) +@SpringBootTest(classes = Application.class) public class SpringContextIntegrationTest { - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } + @Test + public void contextLoads() { + } + } diff --git a/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml b/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml new file mode 100644 index 0000000000..9fd3fd5674 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml @@ -0,0 +1,54 @@ +apiVersion: v1 +kind: Service +metadata: + name: liveness-example +spec: + selector: + app: liveness-example + ports: + - port: 8080 + +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: liveness-example +spec: + selector: + matchLabels: + app: liveness-example + replicas: 1 + strategy: + rollingUpdate: + maxUnavailable: 0 + template: + metadata: + labels: + app: liveness-example + spec: + containers: + - name: liveness-example + image: dbdock/liveness-example:1.0.0 + imagePullPolicy: IfNotPresent + resources: + requests: + memory: 400Mi + cpu: 400m + ports: + - containerPort: 8080 + readinessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 10 + timeoutSeconds: 2 + periodSeconds: 3 + failureThreshold: 1 + livenessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 20 + timeoutSeconds: 2 + periodSeconds: 8 + failureThreshold: 1 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml b/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml new file mode 100644 index 0000000000..010c468107 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml @@ -0,0 +1,54 @@ +apiVersion: v1 +kind: Service +metadata: + name: readiness-example +spec: + selector: + app: readiness-example + ports: + - port: 8080 + +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: readiness-example +spec: + selector: + matchLabels: + app: readiness-example + replicas: 1 + strategy: + rollingUpdate: + maxUnavailable: 0 + template: + metadata: + labels: + app: readiness-example + spec: + containers: + - name: readiness-example + image: dbdock/readiness-example:1.0.0 + imagePullPolicy: IfNotPresent + resources: + requests: + memory: 400Mi + cpu: 400m + ports: + - containerPort: 8080 + readinessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 40 + timeoutSeconds: 2 + periodSeconds: 3 + failureThreshold: 5 + livenessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 100 + timeoutSeconds: 2 + periodSeconds: 8 + failureThreshold: 1 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml index 984b3811dd..de0718633e 100644 --- a/spring-cloud/spring-cloud-kubernetes/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/pom.xml @@ -11,6 +11,8 @@ demo-frontend demo-backend + liveness-example + readiness-example diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile b/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile new file mode 100644 index 0000000000..0fc0a9bd64 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile @@ -0,0 +1,11 @@ +FROM openjdk:8-jdk-alpine + +# Create app directory +RUN mkdir -p /usr/opt/service + +# Copy app +COPY target/*.jar /usr/opt/service/service.jar + +EXPOSE 8080 + +ENTRYPOINT exec java -jar /usr/opt/service/service.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml new file mode 100644 index 0000000000..fa85120d21 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml @@ -0,0 +1,49 @@ + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.17.RELEASE + + + 4.0.0 + + readiness-example + 1.0-SNAPSHOT + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java new file mode 100644 index 0000000000..11ffe577c3 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.readiness; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java new file mode 100644 index 0000000000..d37a1905f6 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java @@ -0,0 +1,27 @@ +package com.baeldung.readiness.health; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +@Component +public class CustomHealthIndicator implements HealthIndicator { + + private boolean isHealthy = false; + + public CustomHealthIndicator() { + ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor(); + scheduled.schedule(() -> { + isHealthy = true; + }, 40, TimeUnit.SECONDS); + } + + @Override + public Health health() { + return isHealthy ? Health.up().build() : Health.down().build(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties new file mode 100644 index 0000000000..a3ac65cee5 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties @@ -0,0 +1 @@ +server.port=8080 \ No newline at end of file diff --git a/spring-5-reactive-functional/src/main/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml similarity index 100% rename from spring-5-reactive-functional/src/main/resources/logback.xml rename to spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..18458182c7 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.readiness.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 contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index 340c276c2d..5d15c6c726 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -5,8 +5,8 @@ auth-client jar auth-client - Spring Cloud Security APP Client Module - + Spring Cloud Security APP Client Module + spring-cloud-security com.baeldung @@ -61,6 +61,10 @@ org.springframework.boot spring-boot-starter-thymeleaf + + org.springframework.security.oauth + spring-security-oauth2 + diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index 09474b2a4d..0367baa990 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 auth-resource @@ -14,16 +14,16 @@ com.baeldung 1.0.0-SNAPSHOT - + + + org.springframework.boot + spring-boot-starter-web + org.springframework.security.oauth spring-security-oauth2 - - org.springframework.cloud - spring-cloud-starter-security - org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml index 68b8e44875..3a7198ecc3 100644 --- a/spring-cloud/spring-cloud-vault/pom.xml +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -24,7 +24,7 @@ UTF-8 UTF-8 1.8 - Finchley.SR1 + Greenwich.M3 @@ -82,6 +82,17 @@ + + + + spring-milestones + Spring Milestones + http://repo.spring.io/milestone + + false + + + diff --git a/spring-mvc-forms-thymeleaf/pom.xml b/spring-mvc-forms-thymeleaf/pom.xml index 504ad1dcb2..67a2696c8a 100644 --- a/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-mvc-forms-thymeleaf/pom.xml @@ -9,10 +9,10 @@ spring forms examples using thymeleaf - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 5240ae24e7..22ddabb4ea 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -8,10 +8,10 @@ war - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index 70fea91f31..6f790f1f48 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml index 540b3d08eb..8b7ce1770d 100644 --- a/spring-rest-shell/pom.xml +++ b/spring-rest-shell/pom.xml @@ -8,10 +8,10 @@ A simple project to demonstrate Spring REST Shell features. - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index d301957eb9..e5de463999 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -8,10 +8,10 @@ war - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-rest-template/pom.xml b/spring-rest-template/pom.xml index fa93308cf5..d86e208987 100644 --- a/spring-rest-template/pom.xml +++ b/spring-rest-template/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index ba74d26c35..ea4cfc26d7 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp @@ -183,9 +183,6 @@ org.springframework.boot spring-boot-maven-plugin - - true - org.apache.maven.plugins @@ -300,6 +297,7 @@ 2.2.0 3.5.11 3.1.0 + com.baeldung.sampleapp.config.MainApplication diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java similarity index 90% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java index baaa4c4d80..1967d4f2aa 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.lists; +package com.baeldung.resttemplate.lists; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java index 729fa3ca3e..d811045733 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -1,11 +1,12 @@ -package org.baeldung.resttemplate.lists.client; +package com.baeldung.resttemplate.lists.client; -import org.baeldung.resttemplate.lists.dto.Employee; -import org.baeldung.resttemplate.lists.dto.EmployeeList; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; +import com.baeldung.resttemplate.lists.dto.Employee; +import com.baeldung.resttemplate.lists.dto.EmployeeList; + import java.util.ArrayList; import java.util.List; diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java index f051c6a78b..8a4d510f63 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java @@ -1,14 +1,15 @@ -package org.baeldung.resttemplate.lists.controller; +package com.baeldung.resttemplate.lists.controller; -import org.baeldung.resttemplate.lists.dto.Employee; -import org.baeldung.resttemplate.lists.dto.EmployeeList; -import org.baeldung.resttemplate.lists.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.resttemplate.lists.dto.Employee; +import com.baeldung.resttemplate.lists.dto.EmployeeList; +import com.baeldung.resttemplate.lists.service.EmployeeService; + import java.util.List; @RestController diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java similarity index 92% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java index bd8ebbf969..0754c13c5b 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.lists.dto; +package com.baeldung.resttemplate.lists.dto; public class Employee { diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java similarity index 91% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java index 2bb86ac5b4..eeabbfe450 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.lists.dto; +package com.baeldung.resttemplate.lists.dto; import java.util.ArrayList; import java.util.List; diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java similarity index 83% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java index 08196dda77..226134787f 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java @@ -1,8 +1,9 @@ -package org.baeldung.resttemplate.lists.service; +package com.baeldung.resttemplate.lists.service; -import org.baeldung.resttemplate.lists.dto.Employee; import org.springframework.stereotype.Service; +import com.baeldung.resttemplate.lists.dto.Employee; + import java.util.ArrayList; import java.util.List; diff --git a/spring-rest/src/main/java/org/baeldung/config/MainApplication.java b/spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/config/MainApplication.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java index 6a7fdc041a..507f340e9d 100644 --- a/spring-rest/src/main/java/org/baeldung/config/MainApplication.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.sampleapp.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @EnableAutoConfiguration -@ComponentScan("org.baeldung") +@ComponentScan("com.baeldung.sampleapp") public class MainApplication implements WebMvcConfigurer { public static void main(final String[] args) { diff --git a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java b/spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java index 8743af20fe..8abc368bdb 100644 --- a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java @@ -1,15 +1,16 @@ -package org.baeldung.config; +package com.baeldung.sampleapp.config; import java.util.ArrayList; import java.util.List; -import org.baeldung.interceptors.RestTemplateHeaderModifierInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.util.CollectionUtils; import org.springframework.web.client.RestTemplate; +import com.baeldung.sampleapp.interceptors.RestTemplateHeaderModifierInterceptor; + @Configuration public class RestClientConfig { diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java similarity index 95% rename from spring-rest/src/main/java/org/baeldung/config/WebConfig.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java index b3e3cd179a..d5209a520b 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.sampleapp.config; import java.text.SimpleDateFormat; import java.util.List; @@ -18,7 +18,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; */ @Configuration @EnableWebMvc -@ComponentScan({ "org.baeldung.web" }) +@ComponentScan({ "com.baeldung.sampleapp.web" }) public class WebConfig implements WebMvcConfigurer { public WebConfig() { diff --git a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java b/spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java similarity index 91% rename from spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java index fabb904634..519e5ebf0d 100644 --- a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.interceptors; +package com.baeldung.sampleapp.interceptors; import java.io.IOException; diff --git a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java b/spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java similarity index 72% rename from spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java index e4eb6d8875..ea9541c31a 100644 --- a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java @@ -1,10 +1,10 @@ -package org.baeldung.repository; - -import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressOnly; +package com.baeldung.sampleapp.repository; import java.util.Map; +import com.baeldung.sampleapp.web.dto.HeavyResource; +import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly; + public class HeavyResourceRepository { public void save(HeavyResource heavyResource) { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java similarity index 96% rename from spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java index 1c3a1086ca..c6b8d23944 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java similarity index 82% rename from spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java index aa694c08ed..bfda2fe0d6 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java @@ -1,10 +1,11 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; -import org.baeldung.web.dto.Company; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.Company; + @RestController public class CompanyController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/DeferredResultController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java similarity index 98% rename from spring-rest/src/main/java/org/baeldung/web/controller/DeferredResultController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java index 5d039d2d02..8f4eb3218a 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/DeferredResultController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java similarity index 88% rename from spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java index fed45066bd..8156fc14a9 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java @@ -1,11 +1,8 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.Map; -import org.baeldung.repository.HeavyResourceRepository; -import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressOnly; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -14,6 +11,10 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.repository.HeavyResourceRepository; +import com.baeldung.sampleapp.web.dto.HeavyResource; +import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly; + @RestController public class HeavyResourceController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java similarity index 83% rename from spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java index 1cc3eae432..69bd458968 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java @@ -1,14 +1,14 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.Date; -import org.baeldung.web.dto.Item; -import org.baeldung.web.dto.ItemManager; -import org.baeldung.web.dto.Views; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.Item; +import com.baeldung.sampleapp.web.dto.ItemManager; +import com.baeldung.sampleapp.web.dto.Views; import com.fasterxml.jackson.annotation.JsonView; @RestController diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java index 251e0b23e7..11ea5b70c9 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.Collection; import java.util.HashMap; @@ -6,8 +6,6 @@ import java.util.Map; import javax.servlet.http.HttpServletResponse; -import org.baeldung.web.dto.Foo; -import org.baeldung.web.exception.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -18,6 +16,9 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import com.baeldung.sampleapp.web.dto.Foo; +import com.baeldung.sampleapp.web.exception.ResourceNotFoundException; + @Controller @RequestMapping(value = "/foos") public class MyFooController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/PactController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java similarity index 90% rename from spring-rest/src/main/java/org/baeldung/web/controller/PactController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java index 4f586479ef..0f5d7f1acb 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/PactController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java @@ -1,9 +1,8 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.ArrayList; import java.util.List; -import org.baeldung.web.dto.PactDto; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -12,6 +11,8 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.PactDto; + @RestController public class PactController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/SimplePostController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java similarity index 97% rename from spring-rest/src/main/java/org/baeldung/web/controller/SimplePostController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java index f8407acb47..7b57d35088 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/SimplePostController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.io.BufferedOutputStream; import java.io.File; @@ -7,7 +7,6 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; -import org.baeldung.web.dto.Foo; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -15,6 +14,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; +import com.baeldung.sampleapp.web.dto.Foo; + // used to test HttpClientPostingTest @RestController public class SimplePostController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java index 996f229128..853e417d46 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.advice; +package com.baeldung.sampleapp.web.controller.advice; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java index a0a6c6341e..fc73bade87 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java @@ -1,13 +1,14 @@ -package org.baeldung.web.controller.mediatypes; +package com.baeldung.sampleapp.web.controller.mediatypes; -import org.baeldung.web.dto.BaeldungItem; -import org.baeldung.web.dto.BaeldungItemV2; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.BaeldungItem; +import com.baeldung.sampleapp.web.dto.BaeldungItemV2; + @RestController @RequestMapping(value = "/", produces = "application/vnd.baeldung.api.v1+json") public class CustomMediaTypeController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java similarity index 98% rename from spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java index 59868593a3..321f3be3ef 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.redirect; +package com.baeldung.sampleapp.web.controller.redirect; import javax.servlet.http.HttpServletRequest; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItem.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java similarity index 83% rename from spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItem.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java index 9b3ecd33b9..807a254cfc 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItem.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class BaeldungItem { private final String itemId; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItemV2.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java similarity index 84% rename from spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItemV2.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java index 64df20a14e..f84591ea43 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItemV2.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class BaeldungItemV2 { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/Company.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java index 3164d604ad..6cfcc079d9 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class Company { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/web/dto/Foo.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java index 240b368b50..186df8e678 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResource.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java similarity index 96% rename from spring-rest/src/main/java/org/baeldung/web/dto/HeavyResource.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java index 934e76606f..2821341888 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResource.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class HeavyResource { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java index f96347d60c..01ee6e7dd4 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class HeavyResourceAddressOnly { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressPartialUpdate.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressPartialUpdate.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java index f90f02ea08..1832a1a58b 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressPartialUpdate.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class HeavyResourceAddressPartialUpdate { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Item.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/web/dto/Item.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java index 536c72020f..a4fcef5dce 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Item.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; import com.fasterxml.jackson.annotation.JsonView; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/ItemManager.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java similarity index 80% rename from spring-rest/src/main/java/org/baeldung/web/dto/ItemManager.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java index 74ffada300..0009c0180b 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/ItemManager.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class ItemManager { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/PactDto.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/PactDto.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java index e34e2bdf3b..e184119611 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/PactDto.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class PactDto { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Views.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java similarity index 75% rename from spring-rest/src/main/java/org/baeldung/web/dto/Views.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java index 6231e12bcc..e2d83fda22 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Views.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class Views { public static class Public { diff --git a/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java similarity index 82% rename from spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java index aab737b6ec..69532f196d 100644 --- a/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.exception; +package com.baeldung.sampleapp.web.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml index 7e7d820836..ddb9c91792 100644 --- a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -6,7 +6,7 @@ http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd" > - + diff --git a/spring-rest/src/main/webapp/WEB-INF/web.xml b/spring-rest/src/main/webapp/WEB-INF/web.xml index 1b8b767ae3..20a11f3422 100644 --- a/spring-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest/src/main/webapp/WEB-INF/web.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.config + com.baeldung.sampleapp.config