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 System.out.println(todoItem.toString())); + } + +} diff --git a/core-java-lang/src/main/java/com/baeldung/packages/TodoList.java b/core-java-lang/src/main/java/com/baeldung/packages/TodoList.java new file mode 100644 index 0000000000..6ed6cd4ec1 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/packages/TodoList.java @@ -0,0 +1,27 @@ +package com.baeldung.packages; + +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.packages.domain.TodoItem; + +public class TodoList { + private List todoItems; + + public void addTodoItem(TodoItem todoItem) { + if (todoItems == null) { + todoItems = new ArrayList(); + } + + todoItems.add(todoItem); + } + + public List getTodoItems() { + return todoItems; + } + + public void setTodoItems(List todoItems) { + this.todoItems = todoItems; + } + +} diff --git a/core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java b/core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java new file mode 100644 index 0000000000..972e574a7f --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java @@ -0,0 +1,39 @@ +package com.baeldung.packages.domain; + +import java.time.LocalDate; + +public class TodoItem { + private Long id; + private String description; + private LocalDate dueDate; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public LocalDate getDueDate() { + return dueDate; + } + + public void setDueDate(LocalDate dueDate) { + this.dueDate = dueDate; + } + + @Override + public String toString() { + return "TodoItem [id=" + id + ", description=" + description + ", dueDate=" + dueDate + "]"; + } + +} diff --git a/core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java b/core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java new file mode 100644 index 0000000000..212fb7b3c7 --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.packages; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; + +import org.junit.Test; + +import com.baeldung.packages.domain.TodoItem; + +public class PackagesUnitTest { + + @Test + public void whenTodoItemAdded_ThenSizeIncreases() { + TodoItem todoItem = new TodoItem(); + todoItem.setId(1L); + todoItem.setDescription("Test the Todo List"); + todoItem.setDueDate(LocalDate.now()); + TodoList todoList = new TodoList(); + todoList.addTodoItem(todoItem); + assertEquals(1, todoList.getTodoItems().size()); + } +} diff --git a/core-java-networking/README.md b/core-java-networking/README.md index b7a142ea27..626ea794e6 100644 --- a/core-java-networking/README.md +++ b/core-java-networking/README.md @@ -1,3 +1,7 @@ ========= -## Core Java Net +## Core Java Networking + +### Relevant Articles + +- [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server) diff --git a/core-java/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-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/inline/classes/CircleRadius.kt b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt new file mode 100644 index 0000000000..5b46b9570f --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt @@ -0,0 +1,14 @@ +package com.baeldung.inline.classes + +interface Drawable { + fun draw() +} + +inline class CircleRadius(private val circleRadius : Double) : Drawable { + val diameterOfCircle get() = 2 * circleRadius + fun areaOfCircle() = 3.14 * circleRadius * circleRadius + + override fun draw() { + println("Draw my circle") + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt new file mode 100644 index 0000000000..430fa509da --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt @@ -0,0 +1,3 @@ +package com.baeldung.inline.classes + +inline class InlineDoubleWrapper(val doubleValue : Double) \ No newline at end of file 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/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt new file mode 100644 index 0000000000..8de378b6dd --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt @@ -0,0 +1,19 @@ +package com.baeldung.inline.classes + +import org.junit.Test +import kotlin.test.assertEquals + +class CircleRadiusTest { + + @Test + fun givenRadius_ThenDiameterIsCorrectlyCalculated() { + val radius = CircleRadius(5.0) + assertEquals(10.0, radius.diameterOfCircle) + } + + @Test + fun givenRadius_ThenAreaIsCorrectlyCalculated() { + val radius = CircleRadius(5.0) + assertEquals(78.5, radius.areaOfCircle()) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt new file mode 100644 index 0000000000..349c90d6f4 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt @@ -0,0 +1,13 @@ +package com.baeldung.inline.classes + +import org.junit.Test +import kotlin.test.assertEquals + +class InlineDoubleWrapperTest { + + @Test + fun whenInclineClassIsUsed_ThenPropertyIsReadCorrectly() { + val piDoubleValue = InlineDoubleWrapper(3.14) + assertEquals(3.14, piDoubleValue.doubleValue) + } +} \ No newline at end of file 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-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/README.md b/java-strings/README.md index 240acd663b..2713f69d58 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -35,6 +35,7 @@ - [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) - [String Performance Hints](https://www.baeldung.com/java-string-performance) - [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) +- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) - [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) - [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) - [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) @@ -42,4 +43,4 @@ - [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) - [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) - [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) -- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) +- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) \ No newline at end of file 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/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java new file mode 100644 index 0000000000..a9f8a04c8d --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.string.conversion; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +public class ByteArrayToStringUnitTest { + + @Test + public void whenStringConstructorWithDefaultCharset_thenOK() { + final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, + 108, 100, 33 }; + String string = new String(byteArrray); + System.out.println(string); + + assertNotNull(string); + } + + @Test + public void whenStringConstructorWithNamedCharset_thenOK() + throws UnsupportedEncodingException { + final String charsetName = "IBM01140"; + final byte[] byteArrray = { -56, -123, -109, -109, -106, 64, -26, -106, + -103, -109, -124, 90 }; + + String string = new String(byteArrray, charsetName); + + assertEquals("Hello World!", string); + } + + @Test + public void whenStringConstructorWithCharSet_thenOK() { + final Charset charset = Charset.forName("UTF-8"); + final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, + 108, 100, 33 }; + + String string = new String(byteArrray, charset); + + assertEquals("Hello World!", string); + } + + @Test + public void whenStringConstructorWithStandardCharSet_thenOK() { + final Charset charset = StandardCharsets.UTF_16; + + final byte[] byteArrray = { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, + 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }; + + String string = new String(byteArrray, charset); + + assertEquals("Hello World!", string); + } + + @Test + public void whenDecodeWithCharset_thenOK() { + byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33 }; + final Charset charset = StandardCharsets.US_ASCII; + + String string = charset.decode(ByteBuffer.wrap(byteArrray)).toString(); + System.out.println(string); + + assertEquals("Hello �orl�!", string); + } + + @Test + public void whenUsingCharsetDecoder_thenOK() + throws CharacterCodingException { + byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33}; + CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder(); + + decoder.onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE) + .replaceWith("?"); + + String string = decoder.decode(ByteBuffer.wrap(byteArrray)).toString(); + + assertEquals("Hello ?orl?!", string); + } + + +} diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java new file mode 100644 index 0000000000..5377b4b28d --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java @@ -0,0 +1,122 @@ +package com.baeldung.string.conversion; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.UnsupportedEncodingException; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import org.junit.Test; + +public class StringToByteArrayUnitTest { + + @Test + public void whenGetBytesWithDefaultCharset_thenOK() { + final String inputString = "Hello World!"; + final String defaultCharSet = Charset.defaultCharset() + .displayName(); + + byte[] byteArrray = inputString.getBytes(); + + System.out.printf( + "Using default charset:%s, Input String:%s, Output byte array:%s\n", + defaultCharSet, inputString, Arrays.toString(byteArrray)); + + assertNotNull(byteArrray); + assert (byteArrray.length >= inputString.length()); + } + + @Test + public void whenGetBytesWithNamedCharset_thenOK() + throws UnsupportedEncodingException { + final String inputString = "Hello World!"; + final String charsetName = "IBM01140"; + + byte[] byteArrray = inputString.getBytes("IBM01140"); + + System.out.printf( + "Using named charset:%s, Input String:%s, Output byte array:%s\n", + charsetName, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals(new byte[] { -56, -123, -109, -109, -106, 64, -26, + -106, -103, -109, -124, 90 }, + byteArrray); + } + + @Test + public void whenGetBytesWithCharset_thenOK() { + final String inputString = "Hello ਸੰਸਾਰ!"; + final Charset charset = Charset.forName("ASCII"); + + byte[] byteArrray = inputString.getBytes(charset); + + System.out.printf( + "Using Charset:%s, Input String:%s, Output byte array:%s\n", + charset, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals( + new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 }, + byteArrray); + } + + @Test + public void whenGetBytesWithStandardCharset_thenOK() { + final String inputString = "Hello World!"; + final Charset charset = StandardCharsets.UTF_16; + + byte[] byteArrray = inputString.getBytes(charset); + + System.out.printf( + "Using Standard Charset:%s, Input String:%s, Output byte array:%s\n", + charset, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals(new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, + 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }, + byteArrray); + } + + @Test + public void whenEncodeWithCharset_thenOK() { + final String inputString = "Hello ਸੰਸਾਰ!"; + final Charset charset = StandardCharsets.US_ASCII; + + byte[] byteArrray = charset.encode(inputString) + .array(); + + System.out.printf( + "Using encode with Charset:%s, Input String:%s, Output byte array:%s\n", + charset, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals( + new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 }, + byteArrray); + } + + @Test + public void whenUsingCharsetEncoder_thenOK() + throws CharacterCodingException { + final String inputString = "Hello ਸੰਸਾਰ!"; + CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder(); + encoder.onMalformedInput(CodingErrorAction.IGNORE) + .onUnmappableCharacter(CodingErrorAction.REPLACE) + .replaceWith(new byte[] { 0 }); + + byte[] byteArrray = encoder.encode(CharBuffer.wrap(inputString)) + .array(); + + System.out.printf( + "Using encode with CharsetEncoder:%s, Input String:%s, Output byte array:%s\n", + encoder, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals( + new byte[] { 72, 101, 108, 108, 111, 32, 0, 0, 0, 0, 0, 33 }, + byteArrray); + } + +} 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/libraries-apache-commons/.gitignore b/libraries-apache-commons/.gitignore new file mode 100644 index 0000000000..e594daf27a --- /dev/null +++ b/libraries-apache-commons/.gitignore @@ -0,0 +1,9 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar +/bin/ diff --git a/libraries-apache-commons/README.md b/libraries-apache-commons/README.md new file mode 100644 index 0000000000..01f2379588 --- /dev/null +++ b/libraries-apache-commons/README.md @@ -0,0 +1,20 @@ +### Relevant articles + +- [Array Processing with Apache Commons Lang 3](http://www.baeldung.com/array-processing-commons-lang) +- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) +- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) +- [Apache Commons Collections SetUtils](http://www.baeldung.com/apache-commons-setutils) +- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) +- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text) +- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) +- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) +- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain) +- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) +- [Apache Commons IO](http://www.baeldung.com/apache-commons-io) +- [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag) +- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils) +- [Apache Commons BeanUtils](http://www.baeldung.com/apache-commons-beanutils) +- [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map) +- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) +- [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) +- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) \ No newline at end of file diff --git a/libraries-apache-commons/log4j.properties b/libraries-apache-commons/log4j.properties new file mode 100644 index 0000000000..2173c5d96f --- /dev/null +++ b/libraries-apache-commons/log4j.properties @@ -0,0 +1 @@ +log4j.rootLogger=INFO, stdout diff --git a/libraries-apache-commons/pom.xml b/libraries-apache-commons/pom.xml new file mode 100644 index 0000000000..c7ff918af9 --- /dev/null +++ b/libraries-apache-commons/pom.xml @@ -0,0 +1,109 @@ + + + 4.0.0 + libraries-apache-commons + libraries-apache-commons + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + + + commons-beanutils + commons-beanutils + ${commons-beanutils.version} + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + commons-io + commons-io + ${commons.io.version} + + + commons-chain + commons-chain + ${commons-chain.version} + + + org.apache.commons + commons-csv + ${commons-csv.version} + + + commons-dbutils + commons-dbutils + ${commons.dbutils.version} + + + org.apache.commons + commons-math3 + ${common-math3.version} + + + commons-net + commons-net + ${commons-net.version} + + + com.h2database + h2 + ${h2.version} + + + org.knowm.xchart + xchart + ${xchart-version} + + + org.apache.commons + commons-collections4 + ${commons.collections.version} + + + org.hamcrest + java-hamcrest + ${org.hamcrest.java-hamcrest.version} + test + + + + + + 3.6 + 1.1 + 1.9.3 + 1.2 + 1.4 + 3.6.2 + 2.5 + 1.6 + 1.4.196 + 4.1 + 4.12 + 2.0.0.0 + 1.10.L001 + 3.5.2 + 3.6 + 1.3 + 3.6.1 + + + diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/Course.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Course.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/Course.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Course.java diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseService.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseService.java diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/Student.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Student.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/Student.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Student.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmCatalog.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmCatalog.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmConstants.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmConstants.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AuditFilter.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AuditFilter.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/collectionutil/Address.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Address.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/collectionutil/Address.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Address.java diff --git a/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Customer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Customer.java diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Email.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/dbutils/Email.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Email.java diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Employee.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Employee.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/dbutils/Employee.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Employee.java diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java diff --git a/libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/io/FileMonitor.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/io/FileMonitor.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleObject.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleObject.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/application/Application.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/application/Application.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/User.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/User.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java diff --git a/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/math3/Histogram.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/math3/Histogram.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/math3/Histogram.java diff --git a/flips/src/main/resources/logback.xml b/libraries-apache-commons/src/main/resources/logback.xml similarity index 100% rename from flips/src/main/resources/logback.xml rename to libraries-apache-commons/src/main/resources/logback.xml diff --git a/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/FractionUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/FractionUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/FractionUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/FractionUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/DiffUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/DiffUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/DiffUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/DiffUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/StrBuilderUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/StrBuilderUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/StrBuilderUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/WordUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/WordUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/WordUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/WordUtilsUnitTest.java diff --git a/libraries/src/test/resources/aaa.txt b/libraries-apache-commons/src/test/resources/aaa.txt similarity index 100% rename from libraries/src/test/resources/aaa.txt rename to libraries-apache-commons/src/test/resources/aaa.txt diff --git a/libraries/src/test/resources/book.csv b/libraries-apache-commons/src/test/resources/book.csv similarity index 100% rename from libraries/src/test/resources/book.csv rename to libraries-apache-commons/src/test/resources/book.csv diff --git a/libraries/src/test/resources/employees.sql b/libraries-apache-commons/src/test/resources/employees.sql similarity index 100% rename from libraries/src/test/resources/employees.sql rename to libraries-apache-commons/src/test/resources/employees.sql diff --git a/libraries/src/test/resources/fileTest.txt b/libraries-apache-commons/src/test/resources/fileTest.txt similarity index 100% rename from libraries/src/test/resources/fileTest.txt rename to libraries-apache-commons/src/test/resources/fileTest.txt diff --git a/libraries/src/test/resources/sample.txt b/libraries-apache-commons/src/test/resources/sample.txt similarity index 100% rename from libraries/src/test/resources/sample.txt rename to libraries-apache-commons/src/test/resources/sample.txt diff --git a/libraries/README.md b/libraries/README.md index 851e3a3d17..ce2445f3e0 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -1,40 +1,29 @@ ### Relevant articles - [Intro to Jasypt](http://www.baeldung.com/jasypt) -- [Array Processing with Apache Commons Lang 3](http://www.baeldung.com/array-processing-commons-lang) -- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) - [Introduction to Javatuples](http://www.baeldung.com/java-tuples) - [Introduction to Javassist](http://www.baeldung.com/javassist) - [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink) - [Introduction to JSONassert](http://www.baeldung.com/jsonassert) - [Intro to JaVers](http://www.baeldung.com/javers) -- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) - [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay) - [Introduction to Quartz](http://www.baeldung.com/quartz) - [How to Warm Up the JVM](http://www.baeldung.com/java-jvm-warmup) -- [Apache Commons Collections SetUtils](http://www.baeldung.com/apache-commons-setutils) - [Software Transactional Memory in Java Using Multiverse](http://www.baeldung.com/java-multiverse-stm) - [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave) - [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) -- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) -- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text) -- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) - [Introduction to Neuroph](http://www.baeldung.com/neuroph) -- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) - [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception) - [Introduction to PCollections](http://www.baeldung.com/java-pcollections) - [Introduction to Hoverfly in Java](http://www.baeldung.com/hoverfly) -- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain) - [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections) - [DistinctBy in Java Stream API](http://www.baeldung.com/java-streams-distinct-by) -- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) - [Introduction to NoException](http://www.baeldung.com/no-exception) -- [Apache Commons IO](http://www.baeldung.com/apache-commons-io) - [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types) - [Introduction to javax.measure](http://www.baeldung.com/javax-measure) - [Spring Yarg Integration](http://www.baeldung.com/spring-yarg) @@ -44,7 +33,6 @@ - [Introduction to MBassador](http://www.baeldung.com/mbassador) - [Introduction to Retrofit](http://www.baeldung.com/retrofit) - [Using Pairs in Java](http://www.baeldung.com/java-pairs) -- [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag) - [Introduction to Caffeine](http://www.baeldung.com/java-caching-caffeine) - [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) - [Introduction To Docx4J](http://www.baeldung.com/docx4j) @@ -62,28 +50,22 @@ - [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) -- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils) - [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) - [Introduction to jOOL](http://www.baeldung.com/jool) - [Consumer Driven Contracts with Pact](http://www.baeldung.com/pact-junit-consumer-driven-contracts) -- [Apache Commons BeanUtils](http://www.baeldung.com/apache-commons-beanutils) -- [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map) - [Introduction to Atlassian Fugue](http://www.baeldung.com/java-fugue) - [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client) - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) -- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) - [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) - [Introduction to JavaPoet](http://www.baeldung.com/java-poet) - [Introduction to Joda-Time](http://www.baeldung.com/joda-time) -- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) - [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date) -- [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) - [Guide to Resilience4j](http://www.baeldung.com/resilience4j) - [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml) - [Guide to JMapper](http://www.baeldung.com/jmapper) -- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) - [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) +- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index cb85a57304..2ad4871e3f 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -50,31 +50,21 @@ opencsv ${opencsv.version} - - commons-beanutils - commons-beanutils - ${commons-beanutils.version} - org.apache.commons commons-lang3 ${commons-lang.version} - org.apache.commons - commons-text - ${commons-text.version} + commons-net + commons-net + ${commons-net.version} tec.units unit-ri ${unit-ri.version} - - org.apache.commons - commons-collections4 - ${commons.collections.version} - org.jasypt jasypt @@ -134,32 +124,6 @@ - - commons-io - commons-io - ${commons.io.version} - - - commons-chain - commons-chain - ${commons-chain.version} - - - org.apache.commons - commons-csv - ${commons-csv.version} - - - commons-dbutils - commons-dbutils - ${commons.dbutils.version} - - - - org.apache.commons - commons-math3 - ${common-math3.version} - net.serenity-bdd serenity-core @@ -675,24 +639,6 @@ resilience4j-timelimiter ${resilience4j.version} - - org.knowm.xchart - xchart - ${xchart-version} - - - - commons-net - commons-net - ${commons-net.version} - - - org.mockftpserver - MockFtpServer - ${mockftpserver.version} - test - - com.squareup javapoet @@ -723,6 +669,12 @@ ${derive4j.version} true + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + @@ -860,10 +812,6 @@ 0.7.0 3.2.7 3.6 - 1.1 - 1.9.3 - 1.2 - 1.4 1.9.2 1.2 3.21.0-GA @@ -871,13 +819,10 @@ 1.5.0 3.1.0 4.5.3 - 2.5 - 1.6 1.4.196 1.0 4.5.3 - 2.5 2.8.5 2.92 1.9.26 @@ -885,7 +830,6 @@ 1.9.0 1.9.27 1.1.0 - 4.1 4.12 0.10 3.5.0 @@ -923,13 +867,9 @@ 2.1.2 2.5.11 0.12.1 - 3.5.2 - 3.6 - 2.7.1 1.10.0 1.3 0.8.1 - 3.6.1 3.2.0-m7 5.1.1 5.0.2 @@ -959,6 +899,8 @@ 3.3.0 3.0.2 1.1.0 + 2.7.1 + 3.6 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/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/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/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java index 5795e9912b..50d28af3d1 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java @@ -144,8 +144,8 @@ public class JedisIntegrationTest { scores.put("PlayerTwo", 1500.0); scores.put("PlayerThree", 8200.0); - scores.keySet().forEach(player -> { - jedis.zadd(key, scores.get(player), player); + scores.entrySet().forEach(playerScore -> { + jedis.zadd(key, playerScore.getValue(), playerScore.getKey()); }); Set players = jedis.zrevrange(key, 0, 1); 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 d0d0fa7049..57487f00cc 100644 --- a/pom.xml +++ b/pom.xml @@ -323,219 +323,240 @@ parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - asm - atomix - apache-cayenne - aws - aws-lambda - akka-streams - algorithms - annotations - apache-cxf - apache-fop - apache-geode - apache-poi - apache-tika - apache-thrift - apache-curator - apache-zookeeper - apache-opennlp - autovalue - axon - azure - bootique - cdi - java-strings - - core-java - core-java-collections - java-collections-conversions - java-collections-maps - core-java-io - core-java-8 - java-streams + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + 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-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 + + 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 + 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 + helidon + httpclient + hystrix + + image-processing + immutables + + jackson + java-collections-conversions + java-collections-maps + + 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 + + jee-7-security + jersey + JGit + jgroups + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta + + + kotlin-libraries + + + libraries-data + libraries-apache-commons + libraries-security + libraries-server + linkrest + 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 + + noexception + + optaplanner + orika + osgi + + patterns + pdf + performance-tests + + protobuffer + + persistence-modules/activejdbc + persistence-modules/apache-cayenne persistence-modules/core-java-persistence - core-kotlin - kotlin-libraries - core-groovy - core-java-concurrency - core-java-concurrency-collections - couchbase - persistence-modules/deltaspike - dozer - ethereum - ejb - ejb/ejb-client - feign - flips - testing-modules/gatling - geotools - testing-modules/groovy-spock - google-cloud - google-web-toolkit - gson - guava - guava-collections - guava-modules/guava-18 - guava-modules/guava-19 - guava-modules/guava-21 - guice - disruptor - spring-static-resources - hazelcast - hbase - hibernate5 - httpclient - hystrix - image-processing - immutables - persistence-modules/influxdb - jackson - persistence-modules/java-cassandra - vavr - java-lite - java-numbers - java-rmi - java-vavr-stream - javax-servlets - javaxval - jaxb - javafx - jgroups - jee-7 - jee-7-security - jhipster - jjwt - jsf - json-path - json - jsoup - testing-modules/junit-5 - - libraries - libraries-data - libraries-security - libraries-server - linkrest - logging-modules/log-mdc - logging-modules/log4j - logging-modules/log4j2 - logging-modules/logback - lombok - mapstruct - metrics - maven - mesos-marathon - msf4j - testing-modules/mockito - testing-modules/mockito-2 - testing-modules/mocks - mustache - mvn-wrapper - noexception - persistence-modules/orientdb - osgi - orika - patterns - pdf - protobuffer - persistence-modules/querydsl - reactor-core - persistence-modules/redis - testing-modules/rest-assured - testing-modules/rest-testing - resteasy - rxjava - rxjava-2 - spring-swagger-codegen - testing-modules/selenium-junit-testng - persistence-modules/solr - spark-java - spring-4 - spring-5 - spring-5-data-reactive - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client - spring-5-mvc - spring-5-security - spring-activiti - spring-akka - spring-amqp - spring-all - spring-amqp-simple - spring-apache-camel - spring-batch - spring-bom - spring-boot - spring-boot-client - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-camel - spring-boot-ops - persistence-modules/spring-boot-persistence - spring-boot-security - spring-boot-mvc - spring-boot-vue - spring-boot-logging-log4j2 - spring-boot-disable-console-logging - spring-cloud-data-flow - spring-cloud - spring-cloud-bus - spring-core - spring-cucumber - spring-ejb - spring-aop - persistence-modules/spring-data-cassandra - spring-data-couchbase-2 - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-elasticsearch - 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 - spring-data-rest - persistence-modules/spring-data-solr - spring-dispatcher-servlet - spring-exceptions - spring-freemarker - persistence-modules/spring-hibernate-3 - persistence-modules/spring-hibernate4 - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - spring-integration - spring-jenkins-pipeline - spring-jersey - jmeter - spring-jms - spring-jooq - persistence-modules/spring-jpa - spring-kafka - spring-katharsis - spring-ldap - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml - spring-mvc-kotlin - spring-protobuf - spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - - - spring-resttemplate + 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/java-jpa + persistence-modules/jnosql + persistence-modules/liquibase + persistence-modules/orientdb + persistence-modules/querydsl + persistence-modules/redis + persistence-modules/solr + persistence-modules/spring-boot-h2/spring-boot-h2-database + persistence-modules/spring-boot-persistence + 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-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 + @@ -557,7 +578,7 @@ **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java - **/JdbcTest.java + **/*JdbcTest.java **/*LiveTest.java @@ -574,140 +595,119 @@ parent-java parent-kotlin - spring-session - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-thymeleaf - spring-userservice - spring-zuul - spring-remoting - spring-reactor - spring-vertx - spring-jinq - spring-rest-embedded-tomcat - testing-modules/testing - testing-modules/testng - video-tutorials - xml - xmlunit-2 - struts-2 - apache-velocity - apache-solrj - rabbitmq - vertx - persistence-modules/spring-data-gemfire - mybatis - spring-drools - drools - persistence-modules/liquibase - spring-boot-property-exp - testing-modules/mockserver - testing-modules/test-containers - undertow - vaadin - vertx-and-rxjava saas - deeplearning4j - lucene - vraptor - persistence-modules/java-cockroachdb - spring-security-thymeleaf - persistence-modules/java-jdbi - jersey - java-spi - performance-tests - twilio - spring-boot-ctx-fluent - java-ee-8-security-api - spring-webflux-amqp - antlr - maven-archetype - optaplanner - apache-meecrowave - spring-reactive-kotlin - jnosql + 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-activiti + spring-akka + spring-all + spring-amqp + spring-aop + spring-apache-camel + spring-batch + spring-bom + + spring-boot + spring-boot-admin spring-boot-angular-ecommerce - cdi-portable-extension - jta - - java-websocket - activejdbc - animal-sniffer-mvn-plugin - apache-avro - apache-bval - apache-shiro - apache-spark - asciidoctor - checker-plugin - - - core-java-sun - custom-pmd - dagger - data-structures - dubbo - flyway - - - jni - jooby - - - - ratpack - rest-with-spark-java 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-custom-aop + 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-data-rest-querydsl + spring-dispatcher-servlet + spring-drools + + spring-ejb + spring-exceptions + + spring-freemarker + spring-groovy + + spring-integration + + 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-mybatis + + spring-protobuf + + spring-quartz + + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-embedded-tomcat + spring-rest-full spring-rest-hal-browser + spring-rest-query-language spring-rest-shell - spring-rest-template + spring-rest-simple + spring-resttemplate spring-roo - spring-security-stormpath - sse-jaxrs - static-analysis - stripe - - Twitter4J - wicket - xstream - cas/cas-secured-app - cas/cas-server - - - - - - - - - - - - - - - - - spring-boot-custom-starter/greeter - spring-boot-h2/spring-boot-h2-database - - - - - flyway-cdi-extension 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 @@ -715,6 +715,7 @@ 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 @@ -725,12 +726,75 @@ spring-security-mvc-session 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-x509 + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen + + spring-thymeleaf + + spring-userservice + + spring-vault + spring-vertx + + spring-webflux-amqp + + spring-zuul + + sse-jaxrs + static-analysis + stripe + structurizr + struts-2 + + 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/selenium-junit-testng + testing-modules/spring-testing + testing-modules/test-containers + testing-modules/testing + testing-modules/testng + + twilio + Twitter4J + + undertow + + vavr + vertx + vertx-and-rxjava + video-tutorials + vraptor + + wicket + + xml + xmlunit-2 + xstream + @@ -763,6 +827,7 @@ spring-5-reactive-client spring-5-reactive-security spring-5-security + spring-5-security-oauth spring-activiti spring-akka spring-all @@ -779,7 +844,7 @@ spring-boot-custom-starter greeter-spring-boot-autoconfigure greeter-spring-boot-sample-app - spring-boot-h2/spring-boot-h2-database + persistence-modules/spring-boot-h2/spring-boot-h2-database spring-boot-jasypt spring-boot-keycloak spring-boot-mvc @@ -878,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 @@ -889,697 +954,79 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - - - - - - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - - - - - - - - - testing-modules/mockito - testing-modules/mockito-2 - testing-modules/mocks - mustache - mvn-wrapper - noexception - persistence-modules/orientdb - osgi - orika - patterns - pdf - protobuffer - persistence-modules/querydsl - reactor-core - persistence-modules/redis - testing-modules/rest-assured - testing-modules/rest-testing - resteasy - rxjava - rxjava-2 - spring-swagger-codegen - testing-modules/selenium-junit-testng - persistence-modules/solr - spark-java - spring-4 - spring-5 - spring-5-data-reactive - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client - spring-5-mvc - spring-5-security - spring-activiti - spring-akka - spring-amqp - spring-all - spring-amqp-simple - spring-apache-camel - spring-batch - jmh - - - - - - spring-bom - spring-boot - spring-boot-client - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-camel - spring-boot-ops - persistence-modules/spring-boot-persistence - spring-boot-security - spring-boot-mvc - spring-boot-logging-log4j2 - spring-boot-disable-console-logging - spring-cloud-data-flow - spring-cloud - spring-cloud-bus - spring-core - spring-cucumber - spring-ejb - spring-aop - persistence-modules/spring-data-cassandra - spring-data-couchbase-2 - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-elasticsearch - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-mongodb - persistence-modules/spring-data-jpa - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-redis - spring-data-rest - - - - - - - persistence-modules/spring-data-solr - spring-dispatcher-servlet - spring-exceptions - spring-freemarker - persistence-modules/spring-hibernate-3 - persistence-modules/spring-hibernate4 - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jms - spring-jooq - persistence-modules/spring-jpa - spring-kafka - spring-katharsis - spring-ldap - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml - spring-mvc-kotlin - spring-protobuf - spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - spring-rest - spring-resttemplate - spring-rest-simple - spring-reactive-kotlin - - - - - - - - - - - - - - - - java-websocket - activejdbc - animal-sniffer-mvn-plugin - apache-avro - apache-bval - apache-shiro - apache-spark - asciidoctor - checker-plugin - - - core-java-sun - custom-pmd - dagger - data-structures - dubbo - flyway - - - jni - jooby - - - - ratpack - rest-with-spark-java - spring-boot-autoconfiguration - spring-boot-custom-starter - spring-boot-jasypt - spring-custom-aop - spring-data-rest-querydsl - spring-groovy - spring-mobile - spring-mustache - spring-mvc-simple - spring-mybatis - spring-rest-hal-browser - spring-rest-shell - spring-rest-template - spring-roo - spring-security-stormpath - sse-jaxrs - static-analysis - stripe - - - wicket - xstream - cas/cas-secured-app - - - - - - - - - - - - - - jenkins/hello-world - - - - spring-boot-custom-starter/greeter - spring-boot-h2/spring-boot-h2-database - - - - - - - - - - integration-lite - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - - - - - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - asm - atomix - apache-cayenne - aws - aws-lambda - akka-streams - akka-http - algorithms - annotations - apache-cxf - apache-fop - apache-poi - apache-tika - apache-thrift - apache-curator - apache-zookeeper - apache-opennlp - autovalue - axon - azure - bootique - cdi - java-strings - - core-java-collections - java-collections-conversions - java-collections-maps - core-java-io - core-java-8 - java-streams - core-groovy - - couchbase - persistence-modules/deltaspike - dozer - ethereum - feign - flips - testing-modules/groovy-spock - google-cloud - gson - guava - guava-collections - guava-modules/guava-18 - guava-modules/guava-19 - guava-modules/guava-21 - guice - disruptor - spring-static-resources - hazelcast - hbase - - hystrix - image-processing - immutables - persistence-modules/influxdb - jackson - vavr - java-lite - java-numbers - java-rmi - java-vavr-stream - javax-servlets - javaxval - jaxb - javafx - jgroups - jee-7 - jee-7-security - jjwt - jsf - json-path - json - jsoup - jta - testing-modules/junit-5 - testing-modules/junit5-migration - jws - libraries-data - linkrest - logging-modules/log-mdc - logging-modules/log4j - - logging-modules/logback - lombok - mapstruct - - maven - mesos-marathon - msf4j - testing-modules/mockito - testing-modules/mockito-2 - testing-modules/mocks - mustache - mvn-wrapper - noexception - persistence-modules/orientdb - osgi - orika - patterns - pdf - protobuffer - persistence-modules/querydsl - reactor-core - persistence-modules/redis - testing-modules/rest-assured - testing-modules/rest-testing - resteasy - rxjava - rxjava-2 - spring-swagger-codegen - testing-modules/selenium-junit-testng - persistence-modules/solr - spark-java - spring-4 - spring-5-data-reactive - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client - spring-5-mvc - spring-5-security - spring-activiti - spring-akka - spring-amqp - spring-all - spring-amqp-simple - spring-apache-camel - spring-batch - spring-bom - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-camel - persistence-modules/spring-boot-persistence - spring-boot-security - spring-boot-mvc - spring-boot-logging-log4j2 - spring-boot-disable-console-logging - spring-cloud-data-flow - spring-cloud - spring-cloud-bus - spring-core - spring-cucumber - spring-ejb - spring-aop - - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-mongodb - persistence-modules/spring-data-neo4j - - spring-data-rest - persistence-modules/spring-data-solr - spring-dispatcher-servlet - spring-exceptions - spring-freemarker - persistence-modules/spring-hibernate-3 - - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - spring-integration - spring-jenkins-pipeline - spring-jersey - - spring-jms - spring-jooq - persistence-modules/spring-jpa - spring-kafka - spring-katharsis - spring-ldap - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml - spring-mvc-kotlin - spring-protobuf - spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - spring-rest - spring-resttemplate - spring-rest-simple - spring-security-acl - spring-security-cache-control - spring-security-client/spring-security-jsp-authentication - spring-security-client/spring-security-jsp-authorize - spring-security-client/spring-security-jsp-config - spring-security-client/spring-security-mvc - spring-security-client/spring-security-thymeleaf-authentication - spring-security-client/spring-security-thymeleaf-authorize - spring-security-client/spring-security-thymeleaf-config - spring-security-core - spring-security-mvc-boot - spring-security-mvc-digest-auth - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc-session - spring-security-mvc-socket - spring-security-openid - - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-rest - spring-security-sso - spring-security-x509 - spring-session - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-thymeleaf - spring-userservice - spring-zuul - spring-remoting - spring-reactor - spring-vertx - spring-vault - spring-jinq - spring-rest-embedded-tomcat - testing-modules/testing - testing-modules/testng - video-tutorials - - xmlunit-2 - struts-2 - apache-velocity - apache-solrj - rabbitmq - - persistence-modules/spring-data-gemfire - mybatis - spring-drools - drools - persistence-modules/liquibase - spring-boot-property-exp - testing-modules/mockserver - testing-modules/test-containers - undertow - vaadin - vertx-and-rxjava - saas - deeplearning4j - lucene - vraptor - persistence-modules/java-cockroachdb - spring-security-thymeleaf - persistence-modules/java-jdbi - jersey - java-spi - performance-tests - twilio - spring-boot-ctx-fluent - java-ee-8-security-api - spring-webflux-amqp - antlr - maven-archetype - apache-meecrowave - - persistence-modules/spring-hibernate4 - xml - vertx - metrics - httpclient - - - - - - - - - - - - - integration-heavy + 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 org.apache.maven.plugins maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - json - + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + @@ -1591,23 +1038,523 @@ parent-spring-4 parent-spring-5 parent-java - parent-kotlin - libraries - geotools - jhipster - testing-modules/gatling - spring-boot - spring-boot-ops - spring-5 - core-kotlin - kotlin-libraries - core-java + parent-kotlin + + 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-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 + + 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 + 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 + helidon + httpclient + hystrix + + image-processing + immutables + + jackson + java-collections-conversions + java-collections-maps + + 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 + + jee-7-security + jersey + JGit + jgroups + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta + + + kotlin-libraries + + + libraries-data + libraries-apache-commons + libraries-security + libraries-server + linkrest + 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 + + noexception + + optaplanner + orika + osgi + + patterns + pdf + 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/java-jpa + persistence-modules/jnosql + persistence-modules/liquibase + persistence-modules/orientdb + persistence-modules/querydsl + persistence-modules/redis + persistence-modules/solr + persistence-modules/spring-boot-h2/spring-boot-h2-database + persistence-modules/spring-boot-persistence + 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-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 + + + + + + + integration-lite-second + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + 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-activiti + spring-akka + spring-all + spring-amqp + spring-aop + spring-apache-camel + spring-batch + spring-bom + + 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-data-rest-querydsl + spring-dispatcher-servlet + spring-drools + + spring-ejb + spring-exceptions + + spring-freemarker + + spring-groovy + + spring-integration + + 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-mybatis + + spring-protobuf + + spring-quartz + + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-embedded-tomcat + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-resttemplate + spring-roo + + 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 + spring-security-client/spring-security-mvc + spring-security-client/spring-security-thymeleaf-authentication + spring-security-client/spring-security-thymeleaf-authorize + spring-security-client/spring-security-thymeleaf-config + + spring-security-core + spring-security-mvc-boot spring-security-mvc-custom - hibernate5 - persistence-modules/spring-data-elasticsearch - core-java-concurrency - core-java-concurrency-collections + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen + + spring-thymeleaf + + spring-userservice + + spring-vault + spring-vertx + + spring-webflux-amqp + + spring-zuul + + sse-jaxrs + static-analysis + stripe + structurizr + struts-2 + + 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/selenium-junit-testng + testing-modules/spring-testing + testing-modules/test-containers + testing-modules/testing + testing-modules/testng + + twilio + Twitter4J + + undertow + + vavr + vertx + vertx-and-rxjava + video-tutorials + vraptor + + wicket + + xml + xmlunit-2 + xstream + + + + + + + integration-heavy + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.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 @@ -1632,13 +1579,16 @@ true false false - + false + 4.12 1.3 2.21.0 + 1.7.21 1.1.7 + 2.21.0 3.7.0 diff --git a/rsocket/README.md b/rsocket/README.md new file mode 100644 index 0000000000..fa232bc515 --- /dev/null +++ b/rsocket/README.md @@ -0,0 +1,3 @@ +Relevant articles + +- [Introduction to RSocket](https://www.baeldung.com/rsocket) diff --git a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java index 496b3fc5c9..a67078db06 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java @@ -61,9 +61,9 @@ public class FireNForgetClient { * @return List of random floats */ private List generateData() { - List dataList = new ArrayList<>(WIND_DATA_LENGTH); + List dataList = new ArrayList<>(DATA_LENGTH); float velocity = 0; - for (int i = 0; i < WIND_DATA_LENGTH; i++) { + for (int i = 0; i < DATA_LENGTH; i++) { velocity += Math.random(); dataList.add(velocity); } diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java index e97192bdf0..085f9874fa 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java @@ -21,7 +21,7 @@ public class ReqStreamClient { public Flux getDataStream() { return socket - .requestStream(DefaultPayload.create(WIND_DATA_STREAM_NAME)) + .requestStream(DefaultPayload.create(DATA_STREAM_NAME)) .map(Payload::getData) .map(buf -> buf.getFloat()) .onErrorReturn(null); diff --git a/rsocket/src/main/java/com/baeldung/rsocket/Server.java b/rsocket/src/main/java/com/baeldung/rsocket/Server.java index b5718ab36d..42243da39f 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/Server.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/Server.java @@ -1,6 +1,6 @@ package com.baeldung.rsocket; -import com.baeldung.rsocket.support.WindDataPublisher; +import com.baeldung.rsocket.support.DataPublisher; import static com.baeldung.rsocket.support.Constants.*; import com.baeldung.rsocket.support.GameController; import io.rsocket.AbstractRSocket; @@ -19,7 +19,7 @@ public class Server { private static final Logger LOG = LoggerFactory.getLogger(Server.class); private final Disposable server; - private final WindDataPublisher windDataPublisher = new WindDataPublisher(); + private final DataPublisher dataPublisher = new DataPublisher(); private final GameController gameController; public Server() { @@ -34,7 +34,7 @@ public class Server { } public void dispose() { - windDataPublisher.complete(); + dataPublisher.complete(); this.server.dispose(); } @@ -67,7 +67,7 @@ public class Server { @Override public Mono fireAndForget(Payload payload) { try { - windDataPublisher.publish(payload); // forward the payload + dataPublisher.publish(payload); // forward the payload return Mono.empty(); } catch (Exception x) { return Mono.error(x); @@ -78,13 +78,13 @@ public class Server { * Handle Request/Stream messages. Each request returns a new stream. * * @param payload Payload that can be used to determine which stream to return - * @return Flux stream containing simulated wind speed data + * @return Flux stream containing simulated measurement data */ @Override public Flux requestStream(Payload payload) { String streamName = payload.getDataUtf8(); - if (WIND_DATA_STREAM_NAME.equals(streamName)) { - return Flux.from(windDataPublisher); + if (DATA_STREAM_NAME.equals(streamName)) { + return Flux.from(dataPublisher); } return Flux.error(new IllegalArgumentException(streamName)); } diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java index 01bb374b4e..4ffc4f6483 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java @@ -4,7 +4,7 @@ public interface Constants { int TCP_PORT = 7101; String ERROR_MSG = "error"; - int WIND_DATA_LENGTH = 30; - String WIND_DATA_STREAM_NAME = "wind-data"; + int DATA_LENGTH = 30; + String DATA_STREAM_NAME = "data"; int SHOT_COUNT = 10; } diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java b/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java similarity index 91% rename from rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java rename to rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java index 2ad5b5144b..3e74da8317 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java @@ -7,7 +7,7 @@ import org.reactivestreams.Subscriber; /** * Simple PUblisher to provide async data to Flux stream */ -public class WindDataPublisher implements Publisher { +public class DataPublisher implements Publisher { private Subscriber subscriber; 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-ops/pom.xml b/spring-boot-ops/pom.xml index 57779c3f8e..9717a352d3 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -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/pom.xml b/spring-boot/pom.xml index 87c782b044..e6866b5a8f 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -162,6 +162,12 @@ javax.validation validation-api + + + org.modelmapper + modelmapper + ${modelmapper.version} + @@ -259,6 +265,7 @@ 5.2.4 18.0 2.2.4 + 2.3.2 diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java b/spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java new file mode 100644 index 0000000000..7684c43648 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java @@ -0,0 +1,20 @@ +package com.baeldung.modelmapper; + +import org.modelmapper.ModelMapper; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class PostApplication { + + public static void main(String[] args) { + SpringApplication.run(PostApplication.class, args); + } + + @Bean + public ModelMapper modelMapper() { + return new ModelMapper(); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java b/spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java new file mode 100644 index 0000000000..c0cbca5220 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java @@ -0,0 +1,91 @@ +package com.baeldung.modelmapper.controller; + +import java.text.ParseException; +import java.util.List; +import java.util.stream.Collectors; + +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +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.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import com.baeldung.modelmapper.dto.PostDto; +import com.baeldung.modelmapper.model.Post; +import com.baeldung.modelmapper.service.IPostService; +import com.baeldung.modelmapper.service.IUserService; + +@Controller +public class PostRestController { + + @Autowired + private IPostService postService; + + @Autowired + private IUserService userService; + + @Autowired + private ModelMapper modelMapper; + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public List getPosts( + @PathVariable("page") int page, + @PathVariable("size") int size, + @PathVariable("sortDir") String sortDir, + @PathVariable("sort") String sort) { + + List posts = postService.getPostsList(page, size, sortDir, sort); + return posts.stream() + .map(post -> convertToDto(post)) + .collect(Collectors.toList()); + } + + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public PostDto createPost(@RequestBody PostDto postDto) throws ParseException { + Post post = convertToEntity(postDto); + Post postCreated = postService.createPost(post); + return convertToDto(postCreated); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public PostDto getPost(@PathVariable("id") Long id) { + return convertToDto(postService.getPostById(id)); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.PUT) + @ResponseStatus(HttpStatus.OK) + public void updatePost(@RequestBody PostDto postDto) throws ParseException { + Post post = convertToEntity(postDto); + postService.updatePost(post); + } + + + private PostDto convertToDto(Post post) { + PostDto postDto = modelMapper.map(post, PostDto.class); + postDto.setSubmissionDate(post.getSubmissionDate(), + userService.getCurrentUser().getPreference().getTimezone()); + return postDto; + } + + private Post convertToEntity(PostDto postDto) throws ParseException { + Post post = modelMapper.map(postDto, Post.class); + post.setSubmissionDate(postDto.getSubmissionDateConverted( + userService.getCurrentUser().getPreference().getTimezone())); + + if (postDto.getId() != null) { + Post oldPost = postService.getPostById(postDto.getId()); + post.setRedditID(oldPost.getRedditID()); + post.setSent(oldPost.isSent()); + } + return post; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java new file mode 100644 index 0000000000..6fe2b23888 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java @@ -0,0 +1,71 @@ +package com.baeldung.modelmapper.dto; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +public class PostDto { + + private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + + private Long id; + + private String title; + + private String url; + + private String date; + + private UserDto user; + + public Date getSubmissionDateConverted(String timezone) throws ParseException { + dateFormat.setTimeZone(TimeZone.getTimeZone(timezone)); + return dateFormat.parse(this.date); + } + + public void setSubmissionDate(Date date, String timezone) { + dateFormat.setTimeZone(TimeZone.getTimeZone(timezone)); + this.date = dateFormat.format(date); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public UserDto getUser() { + return user; + } + + public void setUser(UserDto user) { + this.user = user; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java new file mode 100644 index 0000000000..23110ecbaa --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java @@ -0,0 +1,14 @@ +package com.baeldung.modelmapper.dto; + +public class UserDto { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java new file mode 100644 index 0000000000..be65ce34a2 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java @@ -0,0 +1,98 @@ +package com.baeldung.modelmapper.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Post { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String title; + + private String url; + + private String date; + + private String redditID; + + private Date submissionDate; + + private boolean sent; + + private String userName; + + public Post() { + + } + + public boolean isSent() { + return sent; + } + + public void setSent(boolean sent) { + this.sent = sent; + } + + public String getRedditID() { + return redditID; + } + + public void setRedditID(String redditID) { + this.redditID = redditID; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public Date getSubmissionDate() { + return submissionDate; + } + + public void setSubmissionDate(Date submissionDate) { + this.submissionDate = submissionDate; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/model/Preference.java b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Preference.java new file mode 100644 index 0000000000..0ab5b1eddf --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Preference.java @@ -0,0 +1,32 @@ +package com.baeldung.modelmapper.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Preference { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String timezone; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java b/spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java new file mode 100644 index 0000000000..a458b26f4a --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java @@ -0,0 +1,44 @@ +package com.baeldung.modelmapper.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + @OneToOne + Preference preference; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Preference getPreference() { + return preference; + } + + public void setPreference(Preference preference) { + this.preference = preference; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java b/spring-boot/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java new file mode 100644 index 0000000000..fc3f5733c3 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java @@ -0,0 +1,21 @@ +package com.baeldung.modelmapper.repository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.data.repository.query.Param; + +import com.baeldung.modelmapper.model.Post; +import com.baeldung.modelmapper.model.User; + +public interface PostRepository extends JpaRepository, PagingAndSortingRepository { + + @Query("select u from Post u where u.userName=:userName") + Page findByUser(@Param("userName") String userName, Pageable pageReq); + + default Page findByUser(User user, Pageable pageReq) { + return findByUser(user.getName(), pageReq); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java new file mode 100644 index 0000000000..0182a0da41 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java @@ -0,0 +1,17 @@ +package com.baeldung.modelmapper.service; + +import java.util.List; + +import com.baeldung.modelmapper.model.Post; + +public interface IPostService { + + List getPostsList(int page, int size, String sortDir, String sort); + + void updatePost(Post post); + + Post createPost(Post post); + + Post getPostById(Long id); + +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/IUserService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IUserService.java new file mode 100644 index 0000000000..79934114c1 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IUserService.java @@ -0,0 +1,9 @@ +package com.baeldung.modelmapper.service; + +import com.baeldung.modelmapper.model.User; + +public interface IUserService { + + User getCurrentUser(); + +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java new file mode 100644 index 0000000000..5980c30837 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java @@ -0,0 +1,47 @@ +package com.baeldung.modelmapper.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +import com.baeldung.modelmapper.model.Post; +import com.baeldung.modelmapper.repository.PostRepository; + +@Service +public class PostService implements IPostService { + + @Autowired + private PostRepository postRepository; + + @Autowired + private IUserService userService; + + @Override + public List getPostsList(int page, int size, String sortDir, String sort) { + + PageRequest pageReq + = PageRequest.of(page, size, Sort.Direction.fromString(sortDir), sort); + + Page posts = postRepository.findByUser(userService.getCurrentUser(), pageReq); + return posts.getContent(); + } + + @Override + public void updatePost(Post post) { + postRepository.save(post); + } + + @Override + public Post createPost(Post post) { + return postRepository.save(post); + } + + @Override + public Post getPostById(Long id) { + return postRepository.getOne(id); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java new file mode 100644 index 0000000000..e445f836a4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java @@ -0,0 +1,25 @@ +package com.baeldung.modelmapper.service; + +import org.springframework.stereotype.Service; + +import com.baeldung.modelmapper.model.Preference; +import com.baeldung.modelmapper.model.User; + +@Service +public class UserService implements IUserService { + + @Override + public User getCurrentUser() { + + Preference preference = new Preference(); + preference.setId(1L); + preference.setTimezone("Asia/Calcutta"); + + User user = new User(); + user.setId(1L); + user.setName("Micheal"); + user.setPreference(preference); + + return user; + } +} \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java b/spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java new file mode 100644 index 0000000000..34ec4db783 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.modelmapper; + +import static org.junit.Assert.assertEquals; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import org.junit.Test; +import org.modelmapper.ModelMapper; + +import com.baeldung.modelmapper.dto.PostDto; +import com.baeldung.modelmapper.model.Post; + +public class PostDtoUnitTest { + + private ModelMapper modelMapper = new ModelMapper(); + + @Test + public void whenConvertPostEntityToPostDto_thenCorrect() { + Post post = new Post(); + post.setId(Long.valueOf(1)); + post.setTitle(randomAlphabetic(6)); + post.setUrl("www.test.com"); + + PostDto postDto = modelMapper.map(post, PostDto.class); + assertEquals(post.getId(), postDto.getId()); + assertEquals(post.getTitle(), postDto.getTitle()); + assertEquals(post.getUrl(), postDto.getUrl()); + } + + @Test + public void whenConvertPostDtoToPostEntity_thenCorrect() { + PostDto postDto = new PostDto(); + postDto.setId(Long.valueOf(1)); + postDto.setTitle(randomAlphabetic(6)); + postDto.setUrl("www.test.com"); + + Post post = modelMapper.map(postDto, Post.class); + assertEquals(postDto.getId(), post.getId()); + assertEquals(postDto.getTitle(), post.getTitle()); + assertEquals(postDto.getUrl(), post.getUrl()); + } +} \ No newline at end of file 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-mvc-forms-thymeleaf/README.md b/spring-mvc-forms-thymeleaf/README.md index f0f7e35a98..22f12afbca 100644 --- a/spring-mvc-forms-thymeleaf/README.md +++ b/spring-mvc-forms-thymeleaf/README.md @@ -2,3 +2,4 @@ - [Session Attributes in Spring MVC](http://www.baeldung.com/spring-mvc-session-attributes) - [Binding a List in Thymeleaf](http://www.baeldung.com/thymeleaf-list) + diff --git a/spring-mvc-forms-thymeleaf/pom.xml b/spring-mvc-forms-thymeleaf/pom.xml index 67a2696c8a..504ad1dcb2 100644 --- a/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-mvc-forms-thymeleaf/pom.xml @@ -9,10 +9,10 @@ spring forms examples using thymeleaf - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 442a533d1b..3199118281 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -8,7 +8,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Spring MVC Tutorial](http://www.baeldung.com/spring-mvc-tutorial) - [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) - [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data) - [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind) diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 22ddabb4ea..5240ae24e7 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -8,10 +8,10 @@ war - 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-rest-angular/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java index d6fe719311..fd10643c53 100644 --- a/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java +++ b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java @@ -6,12 +6,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.web.filter.ShallowEtagHeaderFilter; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootApplication @EnableAutoConfiguration @Import(PersistenceConfig.class) -public class Application extends WebMvcConfigurerAdapter { +public class Application implements WebMvcConfigurer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java index 4d65c02fff..1473d44b92 100644 --- a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java +++ b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java @@ -1,62 +1,66 @@ package org.baeldung.web.service; +import static io.restassured.RestAssured.given; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsCollectionContaining.hasItems; +import static org.hamcrest.core.IsEqual.equalTo; + import org.apache.commons.lang3.RandomStringUtils; import org.baeldung.web.main.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; -import static io.restassured.RestAssured.given; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsCollectionContaining.hasItems; -import static org.hamcrest.core.IsEqual.equalTo; - @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class StudentServiceIntegrationTest { + + @LocalServerPort + int port; - private static final String ENDPOINT = "http://localhost:8080/student/get"; + private static final String ENDPOINT = "http://localhost:%s/student/get"; @Test public void givenRequestForStudents_whenPageIsOne_expectContainsNames() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat() + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat() .body("content.name", hasItems("Bryan", "Ben")); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectTwoItems() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("size", equalTo(2)); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat().body("size", equalTo(2)); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectNumberOfElementsTwo() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("numberOfElements", equalTo(2)); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat().body("numberOfElements", equalTo(2)); } @Test public void givenRequestForStudents_whenResourcesAreRetrievedPaged_thenExpect200() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().statusCode(200); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().statusCode(200); } @Test public void givenRequestForStudents_whenPageOfResourcesAreRetrievedOutOfBounds_thenExpect500() { - given().params("page", "1000", "size", "2").get(ENDPOINT).then().statusCode(500); + given().params("page", "1000", "size", "2").get(String.format(ENDPOINT, port)).then().statusCode(500); } @Test public void givenRequestForStudents_whenPageNotValid_thenExpect500() { - given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(ENDPOINT).then().statusCode(500); + given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(String.format(ENDPOINT, port)).then().statusCode(500); } @Test public void givenRequestForStudents_whenPageSizeIsFive_expectFiveItems() { - given().params("page", "0", "size", "5").get(ENDPOINT).then().body("content.size()", is(5)); + given().params("page", "0", "size", "5").get(String.format(ENDPOINT, port)).then().body("content.size()", is(5)); } @Test public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("first", equalTo(true)); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat().body("first", equalTo(true)); } } diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index a5d72372f7..d429e17671 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -19,7 +19,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) - [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring) - +- [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) ### Build the Project diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index 6f790f1f48..70fea91f31 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/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 diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml index 8b7ce1770d..540b3d08eb 100644 --- a/spring-rest-shell/pom.xml +++ b/spring-rest-shell/pom.xml @@ -8,10 +8,10 @@ A simple project to demonstrate Spring REST Shell features. - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index e5de463999..d301957eb9 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -8,10 +8,10 @@ war - 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-rest-template/.gitignore b/spring-rest-template/.gitignore deleted file mode 100644 index afdfaa6ded..0000000000 --- a/spring-rest-template/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -*/.idea/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/spring-rest-template/README.md b/spring-rest-template/README.md deleted file mode 100644 index 2c31796080..0000000000 --- a/spring-rest-template/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Spring REST Template Example Project - -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: -- [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload) -- [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template) diff --git a/spring-rest-template/checkstyle.xml b/spring-rest-template/checkstyle.xml deleted file mode 100644 index 85063a7570..0000000000 --- a/spring-rest-template/checkstyle.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/spring-rest-template/pom.xml b/spring-rest-template/pom.xml deleted file mode 100644 index d86e208987..0000000000 --- a/spring-rest-template/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - 4.0.0 - com.baeldung - spring-rest-template - 0.1-SNAPSHOT - spring-rest-template - jar - - - parent-boot-2.0-temp - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp - - - - - - - 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 ea4cfc26d7..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 diff --git a/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java index d811045733..191719b084 100644 --- a/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -43,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>(){}); @@ -61,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(); @@ -80,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); } @@ -94,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/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java deleted file mode 100644 index 853e417d46..0000000000 --- a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.sampleapp.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/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/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java index e659897303..f04106c1e1 100644 --- a/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.web.log.app.Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = { CustomApplication.class, ImageApplication.class, PropertyEditorApplication.class, - ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.Application.class, + ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.UploadApplication.class, MainApplication.class}) public class SpringContextIntegrationTest { diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md index bf8c56e6ec..1c8ddf73f9 100644 --- a/spring-resttemplate/README.md +++ b/spring-resttemplate/README.md @@ -7,4 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) - [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate) - [Spring RestTemplate Error Handling](http://www.baeldung.com/spring-rest-template-error-handling) -- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) \ No newline at end of file +- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) +- [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template) diff --git a/spring-resttemplate/pom.xml b/spring-resttemplate/pom.xml index 2c404a7e8c..9a0978f120 100644 --- a/spring-resttemplate/pom.xml +++ b/spring-resttemplate/pom.xml @@ -8,10 +8,10 @@ war - 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-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index c072bf0f99..0a40b0b324 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -11,10 +11,10 @@ Spring Security MVC Boot - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -36,7 +36,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 org.springframework.boot diff --git a/spring-security-mvc-boot/src/main/resources/templates/private.html b/spring-security-mvc-boot/src/main/resources/templates/private.html index 5af8c7a13e..035d84bbbd 100644 --- a/spring-security-mvc-boot/src/main/resources/templates/private.html +++ b/spring-security-mvc-boot/src/main/resources/templates/private.html @@ -1,6 +1,6 @@ + xmlns:sec="http://www.thymeleaf.org/extras/spring-security"> Private diff --git a/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java b/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java similarity index 98% rename from spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java rename to spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java index 8207363a70..bd0c14ca1f 100644 --- a/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java +++ b/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java @@ -36,7 +36,7 @@ import com.baeldung.util.DummyContentUtil; @WebAppConfiguration @ContextConfiguration @DirtiesContext -public class SpringDataWithSecurityUnitTest { +public class SpringDataWithSecurityIntegrationTest { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); @Autowired private ServletContext servletContext; diff --git a/spring-security-openid/pom.xml b/spring-security-openid/pom.xml index 6a946792ba..4343996e02 100644 --- a/spring-security-openid/pom.xml +++ b/spring-security-openid/pom.xml @@ -9,10 +9,10 @@ Spring OpenID sample 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-security-openid/src/main/resources/application.properties.sample.properties b/spring-security-openid/src/main/resources/application.properties similarity index 100% rename from spring-security-openid/src/main/resources/application.properties.sample.properties rename to spring-security-openid/src/main/resources/application.properties diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index d9b6a760b2..c396948a59 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -15,6 +15,5 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring Security Context Propagation with @Async](http://www.baeldung.com/spring-security-async-principal-propagation) - [Servlet 3 Async Support with Spring MVC and Spring Security](http://www.baeldung.com/spring-mvc-async-security) - [Intro to Spring Security Expressions](http://www.baeldung.com/spring-security-expressions) -- [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) -- [Error Handling for REST with Spring 3](http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/) +- [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) - [Spring Security for a REST API](http://www.baeldung.com/securing-a-restful-web-service-with-spring-security) diff --git a/spring-security-sso/pom.xml b/spring-security-sso/pom.xml index 4deab01464..4b297a91b5 100644 --- a/spring-security-sso/pom.xml +++ b/spring-security-sso/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -24,7 +24,7 @@ 3.1.0 2.3.3.RELEASE - 2.0.1.RELEASE + 2.1.1.RELEASE diff --git a/spring-security-sso/spring-security-sso-ui-2/pom.xml b/spring-security-sso/spring-security-sso-ui-2/pom.xml index 1f9a5754ae..e4ccb82fea 100644 --- a/spring-security-sso/spring-security-sso-ui-2/pom.xml +++ b/spring-security-sso/spring-security-sso-ui-2/pom.xml @@ -37,7 +37,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 diff --git a/spring-security-sso/spring-security-sso-ui/pom.xml b/spring-security-sso/spring-security-sso-ui/pom.xml index 56131749ba..a946db4c3b 100644 --- a/spring-security-sso/spring-security-sso-ui/pom.xml +++ b/spring-security-sso/spring-security-sso-ui/pom.xml @@ -38,7 +38,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 diff --git a/spring-security-thymeleaf/pom.xml b/spring-security-thymeleaf/pom.xml index 314783ebf2..d8b476683a 100644 --- a/spring-security-thymeleaf/pom.xml +++ b/spring-security-thymeleaf/pom.xml @@ -11,10 +11,10 @@ Spring Security with Thymeleaf tutorial - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -43,7 +43,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 diff --git a/spring-session/README.md b/spring-session/README.md index 30f70996cf..505d043e75 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -3,5 +3,5 @@ ## Spring Session Examples ### Relevant Articles: -- [Introduction to Spring Session](http://www.baeldung.com/spring-session) -- [Spring Session with JDBC](http://www.baeldung.com/spring-session-jdbc) +- [Guide to Spring Session](https://www.baeldung.com/spring-session) +- [Spring Session with JDBC](https://www.baeldung.com/spring-session-jdbc) diff --git a/spring-session/spring-session-jdbc/pom.xml b/spring-session/spring-session-jdbc/pom.xml index a595a94914..ce6b5f5908 100644 --- a/spring-session/spring-session-jdbc/pom.xml +++ b/spring-session/spring-session-jdbc/pom.xml @@ -15,10 +15,10 @@ - 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-vault/pom.xml b/spring-vault/pom.xml index 6a7db5dd71..aad6da1cc3 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -13,10 +13,10 @@ Spring Vault sample project - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -41,27 +41,8 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - - - - - - UTF-8 - 2.0.1.RELEASE + 2.1.1.RELEASE diff --git a/spring-webflux-amqp/pom.xml b/spring-webflux-amqp/pom.xml index e4e0d55ce3..4faa165c50 100755 --- a/spring-webflux-amqp/pom.xml +++ b/spring-webflux-amqp/pom.xml @@ -11,10 +11,10 @@ Spring WebFlux AMQP Sample - 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-webflux-amqp/src/main/resources/application.yml b/spring-webflux-amqp/src/main/resources/application.yml index 3f527ce4c5..702aaba357 100755 --- a/spring-webflux-amqp/src/main/resources/application.yml +++ b/spring-webflux-amqp/src/main/resources/application.yml @@ -1,6 +1,6 @@ spring: rabbitmq: - host: 192.168.99.100 + host: localhost port: 5672 username: guest password: guest diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 1111c0aa0c..c34ffa3636 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -10,10 +10,10 @@ Vaadin - 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/vaadin/src/main/resources/application.properties b/vaadin/src/main/resources/application.properties new file mode 100644 index 0000000000..1cb7086b82 --- /dev/null +++ b/vaadin/src/main/resources/application.properties @@ -0,0 +1,2 @@ +#Vaadin supports spring-boot 2.1 properly from V8 onwards (according to this comment https://github.com/vaadin/spring/issues/331#issuecomment-435128475) +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/vavr/pom.xml b/vavr/pom.xml index fa8eff1ce7..ae495e9830 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -7,10 +7,10 @@ vavr - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2