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/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java similarity index 98% rename from java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java index 688bf43b3c..b3d142eb07 100644 --- a/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.algorithms.string; import java.util.HashSet; import java.util.Set; diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java similarity index 98% rename from java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java index b18a8d4a5f..8d225f67fa 100644 --- a/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.algorithms.string; import static org.junit.Assert.assertEquals; import java.util.HashSet; 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/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java index 0deb48b6a0..945b4ffd7e 100644 --- a/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java @@ -34,7 +34,7 @@ public class MergeSort { while (i < left && j < right) { - if (l[i] < r[j]) + if (l[i] <= r[j]) a[k++] = l[i++]; else a[k++] = r[j++]; diff --git a/core-java-11/src/main/java/com/baeldung/add b/core-java-11/src/main/java/com/baeldung/add new file mode 100755 index 0000000000..539c1a43d4 --- /dev/null +++ b/core-java-11/src/main/java/com/baeldung/add @@ -0,0 +1,12 @@ +#!/usr/local/bin/java --source 11 + +import java.util.Arrays; + +public class Addition +{ + public static void main(String[] args) { + System.out.println(Arrays.stream(args) + .mapToInt(Integer::parseInt) + .sum()); + } +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java new file mode 100644 index 0000000000..d84182aec6 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java @@ -0,0 +1,5 @@ +package com.baeldung.interfaces.multiinheritance; + +public abstract interface Fly{ + void fly(); +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java new file mode 100644 index 0000000000..a18bbafdc1 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java @@ -0,0 +1,5 @@ +package com.baeldung.interfaces.multiinheritance; + +public interface Transform { + void transform(); +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java new file mode 100644 index 0000000000..fb0d36e3e0 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java @@ -0,0 +1,13 @@ +package com.baeldung.interfaces.multiinheritance; + +public class Vehicle implements Fly, Transform { + @Override + public void fly() { + System.out.println("I can Fly!!"); + } + + @Override + public void transform() { + System.out.println("I can Transform!!"); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java new file mode 100644 index 0000000000..bf0e613567 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java @@ -0,0 +1,21 @@ +package com.baeldung.interfaces.polymorphysim; + +public class Circle implements Shape { + + private double radius; + + public Circle(double radius){ + this.radius = radius; + } + + @Override + public String name() { + return "Circle"; + } + + @Override + public double area() { + return Math.PI * (radius * radius); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java new file mode 100644 index 0000000000..2cf4fafee1 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java @@ -0,0 +1,22 @@ +package com.baeldung.interfaces.polymorphysim; + +import java.util.ArrayList; + +public class DisplayShape { + + private ArrayList shapes; + + public DisplayShape() { + shapes = new ArrayList<>(); + } + + public void add(Shape shape) { + shapes.add(shape); + } + + public void display() { + for (Shape shape : shapes) { + System.out.println(shape.name() + " area: " + shape.area()); + } + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java new file mode 100644 index 0000000000..cc43c1300b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java @@ -0,0 +1,15 @@ +package com.baeldung.interfaces.polymorphysim; + +public class MainPolymorphic { + public static void main(String[] args){ + + Shape circleShape = new Circle(2); + Shape squareShape = new Square(2); + + DisplayShape displayShape = new DisplayShape(); + displayShape.add(circleShape); + displayShape.add(squareShape); + + displayShape.display(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java new file mode 100644 index 0000000000..fcb0c65e7b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java @@ -0,0 +1,6 @@ +package com.baeldung.interfaces.polymorphysim; + +public interface Shape { + public abstract String name(); + public abstract double area(); +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java new file mode 100644 index 0000000000..9c440150b5 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java @@ -0,0 +1,20 @@ +package com.baeldung.interfaces.polymorphysim; + +public class Square implements Shape { + + private double width; + + public Square(double width) { + this.width = width; + } + + @Override + public String name() { + return "Square"; + } + + @Override + public double area() { + return width * width; + } +} diff --git a/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java b/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java new file mode 100644 index 0000000000..7ded5e6621 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.interfaces; + +import com.baeldung.interfaces.polymorphysim.Circle; +import com.baeldung.interfaces.polymorphysim.Shape; +import com.baeldung.interfaces.polymorphysim.Square; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +public class PolymorphysimUnitTest { + + @Test + public void whenInterfacePointsToCircle_CircleAreaMethodisBeingCalled(){ + double expectedArea = 12.566370614359172; + Shape circle = new Circle(2); + double actualArea = circle.area(); + Assertions.assertThat(actualArea).isEqualTo(expectedArea); + } + + @Test + public void whenInterfacePointsToSquare_SquareAreaMethodisBeingCalled(){ + double expectedArea = 4; + Shape square = new Square(2); + double actualArea = square.area(); + Assertions.assertThat(actualArea).isEqualTo(expectedArea); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java b/core-java-collections/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java new file mode 100644 index 0000000000..72045d6761 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java @@ -0,0 +1,37 @@ +package com.baeldung.list.multidimensional; + +import java.util.ArrayList; + +public class ArrayListOfArrayList { + + public static void main(String args[]) { + + int vertex = 5; + ArrayList> graph = new ArrayList<>(vertex); + + //Initializing each element of ArrayList with ArrayList + for(int i=0; i< vertex; i++) { + graph.add(new ArrayList()); + } + + //We can add any number of columns to each row + graph.get(0).add(1); + graph.get(0).add(5); + graph.get(1).add(0); + graph.get(1).add(2); + graph.get(2).add(1); + graph.get(2).add(3); + graph.get(3).add(2); + graph.get(3).add(4); + graph.get(4).add(3); + graph.get(4).add(5); + + //Printing all the edges + for(int i=0; i > > space = new ArrayList<>(x_axis_length); + + //Initializing each element of ArrayList with ArrayList< ArrayList > + for(int i=0; i< x_axis_length; i++) { + space.add(new ArrayList< ArrayList >(y_axis_length)); + for(int j =0; j< y_axis_length; j++) { + space.get(i).add(new ArrayList(z_axis_length)); + } + } + + //Set Red color for points (0,0,0) and (0,0,1) + space.get(0).get(0).add("Red"); + space.get(0).get(0).add("Red"); + //Set Blue color for points (0,1,0) and (0,1,1) + space.get(0).get(1).add("Blue"); + space.get(0).get(1).add("Blue"); + //Set Green color for points (1,0,0) and (1,0,1) + space.get(1).get(0).add("Green"); + space.get(1).get(0).add("Green"); + //Set Yellow color for points (1,1,0) and (1,1,1) + space.get(1).get(1).add("Yellow"); + space.get(1).get(1).add("Yellow"); + + //Printing colors for all the points + for(int i=0; i 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/pom.xml b/core-kotlin/pom.xml index ed79ebc01b..8b871f28ee 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -72,6 +72,17 @@ injekt-core 1.16.1 + + uy.kohesive.kovert + kovert-vertx + [1.5.0,1.6.0) + + + nl.komponents.kovenant + kovenant + + + diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt new file mode 100644 index 0000000000..da2bbe4208 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt @@ -0,0 +1,73 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.core.HttpVerb +import uy.kohesive.kovert.core.Location +import uy.kohesive.kovert.core.Verb +import uy.kohesive.kovert.core.VerbAlias +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class AnnotatedServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(AnnotatedServer::class.java) + + @JvmStatic + fun main(args: Array) { + AnnotatedServer().start() + } + } + + @VerbAlias("show", HttpVerb.GET) + class AnnotatedController { + fun RoutingContext.showStringById(id: String) = id + + @Verb(HttpVerb.GET) + @Location("/ping/:id") + fun RoutingContext.ping(id: String) = id + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", AnnotatedServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(AnnotatedController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt new file mode 100644 index 0000000000..a596391ed8 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt @@ -0,0 +1,75 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.core.HttpErrorCode +import uy.kohesive.kovert.core.HttpErrorCodeWithBody +import uy.kohesive.kovert.core.HttpErrorForbidden +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class ErrorServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(ErrorServer::class.java) + + @JvmStatic + fun main(args: Array) { + ErrorServer().start() + } + } + + class ErrorController { + fun RoutingContext.getForbidden() { + throw HttpErrorForbidden() + } + fun RoutingContext.getError() { + throw HttpErrorCode("Something went wrong", 590) + } + fun RoutingContext.getErrorbody() { + throw HttpErrorCodeWithBody("Something went wrong", 591, "Body here") + } + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", ErrorServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(ErrorController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt new file mode 100644 index 0000000000..310fe2a7a0 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt @@ -0,0 +1,76 @@ +package com.baeldung.kovert + +import com.fasterxml.jackson.annotation.JsonProperty +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + +class JsonServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(JsonServer::class.java) + + @JvmStatic + fun main(args: Array) { + JsonServer().start() + } + } + + data class Person( + @JsonProperty("_id") + val id: String, + val name: String, + val job: String + ) + + class JsonController { + fun RoutingContext.getPersonById(id: String) = Person( + id = id, + name = "Tony Stark", + job = "Iron Man" + ) + fun RoutingContext.putPersonById(id: String, person: Person) = person + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", JsonServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(JsonController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt new file mode 100644 index 0000000000..98ce775e66 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt @@ -0,0 +1,57 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + +class NoopServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(NoopServer::class.java) + + @JvmStatic + fun main(args: Array) { + NoopServer().start() + } + } + + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", NoopServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt new file mode 100644 index 0000000000..86ca482808 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt @@ -0,0 +1,68 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class SecuredServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(SecuredServer::class.java) + + @JvmStatic + fun main(args: Array) { + SecuredServer().start() + } + } + + class SecuredContext(private val routingContext: RoutingContext) { + val authenticated = routingContext.request().getHeader("Authorization") == "Secure" + } + + class SecuredController { + fun SecuredContext.getSecured() = this.authenticated + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SecuredServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(SecuredController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt new file mode 100644 index 0000000000..172469ab46 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt @@ -0,0 +1,65 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class SimpleServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(SimpleServer::class.java) + + @JvmStatic + fun main(args: Array) { + SimpleServer().start() + } + } + + class SimpleController { + fun RoutingContext.getStringById(id: String) = id + fun RoutingContext.get_truncatedString_by_id(id: String, length: Int = 1) = id.subSequence(0, length) + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SimpleServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(SimpleController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/resources/kovert.conf b/core-kotlin/src/main/resources/kovert.conf new file mode 100644 index 0000000000..3b08641693 --- /dev/null +++ b/core-kotlin/src/main/resources/kovert.conf @@ -0,0 +1,15 @@ +{ + kovert: { + vertx: { + clustered: false + } + server: { + listeners: [ + { + host: "0.0.0.0" + port: "8000" + } + ] + } + } +} diff --git a/deeplearning4j/README.md b/deeplearning4j/README.md index 7f9c92ec73..14e585cd97 100644 --- a/deeplearning4j/README.md +++ b/deeplearning4j/README.md @@ -2,4 +2,4 @@ This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library. ### Relevant Articles: -- [A Guide to deeplearning4j](http://www.baeldung.com/deeplearning4j) +- [A Guide to Deeplearning4j](http://www.baeldung.com/deeplearning4j) diff --git a/flips/README.md b/flips/README.md deleted file mode 100644 index 0c62173b6a..0000000000 --- a/flips/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/) diff --git a/flips/pom.xml b/flips/pom.xml deleted file mode 100644 index 75dc8bb579..0000000000 --- a/flips/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - 4.0.0 - flips - flips - 0.0.1-SNAPSHOT - jar - flips - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-web - ${spring-boot-starter-web.version} - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot-starter-test.version} - - - com.github.feature-flip - flips-web - ${flips-web.version} - - - org.projectlombok - lombok - - ${lombok.version} - provided - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - - - - - 1.5.10.RELEASE - 1.5.9.RELEASE - 1.0.1 - 1.16.18 - - - diff --git a/flips/src/main/java/com/baeldung/flips/ApplicationConfig.java b/flips/src/main/java/com/baeldung/flips/ApplicationConfig.java deleted file mode 100644 index 7001aeb991..0000000000 --- a/flips/src/main/java/com/baeldung/flips/ApplicationConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.flips; - -import org.flips.describe.config.FlipWebContextConfiguration; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Import; - -@SpringBootApplication -@Import(FlipWebContextConfiguration.class) -public class ApplicationConfig { - - public static void main(String[] args) { - SpringApplication.run(ApplicationConfig.class, args); - } -} \ No newline at end of file diff --git a/flips/src/main/java/com/baeldung/flips/controller/FlipController.java b/flips/src/main/java/com/baeldung/flips/controller/FlipController.java deleted file mode 100644 index 50458023b3..0000000000 --- a/flips/src/main/java/com/baeldung/flips/controller/FlipController.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.flips.controller; - -import com.baeldung.flips.model.Foo; -import com.baeldung.flips.service.FlipService; -import org.flips.annotation.FlipOnDateTime; -import org.flips.annotation.FlipOnDaysOfWeek; -import org.flips.annotation.FlipOnEnvironmentProperty; -import org.flips.annotation.FlipOnProfiles; -import org.springframework.beans.factory.annotation.Autowired; -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.RestController; - -import java.time.DayOfWeek; -import java.util.List; - -@RestController -public class FlipController { - - private FlipService flipService; - - @Autowired - public FlipController(FlipService flipService) { - this.flipService = flipService; - } - - @RequestMapping(value = "/foos", method = RequestMethod.GET) - @FlipOnProfiles(activeProfiles = "dev") - public List getAllFoos() { - return flipService.getAllFoos(); - } - - @RequestMapping(value = "/foo/{id}", method = RequestMethod.GET) - @FlipOnDaysOfWeek(daysOfWeek = { - DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, - DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY - }) - public Foo getFooByNewId(@PathVariable int id) { - return flipService.getFooById(id).orElse(new Foo("Not Found", -1)); - } - - @RequestMapping(value = "/foo/last", method = RequestMethod.GET) - @FlipOnDateTime(cutoffDateTimeProperty = "last.active.after") - public Foo getLastFoo() { - return flipService.getLastFoo(); - } - - @RequestMapping(value = "/foo/first", method = RequestMethod.GET) - @FlipOnDateTime(cutoffDateTimeProperty = "first.active.after") - public Foo getFirstFoo() { - return flipService.getLastFoo(); - } - - @RequestMapping(value = "/foos/{id}", method = RequestMethod.GET) - @FlipOnEnvironmentProperty(property = "feature.foo.by.id", expectedValue = "Y") - public Foo getFooById(@PathVariable int id) { - return flipService.getFooById(id).orElse(new Foo("Not Found", -1)); - } - - @RequestMapping(value = "/foo/new", method = RequestMethod.GET) - public Foo getNewThing() { - return flipService.getNewFoo(); - } -} \ No newline at end of file diff --git a/flips/src/main/java/com/baeldung/flips/model/Foo.java b/flips/src/main/java/com/baeldung/flips/model/Foo.java deleted file mode 100644 index be15bee15c..0000000000 --- a/flips/src/main/java/com/baeldung/flips/model/Foo.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.flips.model; - -import lombok.Data; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; - -@Data -@RequiredArgsConstructor -public class Foo { - @NonNull private final String name; - @NonNull private final int id; -} diff --git a/flips/src/main/java/com/baeldung/flips/service/FlipService.java b/flips/src/main/java/com/baeldung/flips/service/FlipService.java deleted file mode 100644 index 9f7fb325a5..0000000000 --- a/flips/src/main/java/com/baeldung/flips/service/FlipService.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.flips.service; - -import com.baeldung.flips.model.Foo; -import org.flips.annotation.FlipBean; -import org.flips.annotation.FlipOnSpringExpression; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -@Service -public class FlipService { - - private final List foos; - - public FlipService() { - foos = new ArrayList<>(); - foos.add(new Foo("Foo1", 1)); - foos.add(new Foo("Foo2", 2)); - foos.add(new Foo("Foo3", 3)); - foos.add(new Foo("Foo4", 4)); - foos.add(new Foo("Foo5", 5)); - foos.add(new Foo("Foo6", 6)); - - } - - public List getAllFoos() { - return foos; - } - - public Optional getFooById(int id) { - return foos.stream().filter(foo -> (foo.getId() == id)).findFirst(); - } - - @FlipBean(with = NewFlipService.class) - @FlipOnSpringExpression(expression = "(2 + 2) == 4") - public Foo getNewFoo() { - return new Foo("New Foo!", 99); - } - - public Foo getLastFoo() { - return foos.get(foos.size() - 1); - } - - public Foo getFirstFoo() { - return foos.get(0); - } - -} \ No newline at end of file diff --git a/flips/src/main/java/com/baeldung/flips/service/NewFlipService.java b/flips/src/main/java/com/baeldung/flips/service/NewFlipService.java deleted file mode 100644 index 1dcda9b6ca..0000000000 --- a/flips/src/main/java/com/baeldung/flips/service/NewFlipService.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.flips.service; - -import com.baeldung.flips.model.Foo; -import org.springframework.stereotype.Service; - -@Service -public class NewFlipService { - - public Foo getNewFoo() { - return new Foo("Shiny New Foo!", 100); - } - -} \ No newline at end of file diff --git a/flips/src/main/resources/application.properties b/flips/src/main/resources/application.properties deleted file mode 100644 index 274896be15..0000000000 --- a/flips/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -feature.foo.by.id=Y -feature.new.foo=Y -last.active.after=2018-03-14T00:00:00Z -first.active.after=2999-03-15T00:00:00Z -logging.level.org.flips=info \ No newline at end of file diff --git a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java deleted file mode 100644 index 9dd4ef064a..0000000000 --- a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.flips.controller; - -import org.hamcrest.Matchers; -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.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; - -@RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "feature.foo.by.id=Y", - "feature.new.foo=Y", - "last.active.after=2018-03-14T00:00:00Z", - "first.active.after=2999-03-15T00:00:00Z", - "logging.level.org.flips=info" - -}, webEnvironment = SpringBootTest.WebEnvironment.MOCK) -@AutoConfigureMockMvc -@ActiveProfiles("dev") -public class FlipControllerIntegrationTest { - - @Autowired private MockMvc mvc; - - @Test - public void givenValidDayOfWeek_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/1")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void givenValidDate_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/last")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo6"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(6))); - } - - @Test - public void givenInvalidDate_APINotAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/first")) - .andExpect(MockMvcResultMatchers.status().is(501)); - } - - @Test - public void givenCorrectProfile_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(6))); - } - - @Test - public void givenPropertySet_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos/1")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void getValidExpression_FlipBean() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/new")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Shiny New Foo!"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(100))); - } -} \ No newline at end of file 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-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java index 92da22cc95..1234a700de 100644 --- a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java @@ -8,6 +8,7 @@ import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; +import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.Locale; import java.util.TimeZone; @@ -51,6 +52,16 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } + @Test + public void givenTwoDateTimesInJava8_whenDifferentiatingInSeconds_thenWeGetTen() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime tenSecondsLater = now.plusSeconds(10); + + long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater); + + assertEquals(diff, 10); + } + @Test public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() { LocalDateTime ldt = LocalDateTime.now(); @@ -60,6 +71,16 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } + @Test + public void givenTwoDateTimesInJava8_whenDifferentiatingInSecondsUsingUntil_thenWeGetTen() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime tenSecondsLater = now.plusSeconds(10); + + long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS); + + assertEquals(diff, 10); + } + @Test public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() { org.joda.time.LocalDate now = org.joda.time.LocalDate.now(); 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/test/java/com/baeldung/ConvertStringToListUnitTest.java b/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java new file mode 100644 index 0000000000..47357a99cc --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java @@ -0,0 +1,135 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import com.google.common.base.Function; +import com.google.common.base.Splitter; +import com.google.common.collect.Lists; + +public class ConvertStringToListUnitTest { + + private final String countries = "Russia,Germany,England,France,Italy"; + private final String ranks = "1,2,3,4,5, 6,7"; + private final String emptyStrings = ",,,,,"; + private final List expectedCountriesList = Arrays.asList("Russia", "Germany", "England", "France", "Italy"); + private final List expectedRanksList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + private final List expectedEmptyStringsList = Arrays.asList("", "", "", "", "", ""); + + @Test + public void givenString_thenGetListOfStringByJava() { + List convertedCountriesList = Arrays.asList(countries.split(",", -1)); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfStringByApache() { + List convertedCountriesList = Arrays.asList(StringUtils.splitPreserveAllTokens(countries, ",")); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfStringByGuava() { + List convertedCountriesList = Splitter.on(",") + .trimResults() + .splitToList(countries); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfStringByJava8() { + List convertedCountriesList = Stream.of(countries.split(",", -1)) + .collect(Collectors.toList()); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfIntegerByJava() { + String[] convertedRankArray = ranks.split(","); + List convertedRankList = new ArrayList(); + for (String number : convertedRankArray) { + convertedRankList.add(Integer.parseInt(number.trim())); + } + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenString_thenGetListOfIntegerByGuava() { + List convertedRankList = Lists.transform(Splitter.on(",") + .trimResults() + .splitToList(ranks), new Function() { + @Override + public Integer apply(String input) { + return Integer.parseInt(input.trim()); + } + }); + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenString_thenGetListOfIntegerByJava8() { + List convertedRankList = Stream.of(ranks.split(",")) + .map(String::trim) + .map(Integer::parseInt) + .collect(Collectors.toList()); + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenString_thenGetListOfIntegerByApache() { + String[] convertedRankArray = StringUtils.split(ranks, ","); + List convertedRankList = new ArrayList(); + for (String number : convertedRankArray) { + convertedRankList.add(Integer.parseInt(number.trim())); + } + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByJava() { + List convertedEmptyStringsList = Arrays.asList(emptyStrings.split(",", -1)); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByApache() { + List convertedEmptyStringsList = Arrays.asList(StringUtils.splitPreserveAllTokens(emptyStrings, ",")); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByGuava() { + List convertedEmptyStringsList = Splitter.on(",") + .trimResults() + .splitToList(emptyStrings); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByJava8() { + List convertedEmptyStringsList = Stream.of(emptyStrings.split(",", -1)) + .collect(Collectors.toList()); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + +} diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index d321e9e81e..a2c267b74d 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,7 +1,5 @@ ### Relevant articles -- [Intro to JHipster](http://www.baeldung.com/jhipster) - # baeldung This application was generated using JHipster 4.0.8, you can find documentation and help at [https://jhipster.github.io/documentation-archive/v4.0.8](https://jhipster.github.io/documentation-archive/v4.0.8). 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 eb0bc58225..16d79a59b1 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -658,6 +658,12 @@ ${suanshu.version} + + org.derive4j + derive4j + ${derive4j.version} + true + @@ -881,6 +887,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/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java index aa06ba4eb9..97ead07470 100644 --- a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java +++ b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.fj; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -30,7 +32,7 @@ public class FunctionalJavaUnitTest { List fList1 = fList.map(timesTwo); List fList2 = fList.map(i -> i * 2); - assertEquals(fList1.equals(fList2), true); + assertTrue(fList1.equals(fList2)); } @Test @@ -41,7 +43,7 @@ public class FunctionalJavaUnitTest { List fList2 = fList.map(plusOne).map(timesTwo); Show.listShow(Show.intShow).println(fList2); - assertEquals(fList1.equals(fList2), false); + assertFalse(fList1.equals(fList2)); } @Test @@ -49,10 +51,8 @@ public class FunctionalJavaUnitTest { List fList = List.list(3, 4, 5, 6); List evenList = fList.map(isEven); List evenListTrueResult = List.list(false, true, false, true); - List evenListFalseResult = List.list(true, false, false, true); - assertEquals(evenList.equals(evenListTrueResult), true); - assertEquals(evenList.equals(evenListFalseResult), false); + assertTrue(evenList.equals(evenListTrueResult)); } @Test @@ -60,10 +60,8 @@ public class FunctionalJavaUnitTest { List fList = List.list(3, 4, 5, 6); fList = fList.map(i -> i + 100); List resultList = List.list(103, 104, 105, 106); - List falseResultList = List.list(15, 504, 105, 106); - assertEquals(fList.equals(resultList), true); - assertEquals(fList.equals(falseResultList), false); + assertTrue(fList.equals(resultList)); } @Test @@ -71,23 +69,19 @@ public class FunctionalJavaUnitTest { Array array = Array.array(3, 4, 5, 6); Array filteredArray = array.filter(isEven); Array result = Array.array(4, 6); - Array wrongResult = Array.array(3, 5); - assertEquals(filteredArray.equals(result), true); - assertEquals(filteredArray.equals(wrongResult), false); + assertTrue(filteredArray.equals(result)); } @Test public void checkForLowerCase_givenStringArray_returnResult() { Array array = Array.array("Welcome", "To", "baeldung"); + assertTrue(array.exists(s -> List.fromString(s).forall(Characters.isLowerCase))); + Array array2 = Array.array("Welcome", "To", "Baeldung"); - Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); - Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); - Boolean isAll = array.forall(s -> List.fromString(s).forall(Characters.isLowerCase)); - - assertEquals(isExist, true); - assertEquals(isExist2, false); - assertEquals(isAll, false); + assertFalse(array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase))); + + assertFalse(array.forall(s -> List.fromString(s).forall(Characters.isLowerCase))); } @Test @@ -102,9 +96,9 @@ public class FunctionalJavaUnitTest { Option result2 = n2.bind(function); Option result3 = n3.bind(function); - assertEquals(result1, Option.none()); - assertEquals(result2, Option.some(102)); - assertEquals(result3, Option.none()); + assertEquals(Option.none(), result1); + assertEquals(Option.some(102), result2); + assertEquals(Option.none(), result3); } @Test @@ -112,11 +106,11 @@ public class FunctionalJavaUnitTest { Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); int sumAll = intArray.foldLeft(Integers.add, 0); - assertEquals(sumAll, 260); + assertEquals(260, sumAll); int sumEven = intArray.filter(isEven).foldLeft(Integers.add, 0); - assertEquals(sumEven, 148); + assertEquals(148, sumEven); } - + } diff --git a/parent-boot-2.0-temp/README.md b/parent-boot-2.0-temp/README.md deleted file mode 100644 index 8134c8eafe..0000000000 --- a/parent-boot-2.0-temp/README.md +++ /dev/null @@ -1,2 +0,0 @@ -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 deleted file mode 100644 index 9284e4af13..0000000000 --- a/parent-boot-2.0-temp/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - 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/persistence-modules/hibernate-ogm/README.md b/persistence-modules/hibernate-ogm/README.md new file mode 100644 index 0000000000..f4a5bb6c3b --- /dev/null +++ b/persistence-modules/hibernate-ogm/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [Guide to Hibernate OGM](http://www.baeldung.com/xxxx) + diff --git a/persistence-modules/hibernate-ogm/pom.xml b/persistence-modules/hibernate-ogm/pom.xml new file mode 100644 index 0000000000..2ccac03bd3 --- /dev/null +++ b/persistence-modules/hibernate-ogm/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + com.baeldung + hibernate-ogm + 0.0.1-SNAPSHOT + hibernate-ogm + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + + org.hibernate.ogm + hibernate-ogm-mongodb + 5.4.0.Final + + + + org.hibernate.ogm + hibernate-ogm-neo4j + 5.4.0.Final + + + + org.jboss.narayana.jta + narayana-jta + 5.5.23.Final + + + + junit + junit + 4.12 + test + + + org.easytesting + fest-assert + 1.4 + test + + + + + hibernate-ogm + + + src/main/resources + true + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java new file mode 100644 index 0000000000..29f01ecde7 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java @@ -0,0 +1,54 @@ +package com.baeldung.hibernate.ogm; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Article { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String articleId; + + private String articleTitle; + + @ManyToOne + private Author author; + + // constructors, getters and setters... + + Article() { + } + + public Article(String articleTitle) { + this.articleTitle = articleTitle; + } + + public String getArticleId() { + return articleId; + } + + public void setArticleId(String articleId) { + this.articleId = articleId; + } + + public String getArticleTitle() { + return articleTitle; + } + + public void setArticleTitle(String articleTitle) { + this.articleTitle = articleTitle; + } + + public Author getAuthor() { + return author; + } + + public void setAuthor(Author author) { + this.author = author; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java new file mode 100644 index 0000000000..9e60c9f934 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java @@ -0,0 +1,70 @@ +package com.baeldung.hibernate.ogm; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Author { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String authorId; + + private String authorName; + + @ManyToOne + private Editor editor; + + @OneToMany(mappedBy = "author", cascade = CascadeType.PERSIST) + private Set
authoredArticles = new HashSet<>(); + + // constructors, getters and setters... + + Author() { + } + + public Author(String authorName) { + this.authorName = authorName; + } + + public String getAuthorId() { + return authorId; + } + + public void setAuthorId(String authorId) { + this.authorId = authorId; + } + + public String getAuthorName() { + return authorName; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public Editor getEditor() { + return editor; + } + + public void setEditor(Editor editor) { + this.editor = editor; + } + + public Set
getAuthoredArticles() { + return authoredArticles; + } + + public void setAuthoredArticles(Set
authoredArticles) { + this.authoredArticles = authoredArticles; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java new file mode 100644 index 0000000000..2c3f720e91 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.ogm; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Editor { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String editorId; + + private String editorName; + + @OneToMany(mappedBy = "editor", cascade = CascadeType.PERSIST) + private Set assignedAuthors = new HashSet<>(); + + // constructors, getters and setters... + + Editor() { + } + + public Editor(String editorName) { + this.editorName = editorName; + } + + public String getEditorId() { + return editorId; + } + + public void setEditorId(String editorId) { + this.editorId = editorId; + } + + public String getEditorName() { + return editorName; + } + + public void setEditorName(String editorName) { + this.editorName = editorName; + } + + public Set getAssignedAuthors() { + return assignedAuthors; + } + + public void setAssignedAuthors(Set assignedAuthors) { + this.assignedAuthors = assignedAuthors; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..43c86fb55b --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,24 @@ + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java new file mode 100644 index 0000000000..d7fd49d917 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.hibernate.ogm; + +import static org.fest.assertions.Assertions.assertThat; + +import java.util.Map; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.transaction.TransactionManager; + +import org.junit.Test; + +public class EditorUnitTest { + /* + @Test + public void givenMongoDB_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-mongodb"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + */ + @Test + public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + + private void persistTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + entityManager.persist(editor); + entityManager.close(); + transactionManager.commit(); + } + + private void loadAndVerifyTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + Editor loadedEditor = entityManager.find(Editor.class, editor.getEditorId()); + assertThat(loadedEditor).isNotNull(); + assertThat(loadedEditor.getEditorName()).isEqualTo("Tom"); + assertThat(loadedEditor.getAssignedAuthors()).onProperty("authorName") + .containsOnly("Maria", "Mike"); + Map loadedAuthors = loadedEditor.getAssignedAuthors() + .stream() + .collect(Collectors.toMap(Author::getAuthorName, e -> e)); + assertThat(loadedAuthors.get("Maria") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Basic of Hibernate OGM"); + assertThat(loadedAuthors.get("Mike") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Intermediate of Hibernate OGM", "Advanced of Hibernate OGM"); + entityManager.close(); + transactionManager.commit(); + } + + private Editor generateTestData() { + Editor tom = new Editor("Tom"); + Author maria = new Author("Maria"); + Author mike = new Author("Mike"); + Article basic = new Article("Basic of Hibernate OGM"); + Article intermediate = new Article("Intermediate of Hibernate OGM"); + Article advanced = new Article("Advanced of Hibernate OGM"); + maria.getAuthoredArticles() + .add(basic); + basic.setAuthor(maria); + mike.getAuthoredArticles() + .add(intermediate); + intermediate.setAuthor(mike); + mike.getAuthoredArticles() + .add(advanced); + advanced.setAuthor(mike); + tom.getAssignedAuthors() + .add(maria); + maria.setEditor(tom); + tom.getAssignedAuthors() + .add(mike); + mike.setEditor(tom); + return tom; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 363e2153b6..f5a3a7e4c9 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -36,6 +36,11 @@ hibernate-spatial ${hibernate.version} + + org.hibernate + hibernate-c3p0 + ${hibernate.version} + mysql mysql-connector-java @@ -51,6 +56,16 @@ hibernate-testing 5.2.2.Final + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + net.bytebuddy + byte-buddy + 1.9.5 + @@ -69,6 +84,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/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties new file mode 100644 index 0000000000..2cf8ac5b63 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties @@ -0,0 +1,7 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +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/hibernate5/src/test/resources/hibernate.properties b/persistence-modules/hibernate5/src/test/resources/hibernate.properties index 7b8764637b..c14782ce0f 100644 --- a/persistence-modules/hibernate5/src/test/resources/hibernate.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate.properties @@ -6,4 +6,9 @@ jdbc.password= hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/java-jdbi/README.md b/persistence-modules/java-jdbi/README.md index 3bab6faa29..7d843af9ea 100644 --- a/persistence-modules/java-jdbi/README.md +++ b/persistence-modules/java-jdbi/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java) 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/redis/README.md b/persistence-modules/redis/README.md index dd655ca7aa..21cd048693 100644 --- a/persistence-modules/redis/README.md +++ b/persistence-modules/redis/README.md @@ -1,5 +1,4 @@ ### Relevant Articles: - [Intro to Jedis – the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library) - [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson) -- [Intro to Lettuce – the Java Redis Client Library](http://www.baeldung.com/lettuce-java-redis-client-library) - +- [Introduction to Lettuce – the Java Redis Client](https://www.baeldung.com/java-redis-lettuce) diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java old mode 100644 new mode 100755 index 7044d57e53..1f9f5f9195 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java @@ -1,8 +1,13 @@ package com.baeldung.dao.repositories.product; import com.baeldung.domain.product.Product; -import org.springframework.data.jpa.repository.JpaRepository; -public interface ProductRepository extends JpaRepository { +import java.util.List; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; + +public interface ProductRepository extends PagingAndSortingRepository { + + List findAllByPrice(double price, Pageable pageable); } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java old mode 100644 new mode 100755 index 42e6dd8f45..2f82e3e318 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java @@ -19,6 +19,17 @@ public class Product { super(); } + private Product(int id, String name, double price) { + super(); + this.id = id; + this.name = name; + this.price = price; + } + + public static Product from(int id, String name, double price) { + return new Product(id, name, price); + } + public int getId() { return id; } @@ -46,7 +57,11 @@ public class Product { @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append("Product [name=").append(name).append(", id=").append(id).append("]"); + builder.append("Product [name=") + .append(name) + .append(", id=") + .append(id) + .append("]"); return builder.toString(); } } diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4caa0f0ca4 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java @@ -0,0 +1,142 @@ +package com.baeldung.dao.repositories.product; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.domain.product.Product; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { PersistenceProductConfiguration.class }) +@EnableTransactionManagement +public class ProductRepositoryIntegrationTest { + + @Autowired + private ProductRepository productRepository; + + @Before + @Transactional("productTransactionManager") + public void setUp() { + productRepository.save(Product.from(1001, "Book", 21)); + productRepository.save(Product.from(1002, "Coffee", 10)); + productRepository.save(Product.from(1003, "Jeans", 30)); + productRepository.save(Product.from(1004, "Shirt", 32)); + productRepository.save(Product.from(1005, "Bacon", 10)); + } + + @Test + public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { + Pageable pageRequest = PageRequest.of(0, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1001, 1002) + .contains(id))); + } + + @Test + public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { + Pageable pageRequest = PageRequest.of(1, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1003, 1004) + .contains(id))); + } + + @Test + public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { + Pageable pageRequest = PageRequest.of(2, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(1)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1005) + .contains(id))); + } + + @Test + public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(3)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); + + } + + @Test + public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") + .descending()); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(3)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); + + } + + @Test + public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price") + .descending() + .and(Sort.by("name"))); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(5)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); + + } + + @Test + public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { + Pageable pageRequest = PageRequest.of(0, 2); + + List result = productRepository.findAllByPrice(10, pageRequest); + + assertThat(result, hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1002, 1005) + .contains(id))); + } +} diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index b4d73708c3..75d23f7532 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -1,6 +1,6 @@ ### Relevant articles -- [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable) +- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) - [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many) - [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions) - [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) diff --git a/pom.xml b/pom.xml index 44a844b6ee..57487f00cc 100644 --- a/pom.xml +++ b/pom.xml @@ -324,170 +324,239 @@ 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 + 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 + 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-apache-commons + 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/hibernate-ogm + persistence-modules/influxdb + persistence-modules/java-cassandra + persistence-modules/java-cockroachdb persistence-modules/java-jdbi - persistence-modules/redis + persistence-modules/java-jpa + 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-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 + + + rule-engines/easy-rules + rule-engines/openl-tablets + rule-engines/rulebook + rsocket + rxjava + rxjava-2 + @@ -521,104 +590,124 @@ 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-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 @@ -626,8 +715,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 @@ -636,65 +727,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 @@ -844,7 +943,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 @@ -855,6 +954,62 @@ + + 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-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + core-java + core-java-concurrency + core-kotlin + + jenkins/hello-world + jhipster + jws + + libraries + + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql + + spring-5-data-reactive + spring-amqp-simple + + vaadin + + + integration-lite-first @@ -880,171 +1035,240 @@ 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 + 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 + 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-apache-commons + 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/hibernate-ogm + persistence-modules/influxdb + persistence-modules/java-cassandra + persistence-modules/java-cockroachdb persistence-modules/java-jdbi - persistence-modules/redis + persistence-modules/java-jpa + 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-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 + + + rule-engines/easy-rules + rule-engines/openl-tablets + rule-engines/rulebook + rsocket + rxjava + rxjava-2 + + @@ -1073,104 +1297,124 @@ 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-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 @@ -1178,8 +1422,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 @@ -1188,65 +1434,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 @@ -1277,13 +1531,30 @@ 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 + jhipster + jws + + libraries + + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/java-mongodb + 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..a67078db06 --- /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<>(DATA_LENGTH); + float velocity = 0; + for (int i = 0; i < 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..085f9874fa --- /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(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..42243da39f --- /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.DataPublisher; +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 DataPublisher dataPublisher = new DataPublisher(); + 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() { + dataPublisher.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 { + dataPublisher.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 measurement data + */ + @Override + public Flux requestStream(Payload payload) { + String streamName = payload.getDataUtf8(); + if (DATA_STREAM_NAME.equals(streamName)) { + return Flux.from(dataPublisher); + } + 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..4ffc4f6483 --- /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 DATA_LENGTH = 30; + String DATA_STREAM_NAME = "data"; + int SHOT_COUNT = 10; +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java b/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java new file mode 100644 index 0000000000..3e74da8317 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.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 DataPublisher 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/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/flips/src/main/resources/logback.xml b/rsocket/src/main/resources/logback.xml similarity index 100% rename from flips/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/README.md b/rxjava-2/README.md index f9528bb1d5..d0bdeec684 100644 --- a/rxjava-2/README.md +++ b/rxjava-2/README.md @@ -6,3 +6,4 @@ - [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) - [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) - [Combining RxJava Completables](https://www.baeldung.com/rxjava-completable) +- [Converting Synchronous and Asynchronous APIs to Observables using RxJava2](https://www.baeldung.com/rxjava-apis-to-observables) diff --git a/spring-4/README.md b/spring-4/README.md index 4600a603ef..402557eb41 100644 --- a/spring-4/README.md +++ b/spring-4/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: -- [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/) - [A Guide to Flips for Spring](http://www.baeldung.com/flips-spring) - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index ab64d1e2fa..63cc185afe 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -143,7 +143,7 @@ 1.0 1.0 4.1 - 3.1.6.RELEASE + 3.2.3.RELEASE diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java new file mode 100644 index 0000000000..17fea6b50b --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import java.time.Duration; + +public class PostExecutionUnitTest { + + Flux source = Flux.create(emitter -> { + emitter.next(1); + emitter.next(2); + emitter.next(3); + emitter.complete(); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + emitter.next(4); + }).filter(number -> number % 2 == 0); + + @Test + public void droppedElements() { + StepVerifier.create(source) + .expectNext(2) + .expectComplete() + .verifyThenAssertThat() + .hasDropped(4) + .tookLessThan(Duration.ofMillis(1050)); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java new file mode 100644 index 0000000000..c7196d6b6c --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +public class StepByStepUnitTest { + + Flux source = Flux.just("John", "Monica", "Mark", "Cloe", "Frank", "Casper", "Olivia", "Emily", "Cate") + .filter(name -> name.length() == 4) + .map(String::toUpperCase); + + @Test + public void shouldReturnForLettersUpperCaseStrings() { + StepVerifier + .create(source) + .expectNext("JOHN") + .expectNextMatches(name -> name.startsWith("MA")) + .expectNext("CLOE", "CATE") + .expectComplete() + .verify(); + } + + @Test + public void shouldThrowExceptionAfterFourElements() { + Flux error = source.concatWith( + Mono.error(new IllegalArgumentException("Our message")) + ); + + StepVerifier + .create(error) + .expectNextCount(4) + .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && + throwable.getMessage().equals("Our message") + ).verify(); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java new file mode 100644 index 0000000000..fb65e2d315 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; +import reactor.test.publisher.TestPublisher; + +public class TestingTestPublisherUnitTest { + + @Test + public void testPublisher() { + TestPublisher + .create() + .next("First", "Second", "Third") + .error(new RuntimeException("Message")); + } + + @Test + public void nonCompliant() { + TestPublisher + .createNoncompliant(TestPublisher.Violation.ALLOW_NULL) + .emit("1", "2", null, "3"); + } + + @Test + public void testPublisherInAction() { + final TestPublisher testPublisher = TestPublisher.create(); + + UppercaseConverter uppercaseConverter = new UppercaseConverter(testPublisher.flux()); + + StepVerifier.create(uppercaseConverter.getUpperCase()) + .then(() -> testPublisher.emit("aA", "bb", "ccc")) + .expectNext("AA", "BB", "CCC") + .verifyComplete(); + } + +} + +class UppercaseConverter { + private final Flux source; + + UppercaseConverter(Flux source) { + this.source = source; + } + + Flux getUpperCase() { + return source + .map(String::toUpperCase); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java new file mode 100644 index 0000000000..54e5e7882a --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import java.time.Duration; + +public class TimeBasedUnitTest { + + @Test + public void simpleExample() { + StepVerifier + .withVirtualTime(() -> Flux.interval(Duration.ofSeconds(1)).take(2)) + .expectSubscription() + .expectNoEvent(Duration.ofSeconds(1)) + .expectNext(0L) + .thenAwait(Duration.ofSeconds(1)) + .expectNext(1L) + .verifyComplete(); + } +} 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/pom.xml b/spring-boot-autoconfiguration/pom.xml index 87418bd2c7..1c3d8796ed 100644 --- a/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-autoconfiguration/pom.xml @@ -9,10 +9,10 @@ This is simple boot application demonstrating a custom auto-configuration - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 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 4b0abd5f2e..7cafc5aa24 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -2,16 +2,16 @@ 4.0.0 - org.baeldung + com.baeldung spring-boot-bootstrap jar spring-boot-bootstrap Demo project for Spring Boot - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 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 91% 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/pom.xml b/spring-boot-client/pom.xml index 282488c4b1..fc89931f79 100644 --- a/spring-boot-client/pom.xml +++ b/spring-boot-client/pom.xml @@ -9,10 +9,10 @@ This is simple boot client application for Spring boot actuator test - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 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-ctx-fluent/pom.xml b/spring-boot-ctx-fluent/pom.xml index 52139fec3c..b238374612 100644 --- a/spring-boot-ctx-fluent/pom.xml +++ b/spring-boot-ctx-fluent/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 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-disable-console-logging/pom.xml b/spring-boot-disable-console-logging/pom.xml index c8c43ada7a..63ed129347 100644 --- a/spring-boot-disable-console-logging/pom.xml +++ b/spring-boot-disable-console-logging/pom.xml @@ -7,10 +7,10 @@ Projects for Disabling Spring Boot Console Logging tutorials - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-boot-jasypt/pom.xml b/spring-boot-jasypt/pom.xml index a1707b45b0..de0df92678 100644 --- a/spring-boot-jasypt/pom.xml +++ b/spring-boot-jasypt/pom.xml @@ -10,10 +10,10 @@ Demo project for Spring Boot - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index 8191645d76..b219e53431 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -8,10 +8,10 @@ Module For Spring Boot MVC - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 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-ops/pom.xml b/spring-boot-ops/pom.xml index 760fc69462..9717a352d3 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -9,10 +9,10 @@ Demo project for Spring Boot - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -86,6 +86,12 @@ ${jquery.version} + + org.springframework.cloud + spring-cloud-context + ${springcloud.version} + + @@ -153,6 +159,7 @@ 2.2 18.0 3.1.7 + 2.0.2.RELEASE diff --git a/spring-boot-ops/src/main/java/com/baeldung/restart/Application.java b/spring-boot-ops/src/main/java/com/baeldung/restart/Application.java new file mode 100644 index 0000000000..a6605a0baa --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/restart/Application.java @@ -0,0 +1,30 @@ +package com.baeldung.restart; + +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.ConfigurableApplicationContext; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + private static ConfigurableApplicationContext context; + + public static void main(String[] args) { + context = SpringApplication.run(Application.class, args); + } + + public static void restart() { + ApplicationArguments args = context.getBean(ApplicationArguments.class); + + Thread thread = new Thread(() -> { + context.close(); + context = SpringApplication.run(Application.class, args.getSourceArgs()); + }); + + thread.setDaemon(false); + thread.start(); + } + +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java new file mode 100644 index 0000000000..68a8dc7073 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java @@ -0,0 +1,23 @@ +package com.baeldung.restart; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RestartController { + + @Autowired + private RestartService restartService; + + @PostMapping("/restart") + public void restart() { + Application.restart(); + } + + @PostMapping("/restartApp") + public void restartUsingActuator() { + restartService.restartApp(); + } + +} diff --git a/spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java new file mode 100644 index 0000000000..9883ec653b --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java @@ -0,0 +1,17 @@ +package com.baeldung.restart; + +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.context.restart.RestartEndpoint; + +@Service +public class RestartService { + + @Autowired + private RestartEndpoint restartEndpoint; + + public void restartApp() { + restartEndpoint.restart(); + } + +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/resources/application.properties b/spring-boot-ops/src/main/resources/application.properties index a86bd3052e..27b7915cff 100644 --- a/spring-boot-ops/src/main/resources/application.properties +++ b/spring-boot-ops/src/main/resources/application.properties @@ -1,3 +1,7 @@ management.endpoints.web.exposure.include=* management.metrics.enable.root=true -management.metrics.enable.jvm=true \ No newline at end of file +management.metrics.enable.jvm=true +management.endpoint.restart.enabled=true +spring.datasource.jmx-enabled=false +spring.main.allow-bean-definition-overriding=true +management.endpoint.shutdown.enabled=true \ No newline at end of file diff --git a/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java new file mode 100644 index 0000000000..14e80c3ac7 --- /dev/null +++ b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.restart; + +import static org.junit.Assert.assertEquals; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; + +import java.time.Duration; + +public class RestartApplicationIntegrationTest { + + private TestRestTemplate restTemplate = new TestRestTemplate(); + + @Test + public void givenBootApp_whenRestart_thenOk() throws Exception { + Application.main(new String[0]); + + ResponseEntity response = restTemplate.exchange("http://localhost:8080/restart", + HttpMethod.POST, null, Object.class); + + assertEquals(200, response.getStatusCode().value()); + } + + @Test + public void givenBootApp_whenRestartUsingActuator_thenOk() throws Exception { + Application.main(new String[] { "--server.port=8090" }); + + ResponseEntity response = restTemplate.exchange("http://localhost:8090/restartApp", + HttpMethod.POST, null, Object.class); + + assertEquals(200, response.getStatusCode().value()); + } + +} \ No newline at end of file diff --git a/spring-boot-ops/src/test/resources/application.properties b/spring-boot-ops/src/test/resources/application.properties index 2095a82a14..cf0f0ab74c 100644 --- a/spring-boot-ops/src/test/resources/application.properties +++ b/spring-boot-ops/src/test/resources/application.properties @@ -4,4 +4,9 @@ spring.mail.properties.mail.smtp.auth=false management.endpoints.web.exposure.include=* management.endpoint.shutdown.enabled=true -endpoints.shutdown.enabled=true \ No newline at end of file +endpoints.shutdown.enabled=true + +management.endpoint.restart.enabled=true + +spring.main.allow-bean-definition-overriding=true +spring.jmx.unique-names=true \ No newline at end of file diff --git a/spring-boot-vue/pom.xml b/spring-boot-vue/pom.xml index 919f3e0ff9..d581b11d68 100644 --- a/spring-boot-vue/pom.xml +++ b/spring-boot-vue/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot Vue project - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 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/pom.xml b/spring-boot/pom.xml index 40caf4fb97..87c782b044 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -8,10 +8,10 @@ This is simple boot application for Spring boot actuator test - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 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 10071727f7..392244dc84 100644 --- a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml @@ -11,17 +11,17 @@ Example ETL Load Project - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-2.0-temp + ../../../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 a181020e77..0e429cb593 100644 --- a/spring-cloud-data-flow/etl/customer-transform/pom.xml +++ b/spring-cloud-data-flow/etl/customer-transform/pom.xml @@ -12,17 +12,17 @@ Example transform ETL step - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-2.0-temp + ../../../parent-boot-2 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/spring-rest-template/src/main/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml similarity index 100% rename from spring-rest-template/src/main/resources/logback.xml rename to spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..60b4a28aa6 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @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-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file 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 a19d7f3459..3a7198ecc3 100644 --- a/spring-cloud/spring-cloud-vault/pom.xml +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -12,9 +12,9 @@ com.baeldung - parent-boot-2.0-temp + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-2.0-temp + ../../parent-boot-2 - - org.springframework - spring-web - - - commons-logging - commons-logging - - - - - - - spring-rest-template - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - - check - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*LiveTest.java - - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - - - - - 3.0.0 - - diff --git a/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java b/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java deleted file mode 100644 index 804013d4dc..0000000000 --- a/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.web.upload.client; - -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.RestTemplate; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -public class MultipartFileUploadClient { - - public static void main(String[] args) throws IOException { - uploadSingleFile(); - uploadMultipleFile(); - } - - private static void uploadSingleFile() throws IOException { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - MultiValueMap body = new LinkedMultiValueMap<>(); - body.add("file", getTestFile()); - - - HttpEntity> requestEntity = new HttpEntity<>(body, headers); - String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/"; - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); - System.out.println("Response code: " + response.getStatusCode()); - } - - private static void uploadMultipleFile() throws IOException { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - MultiValueMap body = new LinkedMultiValueMap<>(); - body.add("files", getTestFile()); - body.add("files", getTestFile()); - body.add("files", getTestFile()); - - HttpEntity> requestEntity = new HttpEntity<>(body, headers); - String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/"; - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); - System.out.println("Response code: " + response.getStatusCode()); - } - - public static Resource getTestFile() throws IOException { - Path testFile = Files.createTempFile("test-file", ".txt"); - System.out.println("Creating and Uploading Test File: " + testFile); - Files.write(testFile, "Hello World !!, This is a test file.".getBytes()); - return new FileSystemResource(testFile.toFile()); - } - -} diff --git a/spring-rest/README.md b/spring-rest/README.md index 5b8a35a4a5..efa0dbab60 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -24,3 +24,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list) - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) - [Spring’s RequestBody and ResponseBody Annotations](https://www.baeldung.com/spring-request-response-body) +- [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 1a4ad2fbb6..5c88697cef 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -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 86% 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..191719b084 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; @@ -42,7 +43,7 @@ public class EmployeeClient ResponseEntity> response = restTemplate.exchange( - "http://localhost:8080/spring-rest/employees/", + "http://localhost:8082/spring-rest/employees/", HttpMethod.GET, null, new ParameterizedTypeReference>(){}); @@ -60,7 +61,7 @@ public class EmployeeClient EmployeeList response = restTemplate.getForObject( - "http://localhost:8080/spring-rest/employees/v2", + "http://localhost:8082/spring-rest/employees/v2", EmployeeList.class); List employees = response.getEmployees(); @@ -79,7 +80,7 @@ public class EmployeeClient newEmployees.add(new Employee(4, "CEO")); restTemplate.postForObject( - "http://localhost:8080/spring-rest/employees/", + "http://localhost:8082/spring-rest/employees/", newEmployees, ResponseEntity.class); } @@ -93,7 +94,7 @@ public class EmployeeClient newEmployees.add(new Employee(4, "CEO")); restTemplate.postForObject( - "http://localhost:8080/spring-rest/employees/v2/", + "http://localhost:8082/spring-rest/employees/v2/", new EmployeeList(newEmployees), ResponseEntity.class); } 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/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/java/com/baeldung/web/upload/app/Application.java b/spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java similarity index 79% rename from spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java rename to spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java index d6821196eb..f3b1c0dc6f 100644 --- a/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java +++ b/spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java @@ -9,9 +9,9 @@ import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @ComponentScan("com.baeldung.web.upload") @SpringBootApplication -public class Application extends SpringBootServletInitializer { +public class UploadApplication extends SpringBootServletInitializer { public static void main(final String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(UploadApplication.class, args); } } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java deleted file mode 100644 index 996f229128..0000000000 --- a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.web.controller.advice; - -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; - -@ControllerAdvice -public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - - public JsonpControllerAdvice() { - super("callback"); - } - -} 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