From 445fee41b3925c4bd8272068e432263ec06d378c Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Sun, 30 Dec 2018 23:38:13 +0100 Subject: [PATCH 001/254] java web application without web.xml - servlets 3.0 --- javax-servlets-3/.gitignore | 6 +++ javax-servlets-3/Dockerfile | 2 + javax-servlets-3/README.md | 9 ++++ javax-servlets-3/pom.xml | 51 +++++++++++++++++++ .../servlets3/spring/AppInitializer.java | 27 ++++++++++ .../servlets3/spring/config/AppConfig.java | 11 ++++ .../controllers/UppercaseController.java | 17 +++++++ .../web/filters/EmptyParamFilter.java | 44 ++++++++++++++++ .../servlets3/web/listeners/AppListener.java | 21 ++++++++ .../web/listeners/RequestListener.java | 24 +++++++++ .../web/servlets/CounterServlet.java | 27 ++++++++++ .../web/servlets/UppercaseServlet.java | 26 ++++++++++ 12 files changed, 265 insertions(+) create mode 100644 javax-servlets-3/.gitignore create mode 100644 javax-servlets-3/Dockerfile create mode 100644 javax-servlets-3/README.md create mode 100644 javax-servlets-3/pom.xml create mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/AppInitializer.java create mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/config/AppConfig.java create mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/controllers/UppercaseController.java create mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java create mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/AppListener.java create mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/RequestListener.java create mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/CounterServlet.java create mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/UppercaseServlet.java diff --git a/javax-servlets-3/.gitignore b/javax-servlets-3/.gitignore new file mode 100644 index 0000000000..dfbd063287 --- /dev/null +++ b/javax-servlets-3/.gitignore @@ -0,0 +1,6 @@ +# Created by .ignore support plugin (hsz.mobi) +.idea +classes +target +*.iml +out \ No newline at end of file diff --git a/javax-servlets-3/Dockerfile b/javax-servlets-3/Dockerfile new file mode 100644 index 0000000000..97cc1897dd --- /dev/null +++ b/javax-servlets-3/Dockerfile @@ -0,0 +1,2 @@ +FROM tomcat +ADD ./target/javax-servlets-3-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/ \ No newline at end of file diff --git a/javax-servlets-3/README.md b/javax-servlets-3/README.md new file mode 100644 index 0000000000..ff310b5928 --- /dev/null +++ b/javax-servlets-3/README.md @@ -0,0 +1,9 @@ +## Build with maven: +mvn package + +## Run with Tomcat on Docker container: +docker build --tag my-tomcat . +docker run -it --rm -p 8080:8080 my-tomcat + +### Relevant Articles: +- [Java Web Application Without Web.xml] diff --git a/javax-servlets-3/pom.xml b/javax-servlets-3/pom.xml new file mode 100644 index 0000000000..2b4fc37fc4 --- /dev/null +++ b/javax-servlets-3/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + javax-servlets-3 + 1.0-SNAPSHOT + javax-servlets-3 + war + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + + 4.0.1 + 5.1.3.RELEASE + + + + + org.apache.maven.plugins + maven-war-plugin + 3.1.0 + + + default-war + prepare-package + + false + + + + + + + diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/AppInitializer.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/AppInitializer.java new file mode 100644 index 0000000000..837d439cf4 --- /dev/null +++ b/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/AppInitializer.java @@ -0,0 +1,27 @@ +package com.baeldung.servlets3.spring; + +import com.baeldung.servlets3.spring.config.AppConfig; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class AppInitializer implements WebApplicationInitializer { + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.register(AppConfig.class); + + servletContext.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = servletContext.addServlet("spring-dispatcher", + new DispatcherServlet(context)); + + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/spring/*"); + } +} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/config/AppConfig.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/config/AppConfig.java new file mode 100644 index 0000000000..0088bad770 --- /dev/null +++ b/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/config/AppConfig.java @@ -0,0 +1,11 @@ +package com.baeldung.servlets3.spring.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@Configuration +@EnableWebMvc +@ComponentScan("com.baeldung.servlets3.spring") +public class AppConfig { +} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/controllers/UppercaseController.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/controllers/UppercaseController.java new file mode 100644 index 0000000000..74585e6b5e --- /dev/null +++ b/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/controllers/UppercaseController.java @@ -0,0 +1,17 @@ +package com.baeldung.servlets3.spring.controllers; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/uppercase") +public class UppercaseController { + + @GetMapping(produces = "text/html") + public String getUppercase(@RequestParam(required = false)String param) { + String response = param != null ? param.toUpperCase() : "Missing param"; + return "From Spring: " + response; + } +} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java new file mode 100644 index 0000000000..2c9f603d2c --- /dev/null +++ b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java @@ -0,0 +1,44 @@ +package com.baeldung.servlets3.web.filters; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import java.io.IOException; +import java.io.PrintWriter; + +@WebFilter(servletNames = { "uppercaseServlet" }, filterName = "emptyParamFilter") +public class EmptyParamFilter implements Filter { + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, + FilterChain filterChain) throws IOException, ServletException { + String inputString = servletRequest.getParameter("input"); + + if (inputString == null || inputString.isEmpty()) { + response(servletResponse); + } else { + filterChain.doFilter(servletRequest, servletResponse); + } + } + + private void response(ServletResponse response) throws IOException { + response.setContentType("text/html"); + + PrintWriter out = response.getWriter(); + + out.println("Missing input parameter"); + } + + @Override + public void destroy() { + } + +} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/AppListener.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/AppListener.java new file mode 100644 index 0000000000..d61af65c31 --- /dev/null +++ b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/AppListener.java @@ -0,0 +1,21 @@ +package com.baeldung.servlets3.web.listeners; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +@WebListener +public class AppListener implements ServletContextListener { + + @Override + public void contextInitialized(ServletContextEvent event) { + ServletContext context = event.getServletContext(); + context.setAttribute("counter", 0); + } + + @Override + public void contextDestroyed(ServletContextEvent event) { + + } +} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/RequestListener.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/RequestListener.java new file mode 100644 index 0000000000..aeebf482fb --- /dev/null +++ b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/RequestListener.java @@ -0,0 +1,24 @@ +package com.baeldung.servlets3.web.listeners; + +import javax.servlet.ServletContext; +import javax.servlet.ServletRequestEvent; +import javax.servlet.ServletRequestListener; +import javax.servlet.annotation.WebListener; +import javax.servlet.http.HttpServletRequest; + +@WebListener +public class RequestListener implements ServletRequestListener { + + @Override + public void requestInitialized(ServletRequestEvent event) { + } + + @Override + public void requestDestroyed(ServletRequestEvent event) { + HttpServletRequest request = (HttpServletRequest)event.getServletRequest(); + if (!request.getServletPath().equals("/counter")) { + ServletContext context = event.getServletContext(); + context.setAttribute("counter", (int)context.getAttribute("counter") + 1); + } + } +} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/CounterServlet.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/CounterServlet.java new file mode 100644 index 0000000000..4bb92bbf77 --- /dev/null +++ b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/CounterServlet.java @@ -0,0 +1,27 @@ +package com.baeldung.servlets3.web.servlets; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +@WebServlet(urlPatterns = "/counter", name = "counterServlet") +public class CounterServlet extends HttpServlet { + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { + doGet(request, response); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.setContentType("text/html"); + + PrintWriter out = response.getWriter(); + + int count = (int)request.getServletContext().getAttribute("counter"); + + out.println("Request counter: " + count); + } + +} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/UppercaseServlet.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/UppercaseServlet.java new file mode 100644 index 0000000000..9b948cd994 --- /dev/null +++ b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/UppercaseServlet.java @@ -0,0 +1,26 @@ +package com.baeldung.servlets3.web.servlets; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +@WebServlet(urlPatterns = "/uppercase", name = "uppercaseServlet") +public class UppercaseServlet extends HttpServlet { + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { + doGet(request, response); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + String inputString = request.getParameter("input").toUpperCase(); + + response.setContentType("text/html"); + + PrintWriter out = response.getWriter(); + + out.println(inputString); + } +} From 96d4ae478d9f6f82cd9785ec9f64b5728385acc4 Mon Sep 17 00:00:00 2001 From: mikr Date: Fri, 18 Jan 2019 00:23:08 +0100 Subject: [PATCH 002/254] BAEL-2217 forEach within forEach --- .../kotlin/com/baeldung/forEach/forEach.kt | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt b/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt new file mode 100644 index 0000000000..ef56009c71 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt @@ -0,0 +1,61 @@ +package com.baeldung.forEach + + +class Country(val name : String, val cities : List) + +class City(val name : String, val streets : List) + +class World { + + private val streetsOfAmsterdam = listOf("Herengracht", "Prinsengracht") + private val streetsOfBerlin = listOf("Unter den Linden","Tiergarten") + private val streetsOfMaastricht = listOf("Grote Gracht", "Vrijthof") + private val countries = listOf( + Country("Netherlands", listOf(City("Maastricht", streetsOfMaastricht), + City("Amsterdam", streetsOfAmsterdam))), + Country("Germany", listOf(City("Berlin", streetsOfBerlin)))) + + fun allCountriesIt() { + countries.forEach { println(it.name) } + } + + fun allCountriesItExplicit() { + countries.forEach { it -> println(it.name) } + } + + //here we cannot refer to 'it' anymore inside the forEach + fun allCountriesExplicit() { + countries.forEach { c -> println(c.name) } + } + + fun allNested() { + countries.forEach { + println(it.name) + it.cities.forEach { + println(" ${it.name}") + it.streets.forEach { println(" $it") } + } + } + } + + fun allTable() { + countries.forEach { c -> + c.cities.forEach { p -> + p.streets.forEach { println("${c.name} ${p.name} $it") } + } + } + } +} + +fun main(args : Array) { + + val world = World() + + world.allCountriesExplicit() + + world.allNested() + + world.allTable() +} + + From f5c4e3af74da4a636e558615a20ba0d366698ad5 Mon Sep 17 00:00:00 2001 From: Venkata Kiran Surapaneni Date: Sun, 20 Jan 2019 00:08:52 -0500 Subject: [PATCH 003/254] BAEL-2339 || ResultSet Demo BAEL-2339 || ResultSet Demo --- .../main/java/com/baeldung/jdbc/Employee.java | 6 +- .../com/baeldung/jdbc/ResultSetLiveTest.java | 325 ++++++++++++++++++ 2 files changed, 330 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java index 749855ca3b..8f3fce0378 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java @@ -47,5 +47,9 @@ public class Employee { public void setPosition(String position) { this.position = position; } - + + @Override + public boolean equals(Object obj) { + return this.getId() == ((Employee) obj).getId(); + } } diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java new file mode 100644 index 0000000000..369d5e9222 --- /dev/null +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java @@ -0,0 +1,325 @@ +package com.baeldung.jdbc; + +import static org.junit.Assert.assertEquals; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class ResultSetLiveTest { + + private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class); + + private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer"); + + private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer"); + + private final Employee expectedEmployee2 = new Employee(2, "Chris", 925.0, "DBA"); + + private final int rowCount = 2; + + private static Connection dbConnection; + + @BeforeClass + public static void setup() throws ClassNotFoundException, SQLException { + Class.forName("com.mysql.cj.jdbc.Driver"); + dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB?noAccessToProcedureBodies=true", "user1", "pass"); + String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; + try (Statement stmt = dbConnection.createStatement()) { + stmt.execute(tableSql); + try (PreparedStatement pstmt = dbConnection.prepareStatement("INSERT INTO employees(name, position, salary) values ('John', 'Developer', 1000.0)")) { + pstmt.executeUpdate(); + } + } + } + + @Test + public void givenDbConnectionA_whenARetreiveByColumnNames_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } + + assertEquals("Employee information retreived by column names.", expectedEmployee1, employee); + } + + @Test + public void givenDbConnectionB_whenBRetreiveByColumnIds_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + Integer empId = rs.getInt(1); + String name = rs.getString(2); + String position = rs.getString(3); + Double salary = rs.getDouble(4); + employee = new Employee(empId, name, salary, position); + } + } + + assertEquals("Employee information retreived by column ids.", employee, expectedEmployee1); + } + + @Test + public void givenDbConnectionD_whenInsertRow_thenCorrect() throws SQLException { + int rowCount = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.moveToInsertRow(); + rs.updateString("name", "Venkat"); + rs.updateString("position", "DBA"); + rs.updateDouble("salary", 925.0); + rs.insertRow(); + rs.moveToCurrentRow(); + rs.last(); + rowCount = rs.getRow(); + } + + assertEquals("Row Count after inserting a row", rowCount, 2); + } + + private Employee populateResultSet(ResultSet rs) throws SQLException { + Employee employee; + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + return employee; + } + + @Test + public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException { + int numOfRows = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.last(); + numOfRows = rs.getRow(); + } + + assertEquals("Num of rows", numOfRows, rowCount); + } + + @Test + public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException { + Employee secondEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.absolute(2); + secondEmployee = populateResultSet(rs); + } + + assertEquals("Absolute navigation", secondEmployee, expectedEmployee2); + } + + @Test + public void givenDbConnectionH_whenLastNavigation_thenCorrect() throws SQLException { + Employee secondEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.last(); + secondEmployee = populateResultSet(rs); + } + + assertEquals("Using Last", secondEmployee, expectedEmployee2); + } + + @Test + public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException { + Employee firstEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.beforeFirst(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.first(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + while (rs.previous()) { + Employee employee = populateResultSet(rs); + } + rs.afterLast(); + while (rs.previous()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + while (rs.previous()) { + firstEmployee = populateResultSet(rs); + } + } + + assertEquals("Several Navigation Options", firstEmployee, updatedEmployee1); + } + + @Test + public void givenDbConnectionJ_whenClosedCursor_thenCorrect() throws SQLException { + int numOfRows = 0; + dbConnection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); + try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT)) { + dbConnection.setAutoCommit(false); + pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Chris',2100.0,'Manager')"); + ResultSet rs = pstmt.executeQuery("select * from employees"); + dbConnection.commit(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + numOfRows = rs.getRow(); + } + + assertEquals("Inserted using close cursor after commit", numOfRows, 3); + } + + @Test + public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException { + int numOfRows = 0; + try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT)) { + dbConnection.setAutoCommit(false); + pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Michael',1200.0,'Consultant')"); + ResultSet rs = pstmt.executeQuery("select * from employees"); + dbConnection.commit(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + numOfRows = rs.getRow(); + } + + assertEquals("Inserted using hold cursor after commit", numOfRows, 4); + } + + @Test + public void givenDbConnectionL_whenDelete_thenCorrect() throws SQLException { + int numOfRows = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.absolute(3); + rs.deleteRow(); + rs.last(); + numOfRows = rs.getRow(); + } + + assertEquals("Deleted row", numOfRows, 3); + } + + @Test + public void givenDbConnectionC_whenUpdate_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + rs.updateDouble("salary", 1100.0); + rs.updateRow(); + rs.refreshRow(); + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } + + assertEquals("Employee information updated successfully.", employee, updatedEmployee1); + } + + @Test + public void givenDbConnectionE_whenDBMetaInfo_thenCorrect() throws SQLException { + DatabaseMetaData dbmd = dbConnection.getMetaData(); + boolean supportsTypeForward = dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY); + boolean supportsTypeScrollSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE); + boolean supportsTypeScrollInSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE); + boolean supportsCloseCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); + boolean supportsHoldCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); + boolean concurrency4TypeFwdNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + boolean concurrency4TypeFwdNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollInSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollInSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + boolean concurrency4TypeScrollSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + int rsHoldability = dbmd.getResultSetHoldability(); + + assertEquals("checking scroll sensitivity and concur updates : ", concurrency4TypeScrollInSensitiveNConcurUpdatable, true); + } + + @Test + public void givenDbConnectionF_whenRSMetaInfo_thenCorrect() throws SQLException { + int columnCount = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + ResultSetMetaData metaData = rs.getMetaData(); + columnCount = metaData.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String catalogName = metaData.getCatalogName(i); + String className = metaData.getColumnClassName(i); + String label = metaData.getColumnLabel(i); + String name = metaData.getColumnName(i); + String typeName = metaData.getColumnTypeName(i); + Integer type = metaData.getColumnType(i); + String tableName = metaData.getTableName(i); + String schemaName = metaData.getSchemaName(i); + boolean isAutoIncrement = metaData.isAutoIncrement(i); + boolean isCaseSensitive = metaData.isCaseSensitive(i); + boolean isCurrency = metaData.isCurrency(i); + boolean isDefiniteWritable = metaData.isDefinitelyWritable(i); + boolean isReadOnly = metaData.isReadOnly(i); + boolean isSearchable = metaData.isSearchable(i); + boolean isReadable = metaData.isReadOnly(i); + boolean isSigned = metaData.isSigned(i); + boolean isWritable = metaData.isWritable(i); + int nullable = metaData.isNullable(i); + } + } + + assertEquals("column count", columnCount, 4); + } + + @Test + public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException { + PreparedStatement pstmt = null; + ResultSet rs = null; + List listOfEmployees = new ArrayList(); + try { + pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + pstmt.setFetchSize(2); + rs = pstmt.executeQuery(); + rs.setFetchSize(1); + while (rs.next()) { + Employee employee = populateResultSet(rs); + listOfEmployees.add(employee); + } + } catch (Exception e) { + throw e; + } finally { + if (rs != null) + rs.close(); + if (pstmt != null) + pstmt.close(); + } + + assertEquals(listOfEmployees.size(), 3); + } + + @AfterClass + public static void closeConnection() throws SQLException { + PreparedStatement deleteStmt = dbConnection.prepareStatement("drop table employees", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + deleteStmt.execute(); + dbConnection.close(); + } +} From eb8f0cf66c5464eb6664731477305d9ea16ffd81 Mon Sep 17 00:00:00 2001 From: Venkata Kiran Surapaneni Date: Tue, 22 Jan 2019 02:20:08 -0500 Subject: [PATCH 004/254] Fixed unit tests and equals method for ResultSetLiveTest --- .../main/java/com/baeldung/jdbc/Employee.java | 98 ++-- .../com/baeldung/jdbc/ResultSetLiveTest.java | 551 +++++++++--------- 2 files changed, 344 insertions(+), 305 deletions(-) diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java index 8f3fce0378..88af4902b5 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java @@ -1,55 +1,71 @@ package com.baeldung.jdbc; +import java.util.Objects; + public class Employee { - private int id; - private String name; - private String position; - private double salary; + private int id; + private String name; + private String position; + private double salary; - public Employee() { - } + public Employee() { + } - public Employee(int id, String name, double salary, String position) { - this.id = id; - this.name = name; - this.salary = salary; - this.position = position; - } + public Employee(int id, String name, double salary, String position) { + this.id = id; + this.name = name; + this.salary = salary; + this.position = position; + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public double getSalary() { - return salary; - } + public double getSalary() { + return salary; + } - public void setSalary(double salary) { - this.salary = salary; - } + public void setSalary(double salary) { + this.salary = salary; + } - public String getPosition() { - return position; - } + public String getPosition() { + return position; + } + + public void setPosition(String position) { + this.position = position; + } + + @Override + public int hashCode() { + return Objects.hash(id, name, position, salary); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Employee other = (Employee) obj; + return id == other.id && Objects.equals(name, other.name) && Objects.equals(position, other.position) + && Double.doubleToLongBits(salary) == Double.doubleToLongBits(other.salary); + } - public void setPosition(String position) { - this.position = position; - } - - @Override - public boolean equals(Object obj) { - return this.getId() == ((Employee) obj).getId(); - } } diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java index 369d5e9222..553c7f9919 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java @@ -23,303 +23,326 @@ import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ResultSetLiveTest { - private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class); + private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class); - private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer"); + private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer"); - private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer"); + private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer"); - private final Employee expectedEmployee2 = new Employee(2, "Chris", 925.0, "DBA"); + private final Employee expectedEmployee2 = new Employee(2, "Chris", 925.0, "DBA"); - private final int rowCount = 2; + private final int rowCount = 2; - private static Connection dbConnection; + private static Connection dbConnection; - @BeforeClass - public static void setup() throws ClassNotFoundException, SQLException { - Class.forName("com.mysql.cj.jdbc.Driver"); - dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB?noAccessToProcedureBodies=true", "user1", "pass"); - String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; - try (Statement stmt = dbConnection.createStatement()) { - stmt.execute(tableSql); - try (PreparedStatement pstmt = dbConnection.prepareStatement("INSERT INTO employees(name, position, salary) values ('John', 'Developer', 1000.0)")) { - pstmt.executeUpdate(); - } - } - } + @BeforeClass + public static void setup() throws ClassNotFoundException, SQLException { + Class.forName("com.mysql.cj.jdbc.Driver"); + dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB?noAccessToProcedureBodies=true", + "user1", "pass"); + String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; + try (Statement stmt = dbConnection.createStatement()) { + stmt.execute(tableSql); + try (PreparedStatement pstmt = dbConnection.prepareStatement( + "INSERT INTO employees(name, position, salary) values ('John', 'Developer', 1000.0)")) { + pstmt.executeUpdate(); + } + } + } - @Test - public void givenDbConnectionA_whenARetreiveByColumnNames_thenCorrect() throws SQLException { - Employee employee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - String name = rs.getString("name"); - Integer empId = rs.getInt("emp_id"); - Double salary = rs.getDouble("salary"); - String position = rs.getString("position"); - employee = new Employee(empId, name, salary, position); - } - } + @Test + public void givenDbConnectionA_whenARetreiveByColumnNames_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); + ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } - assertEquals("Employee information retreived by column names.", expectedEmployee1, employee); - } + assertEquals("Employee information retreived by column names.", expectedEmployee1, employee); + } - @Test - public void givenDbConnectionB_whenBRetreiveByColumnIds_thenCorrect() throws SQLException { - Employee employee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - Integer empId = rs.getInt(1); - String name = rs.getString(2); - String position = rs.getString(3); - Double salary = rs.getDouble(4); - employee = new Employee(empId, name, salary, position); - } - } + @Test + public void givenDbConnectionB_whenBRetreiveByColumnIds_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); + ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + Integer empId = rs.getInt(1); + String name = rs.getString(2); + String position = rs.getString(3); + Double salary = rs.getDouble(4); + employee = new Employee(empId, name, salary, position); + } + } - assertEquals("Employee information retreived by column ids.", employee, expectedEmployee1); - } + assertEquals("Employee information retreived by column ids.", expectedEmployee1, employee); + } - @Test - public void givenDbConnectionD_whenInsertRow_thenCorrect() throws SQLException { - int rowCount = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.moveToInsertRow(); - rs.updateString("name", "Venkat"); - rs.updateString("position", "DBA"); - rs.updateDouble("salary", 925.0); - rs.insertRow(); - rs.moveToCurrentRow(); - rs.last(); - rowCount = rs.getRow(); - } + @Test + public void givenDbConnectionD_whenInsertRow_thenCorrect() throws SQLException { + int rowCount = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", + ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.moveToInsertRow(); + rs.updateString("name", "Venkat"); + rs.updateString("position", "DBA"); + rs.updateDouble("salary", 925.0); + rs.insertRow(); + rs.moveToCurrentRow(); + rs.last(); + rowCount = rs.getRow(); + } - assertEquals("Row Count after inserting a row", rowCount, 2); - } + assertEquals("Row Count after inserting a row", 2, rowCount); + } - private Employee populateResultSet(ResultSet rs) throws SQLException { - Employee employee; - String name = rs.getString("name"); - Integer empId = rs.getInt("emp_id"); - Double salary = rs.getDouble("salary"); - String position = rs.getString("position"); - employee = new Employee(empId, name, salary, position); - return employee; - } + private Employee populateResultSet(ResultSet rs) throws SQLException { + Employee employee; + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + return employee; + } - @Test - public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException { - int numOfRows = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.last(); - numOfRows = rs.getRow(); - } + @Test + public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException { + int numOfRows = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", + ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.last(); + numOfRows = rs.getRow(); + } - assertEquals("Num of rows", numOfRows, rowCount); - } + assertEquals("Num of rows", rowCount, numOfRows); + } - @Test - public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException { - Employee secondEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.absolute(2); - secondEmployee = populateResultSet(rs); - } + @Test + public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException { + Employee secondEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", + ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.absolute(2); + secondEmployee = populateResultSet(rs); + } - assertEquals("Absolute navigation", secondEmployee, expectedEmployee2); - } + assertEquals("Absolute navigation", expectedEmployee2, secondEmployee); + } - @Test - public void givenDbConnectionH_whenLastNavigation_thenCorrect() throws SQLException { - Employee secondEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.last(); - secondEmployee = populateResultSet(rs); - } + @Test + public void givenDbConnectionH_whenLastNavigation_thenCorrect() throws SQLException { + Employee secondEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", + ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.last(); + secondEmployee = populateResultSet(rs); + } - assertEquals("Using Last", secondEmployee, expectedEmployee2); - } + assertEquals("Using Last", expectedEmployee2, secondEmployee); + } - @Test - public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException { - Employee firstEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - rs.beforeFirst(); - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - rs.first(); - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - while (rs.previous()) { - Employee employee = populateResultSet(rs); - } - rs.afterLast(); - while (rs.previous()) { - Employee employee = populateResultSet(rs); - } - rs.last(); - while (rs.previous()) { - firstEmployee = populateResultSet(rs); - } - } + @Test + public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException { + Employee firstEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", + ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.beforeFirst(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.first(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + while (rs.previous()) { + Employee employee = populateResultSet(rs); + } + rs.afterLast(); + while (rs.previous()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + while (rs.previous()) { + firstEmployee = populateResultSet(rs); + } + } - assertEquals("Several Navigation Options", firstEmployee, updatedEmployee1); - } + assertEquals("Several Navigation Options", updatedEmployee1, firstEmployee); + } - @Test - public void givenDbConnectionJ_whenClosedCursor_thenCorrect() throws SQLException { - int numOfRows = 0; - dbConnection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); - try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT)) { - dbConnection.setAutoCommit(false); - pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Chris',2100.0,'Manager')"); - ResultSet rs = pstmt.executeQuery("select * from employees"); - dbConnection.commit(); - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - rs.last(); - numOfRows = rs.getRow(); - } + @Test + public void givenDbConnectionJ_whenClosedCursor_thenCorrect() throws SQLException { + int numOfRows = 0; + dbConnection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); + try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, + ResultSet.CLOSE_CURSORS_AT_COMMIT)) { + dbConnection.setAutoCommit(false); + pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Chris',2100.0,'Manager')"); + ResultSet rs = pstmt.executeQuery("select * from employees"); + dbConnection.commit(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + numOfRows = rs.getRow(); + } - assertEquals("Inserted using close cursor after commit", numOfRows, 3); - } + assertEquals("Inserted using close cursor after commit", 3, numOfRows); + } - @Test - public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException { - int numOfRows = 0; - try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT)) { - dbConnection.setAutoCommit(false); - pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Michael',1200.0,'Consultant')"); - ResultSet rs = pstmt.executeQuery("select * from employees"); - dbConnection.commit(); - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - rs.last(); - numOfRows = rs.getRow(); - } + @Test + public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException { + int numOfRows = 0; + try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, + ResultSet.HOLD_CURSORS_OVER_COMMIT)) { + dbConnection.setAutoCommit(false); + pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Michael',1200.0,'Consultant')"); + ResultSet rs = pstmt.executeQuery("select * from employees"); + dbConnection.commit(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + numOfRows = rs.getRow(); + } - assertEquals("Inserted using hold cursor after commit", numOfRows, 4); - } + assertEquals("Inserted using hold cursor after commit", 4, numOfRows); + } - @Test - public void givenDbConnectionL_whenDelete_thenCorrect() throws SQLException { - int numOfRows = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.absolute(3); - rs.deleteRow(); - rs.last(); - numOfRows = rs.getRow(); - } + @Test + public void givenDbConnectionL_whenDelete_thenCorrect() throws SQLException { + int numOfRows = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", + ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.absolute(3); + rs.deleteRow(); + rs.last(); + numOfRows = rs.getRow(); + } - assertEquals("Deleted row", numOfRows, 3); - } + assertEquals("Deleted row", 3, numOfRows); + } - @Test - public void givenDbConnectionC_whenUpdate_thenCorrect() throws SQLException { - Employee employee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - rs.updateDouble("salary", 1100.0); - rs.updateRow(); - rs.refreshRow(); - String name = rs.getString("name"); - Integer empId = rs.getInt("emp_id"); - Double salary = rs.getDouble("salary"); - String position = rs.getString("position"); - employee = new Employee(empId, name, salary, position); - } - } + @Test + public void givenDbConnectionC_whenUpdate_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", + ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + rs.updateDouble("salary", 1100.0); + rs.updateRow(); + rs.refreshRow(); + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } - assertEquals("Employee information updated successfully.", employee, updatedEmployee1); - } + assertEquals("Employee information updated successfully.", updatedEmployee1, employee); + } - @Test - public void givenDbConnectionE_whenDBMetaInfo_thenCorrect() throws SQLException { - DatabaseMetaData dbmd = dbConnection.getMetaData(); - boolean supportsTypeForward = dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY); - boolean supportsTypeScrollSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE); - boolean supportsTypeScrollInSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE); - boolean supportsCloseCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); - boolean supportsHoldCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); - boolean concurrency4TypeFwdNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - boolean concurrency4TypeFwdNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - boolean concurrency4TypeScrollInSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); - boolean concurrency4TypeScrollInSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - boolean concurrency4TypeScrollSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - boolean concurrency4TypeScrollSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - int rsHoldability = dbmd.getResultSetHoldability(); + @Test + public void givenDbConnectionE_whenDBMetaInfo_thenCorrect() throws SQLException { + DatabaseMetaData dbmd = dbConnection.getMetaData(); + boolean supportsTypeForward = dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY); + boolean supportsTypeScrollSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE); + boolean supportsTypeScrollInSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE); + boolean supportsCloseCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); + boolean supportsHoldCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); + boolean concurrency4TypeFwdNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY); + boolean concurrency4TypeFwdNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollInSensitiveNConcurUpdatable = dbmd + .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollInSensitiveNConcurReadOnly = dbmd + .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + boolean concurrency4TypeScrollSensitiveNConcurUpdatable = dbmd + .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollSensitiveNConcurReadOnly = dbmd + .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + int rsHoldability = dbmd.getResultSetHoldability(); - assertEquals("checking scroll sensitivity and concur updates : ", concurrency4TypeScrollInSensitiveNConcurUpdatable, true); - } + assertEquals("checking scroll sensitivity and concur updates : ", true, + concurrency4TypeScrollInSensitiveNConcurUpdatable); + } - @Test - public void givenDbConnectionF_whenRSMetaInfo_thenCorrect() throws SQLException { - int columnCount = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - ResultSetMetaData metaData = rs.getMetaData(); - columnCount = metaData.getColumnCount(); - for (int i = 1; i <= columnCount; i++) { - String catalogName = metaData.getCatalogName(i); - String className = metaData.getColumnClassName(i); - String label = metaData.getColumnLabel(i); - String name = metaData.getColumnName(i); - String typeName = metaData.getColumnTypeName(i); - Integer type = metaData.getColumnType(i); - String tableName = metaData.getTableName(i); - String schemaName = metaData.getSchemaName(i); - boolean isAutoIncrement = metaData.isAutoIncrement(i); - boolean isCaseSensitive = metaData.isCaseSensitive(i); - boolean isCurrency = metaData.isCurrency(i); - boolean isDefiniteWritable = metaData.isDefinitelyWritable(i); - boolean isReadOnly = metaData.isReadOnly(i); - boolean isSearchable = metaData.isSearchable(i); - boolean isReadable = metaData.isReadOnly(i); - boolean isSigned = metaData.isSigned(i); - boolean isWritable = metaData.isWritable(i); - int nullable = metaData.isNullable(i); - } - } + @Test + public void givenDbConnectionF_whenRSMetaInfo_thenCorrect() throws SQLException { + int columnCount = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", + ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + ResultSetMetaData metaData = rs.getMetaData(); + columnCount = metaData.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String catalogName = metaData.getCatalogName(i); + String className = metaData.getColumnClassName(i); + String label = metaData.getColumnLabel(i); + String name = metaData.getColumnName(i); + String typeName = metaData.getColumnTypeName(i); + Integer type = metaData.getColumnType(i); + String tableName = metaData.getTableName(i); + String schemaName = metaData.getSchemaName(i); + boolean isAutoIncrement = metaData.isAutoIncrement(i); + boolean isCaseSensitive = metaData.isCaseSensitive(i); + boolean isCurrency = metaData.isCurrency(i); + boolean isDefiniteWritable = metaData.isDefinitelyWritable(i); + boolean isReadOnly = metaData.isReadOnly(i); + boolean isSearchable = metaData.isSearchable(i); + boolean isReadable = metaData.isReadOnly(i); + boolean isSigned = metaData.isSigned(i); + boolean isWritable = metaData.isWritable(i); + int nullable = metaData.isNullable(i); + } + } - assertEquals("column count", columnCount, 4); - } + assertEquals("column count", 4, columnCount); + } - @Test - public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException { - PreparedStatement pstmt = null; - ResultSet rs = null; - List listOfEmployees = new ArrayList(); - try { - pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - pstmt.setFetchSize(2); - rs = pstmt.executeQuery(); - rs.setFetchSize(1); - while (rs.next()) { - Employee employee = populateResultSet(rs); - listOfEmployees.add(employee); - } - } catch (Exception e) { - throw e; - } finally { - if (rs != null) - rs.close(); - if (pstmt != null) - pstmt.close(); - } - - assertEquals(listOfEmployees.size(), 3); - } + @Test + public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException { + PreparedStatement pstmt = null; + ResultSet rs = null; + List listOfEmployees = new ArrayList(); + try { + pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY); + pstmt.setFetchSize(2); + rs = pstmt.executeQuery(); + rs.setFetchSize(1); + while (rs.next()) { + Employee employee = populateResultSet(rs); + listOfEmployees.add(employee); + } + } catch (Exception e) { + throw e; + } finally { + if (rs != null) + rs.close(); + if (pstmt != null) + pstmt.close(); + } - @AfterClass - public static void closeConnection() throws SQLException { - PreparedStatement deleteStmt = dbConnection.prepareStatement("drop table employees", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); - deleteStmt.execute(); - dbConnection.close(); - } + assertEquals(3, listOfEmployees.size()); + } + + @AfterClass + public static void closeConnection() throws SQLException { + PreparedStatement deleteStmt = dbConnection.prepareStatement("drop table employees", + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + deleteStmt.execute(); + dbConnection.close(); + } } From 48bad8243930c53eb936e1bc37b2126a10302ea2 Mon Sep 17 00:00:00 2001 From: Venkata Kiran Surapaneni Date: Thu, 24 Jan 2019 13:16:56 -0500 Subject: [PATCH 005/254] Fixed issues with adding the 2nd record --- .../com/baeldung/jdbc/ResultSetLiveTest.java | 554 +++++++++--------- 1 file changed, 268 insertions(+), 286 deletions(-) diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java index 553c7f9919..64d64e76f2 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java @@ -20,329 +20,311 @@ import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; +import junit.framework.Assert; + @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ResultSetLiveTest { - private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class); + private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class); - private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer"); + private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer"); - private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer"); + private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer"); - private final Employee expectedEmployee2 = new Employee(2, "Chris", 925.0, "DBA"); + private final Employee expectedEmployee2 = new Employee(2, "Chris", 925.0, "DBA"); - private final int rowCount = 2; + private final int rowCount = 2; - private static Connection dbConnection; + private static Connection dbConnection; - @BeforeClass - public static void setup() throws ClassNotFoundException, SQLException { - Class.forName("com.mysql.cj.jdbc.Driver"); - dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB?noAccessToProcedureBodies=true", - "user1", "pass"); - String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; - try (Statement stmt = dbConnection.createStatement()) { - stmt.execute(tableSql); - try (PreparedStatement pstmt = dbConnection.prepareStatement( - "INSERT INTO employees(name, position, salary) values ('John', 'Developer', 1000.0)")) { - pstmt.executeUpdate(); - } - } - } + @BeforeClass + public static void setup() throws ClassNotFoundException, SQLException { + Class.forName("com.mysql.cj.jdbc.Driver"); + dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB?noAccessToProcedureBodies=true", "user1", "pass"); + String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; + try (Statement stmt = dbConnection.createStatement()) { + stmt.execute(tableSql); + try (PreparedStatement pstmt = dbConnection.prepareStatement("INSERT INTO employees(name, position, salary) values ('John', 'Developer', 1000.0)")) { + pstmt.executeUpdate(); + } + } + } - @Test - public void givenDbConnectionA_whenARetreiveByColumnNames_thenCorrect() throws SQLException { - Employee employee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); - ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - String name = rs.getString("name"); - Integer empId = rs.getInt("emp_id"); - Double salary = rs.getDouble("salary"); - String position = rs.getString("position"); - employee = new Employee(empId, name, salary, position); - } - } + @Test + public void givenDbConnectionA_whenRetreiveByColumnNames_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } - assertEquals("Employee information retreived by column names.", expectedEmployee1, employee); - } + assertEquals("Employee information retreived by column names.", expectedEmployee1, employee); + } - @Test - public void givenDbConnectionB_whenBRetreiveByColumnIds_thenCorrect() throws SQLException { - Employee employee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); - ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - Integer empId = rs.getInt(1); - String name = rs.getString(2); - String position = rs.getString(3); - Double salary = rs.getDouble(4); - employee = new Employee(empId, name, salary, position); - } - } + @Test + public void givenDbConnectionB_whenRetreiveByColumnIds_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + Integer empId = rs.getInt(1); + String name = rs.getString(2); + String position = rs.getString(3); + Double salary = rs.getDouble(4); + employee = new Employee(empId, name, salary, position); + } + } - assertEquals("Employee information retreived by column ids.", expectedEmployee1, employee); - } + assertEquals("Employee information retreived by column ids.", expectedEmployee1, employee); + } - @Test - public void givenDbConnectionD_whenInsertRow_thenCorrect() throws SQLException { - int rowCount = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.moveToInsertRow(); - rs.updateString("name", "Venkat"); - rs.updateString("position", "DBA"); - rs.updateDouble("salary", 925.0); - rs.insertRow(); - rs.moveToCurrentRow(); - rs.last(); - rowCount = rs.getRow(); - } + @Test + public void givenDbConnectionD_whenInsertRow_thenCorrect() throws SQLException { + int rowCount = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.moveToInsertRow(); + rs.updateString("name", "Chris"); + rs.updateString("position", "DBA"); + rs.updateDouble("salary", 925.0); + rs.insertRow(); + rs.moveToCurrentRow(); + rs.last(); + rowCount = rs.getRow(); + } - assertEquals("Row Count after inserting a row", 2, rowCount); - } + assertEquals("Row Count after inserting a row", 2, rowCount); + } - private Employee populateResultSet(ResultSet rs) throws SQLException { - Employee employee; - String name = rs.getString("name"); - Integer empId = rs.getInt("emp_id"); - Double salary = rs.getDouble("salary"); - String position = rs.getString("position"); - employee = new Employee(empId, name, salary, position); - return employee; - } + private Employee populateResultSet(ResultSet rs) throws SQLException { + Employee employee; + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + return employee; + } - @Test - public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException { - int numOfRows = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.last(); - numOfRows = rs.getRow(); - } + @Test + public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException { + int numOfRows = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.last(); + numOfRows = rs.getRow(); + } - assertEquals("Num of rows", rowCount, numOfRows); - } + assertEquals("Num of rows", rowCount, numOfRows); + } - @Test - public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException { - Employee secondEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.absolute(2); - secondEmployee = populateResultSet(rs); - } + @Test + public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException { + Employee secondEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.absolute(2); + secondEmployee = populateResultSet(rs); + } - assertEquals("Absolute navigation", expectedEmployee2, secondEmployee); - } + assertEquals("Absolute navigation", expectedEmployee2, secondEmployee); + } - @Test - public void givenDbConnectionH_whenLastNavigation_thenCorrect() throws SQLException { - Employee secondEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.last(); - secondEmployee = populateResultSet(rs); - } + @Test + public void givenDbConnectionH_whenLastNavigation_thenCorrect() throws SQLException { + Employee secondEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.last(); + secondEmployee = populateResultSet(rs); + } - assertEquals("Using Last", expectedEmployee2, secondEmployee); - } + assertEquals("Using Last", expectedEmployee2, secondEmployee); + } - @Test - public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException { - Employee firstEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - rs.beforeFirst(); - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - rs.first(); - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - while (rs.previous()) { - Employee employee = populateResultSet(rs); - } - rs.afterLast(); - while (rs.previous()) { - Employee employee = populateResultSet(rs); - } - rs.last(); - while (rs.previous()) { - firstEmployee = populateResultSet(rs); - } - } + @Test + public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException { + Employee firstEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.beforeFirst(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.first(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + while (rs.previous()) { + Employee employee = populateResultSet(rs); + } + rs.afterLast(); + while (rs.previous()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + while (rs.previous()) { + firstEmployee = populateResultSet(rs); + } + } - assertEquals("Several Navigation Options", updatedEmployee1, firstEmployee); - } + assertEquals("Several Navigation Options", updatedEmployee1, firstEmployee); + } - @Test - public void givenDbConnectionJ_whenClosedCursor_thenCorrect() throws SQLException { - int numOfRows = 0; - dbConnection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); - try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, - ResultSet.CLOSE_CURSORS_AT_COMMIT)) { - dbConnection.setAutoCommit(false); - pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Chris',2100.0,'Manager')"); - ResultSet rs = pstmt.executeQuery("select * from employees"); - dbConnection.commit(); - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - rs.last(); - numOfRows = rs.getRow(); - } + @Test + public void givenDbConnectionJ_whenClosedCursor_thenCorrect() throws SQLException { + int numOfRows = 0; + dbConnection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); + try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT)) { + dbConnection.setAutoCommit(false); + pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Chris',2100.0,'Manager')"); + ResultSet rs = pstmt.executeQuery("select * from employees"); + dbConnection.commit(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + numOfRows = rs.getRow(); + } - assertEquals("Inserted using close cursor after commit", 3, numOfRows); - } + assertEquals("Inserted using close cursor after commit", 3, numOfRows); + } - @Test - public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException { - int numOfRows = 0; - try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, - ResultSet.HOLD_CURSORS_OVER_COMMIT)) { - dbConnection.setAutoCommit(false); - pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Michael',1200.0,'Consultant')"); - ResultSet rs = pstmt.executeQuery("select * from employees"); - dbConnection.commit(); - while (rs.next()) { - Employee employee = populateResultSet(rs); - } - rs.last(); - numOfRows = rs.getRow(); - } + @Test + public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException { + int numOfRows = 0; + try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT)) { + dbConnection.setAutoCommit(false); + pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Michael',1200.0,'Consultant')"); + ResultSet rs = pstmt.executeQuery("select * from employees"); + dbConnection.commit(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + numOfRows = rs.getRow(); + } - assertEquals("Inserted using hold cursor after commit", 4, numOfRows); - } + assertEquals("Inserted using hold cursor after commit", 4, numOfRows); + } - @Test - public void givenDbConnectionL_whenDelete_thenCorrect() throws SQLException { - int numOfRows = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.absolute(3); - rs.deleteRow(); - rs.last(); - numOfRows = rs.getRow(); - } + @Test + public void givenDbConnectionL_whenDelete_thenCorrect() throws SQLException { + int numOfRows = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.absolute(3); + rs.deleteRow(); + rs.last(); + numOfRows = rs.getRow(); + } - assertEquals("Deleted row", 3, numOfRows); - } + assertEquals("Deleted row", 3, numOfRows); + } - @Test - public void givenDbConnectionC_whenUpdate_thenCorrect() throws SQLException { - Employee employee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - rs.updateDouble("salary", 1100.0); - rs.updateRow(); - rs.refreshRow(); - String name = rs.getString("name"); - Integer empId = rs.getInt("emp_id"); - Double salary = rs.getDouble("salary"); - String position = rs.getString("position"); - employee = new Employee(empId, name, salary, position); - } - } + @Test + public void givenDbConnectionC_whenUpdate_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { - assertEquals("Employee information updated successfully.", updatedEmployee1, employee); - } + Assert.assertEquals(1000.0, rs.getDouble("salary")); - @Test - public void givenDbConnectionE_whenDBMetaInfo_thenCorrect() throws SQLException { - DatabaseMetaData dbmd = dbConnection.getMetaData(); - boolean supportsTypeForward = dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY); - boolean supportsTypeScrollSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE); - boolean supportsTypeScrollInSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE); - boolean supportsCloseCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); - boolean supportsHoldCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); - boolean concurrency4TypeFwdNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_READ_ONLY); - boolean concurrency4TypeFwdNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_UPDATABLE); - boolean concurrency4TypeScrollInSensitiveNConcurUpdatable = dbmd - .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); - boolean concurrency4TypeScrollInSensitiveNConcurReadOnly = dbmd - .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - boolean concurrency4TypeScrollSensitiveNConcurUpdatable = dbmd - .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - boolean concurrency4TypeScrollSensitiveNConcurReadOnly = dbmd - .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - int rsHoldability = dbmd.getResultSetHoldability(); + rs.updateDouble("salary", 1100.0); + rs.updateRow(); - assertEquals("checking scroll sensitivity and concur updates : ", true, - concurrency4TypeScrollInSensitiveNConcurUpdatable); - } + Assert.assertEquals(1100.0, rs.getDouble("salary")); - @Test - public void givenDbConnectionF_whenRSMetaInfo_thenCorrect() throws SQLException { - int columnCount = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - ResultSetMetaData metaData = rs.getMetaData(); - columnCount = metaData.getColumnCount(); - for (int i = 1; i <= columnCount; i++) { - String catalogName = metaData.getCatalogName(i); - String className = metaData.getColumnClassName(i); - String label = metaData.getColumnLabel(i); - String name = metaData.getColumnName(i); - String typeName = metaData.getColumnTypeName(i); - Integer type = metaData.getColumnType(i); - String tableName = metaData.getTableName(i); - String schemaName = metaData.getSchemaName(i); - boolean isAutoIncrement = metaData.isAutoIncrement(i); - boolean isCaseSensitive = metaData.isCaseSensitive(i); - boolean isCurrency = metaData.isCurrency(i); - boolean isDefiniteWritable = metaData.isDefinitelyWritable(i); - boolean isReadOnly = metaData.isReadOnly(i); - boolean isSearchable = metaData.isSearchable(i); - boolean isReadable = metaData.isReadOnly(i); - boolean isSigned = metaData.isSigned(i); - boolean isWritable = metaData.isWritable(i); - int nullable = metaData.isNullable(i); - } - } + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } + } - assertEquals("column count", 4, columnCount); - } + @Test + public void givenDbConnectionE_whenDBMetaInfo_thenCorrect() throws SQLException { + DatabaseMetaData dbmd = dbConnection.getMetaData(); + boolean supportsTypeForward = dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY); + boolean supportsTypeScrollSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE); + boolean supportsTypeScrollInSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE); + boolean supportsCloseCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); + boolean supportsHoldCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); + boolean concurrency4TypeFwdNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + boolean concurrency4TypeFwdNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollInSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollInSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + boolean concurrency4TypeScrollSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + int rsHoldability = dbmd.getResultSetHoldability(); - @Test - public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException { - PreparedStatement pstmt = null; - ResultSet rs = null; - List listOfEmployees = new ArrayList(); - try { - pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_READ_ONLY); - pstmt.setFetchSize(2); - rs = pstmt.executeQuery(); - rs.setFetchSize(1); - while (rs.next()) { - Employee employee = populateResultSet(rs); - listOfEmployees.add(employee); - } - } catch (Exception e) { - throw e; - } finally { - if (rs != null) - rs.close(); - if (pstmt != null) - pstmt.close(); - } + assertEquals("checking scroll sensitivity and concur updates : ", true, concurrency4TypeScrollInSensitiveNConcurUpdatable); + } - assertEquals(3, listOfEmployees.size()); - } + @Test + public void givenDbConnectionF_whenRSMetaInfo_thenCorrect() throws SQLException { + int columnCount = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + ResultSetMetaData metaData = rs.getMetaData(); + columnCount = metaData.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String catalogName = metaData.getCatalogName(i); + String className = metaData.getColumnClassName(i); + String label = metaData.getColumnLabel(i); + String name = metaData.getColumnName(i); + String typeName = metaData.getColumnTypeName(i); + Integer type = metaData.getColumnType(i); + String tableName = metaData.getTableName(i); + String schemaName = metaData.getSchemaName(i); + boolean isAutoIncrement = metaData.isAutoIncrement(i); + boolean isCaseSensitive = metaData.isCaseSensitive(i); + boolean isCurrency = metaData.isCurrency(i); + boolean isDefiniteWritable = metaData.isDefinitelyWritable(i); + boolean isReadOnly = metaData.isReadOnly(i); + boolean isSearchable = metaData.isSearchable(i); + boolean isReadable = metaData.isReadOnly(i); + boolean isSigned = metaData.isSigned(i); + boolean isWritable = metaData.isWritable(i); + int nullable = metaData.isNullable(i); + } + } - @AfterClass - public static void closeConnection() throws SQLException { - PreparedStatement deleteStmt = dbConnection.prepareStatement("drop table employees", - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); - deleteStmt.execute(); - dbConnection.close(); - } + assertEquals("column count", 4, columnCount); + } + + @Test + public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException { + PreparedStatement pstmt = null; + ResultSet rs = null; + List listOfEmployees = new ArrayList(); + try { + pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + pstmt.setFetchSize(2); + rs = pstmt.executeQuery(); + rs.setFetchSize(1); + while (rs.next()) { + Employee employee = populateResultSet(rs); + listOfEmployees.add(employee); + } + } catch (Exception e) { + throw e; + } finally { + if (rs != null) + rs.close(); + if (pstmt != null) + pstmt.close(); + } + + assertEquals(3, listOfEmployees.size()); + } + + @AfterClass + public static void closeConnection() throws SQLException { + PreparedStatement deleteStmt = dbConnection.prepareStatement("drop table employees", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + deleteStmt.execute(); + dbConnection.close(); + } } From d9b88ed303d95a2d2ed72c34c445f7a9f88181a4 Mon Sep 17 00:00:00 2001 From: Venkata Kiran Surapaneni Date: Thu, 24 Jan 2019 15:03:42 -0500 Subject: [PATCH 006/254] Fixed some resultset creation --- .../src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java index 64d64e76f2..ef01382e2c 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java @@ -112,7 +112,7 @@ public class ResultSetLiveTest { @Test public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException { int numOfRows = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE); ResultSet rs = pstmt.executeQuery()) { rs.last(); numOfRows = rs.getRow(); } @@ -123,7 +123,7 @@ public class ResultSetLiveTest { @Test public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException { Employee secondEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE); ResultSet rs = pstmt.executeQuery()) { rs.absolute(2); secondEmployee = populateResultSet(rs); } @@ -145,7 +145,7 @@ public class ResultSetLiveTest { @Test public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException { Employee firstEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE); ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { Employee employee = populateResultSet(rs); } From 2fadf8b5a0cda9dedf9f9e40e430a825257d9832 Mon Sep 17 00:00:00 2001 From: Venkata Kiran Surapaneni Date: Thu, 24 Jan 2019 15:09:02 -0500 Subject: [PATCH 007/254] d --- .../src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java index ef01382e2c..7f714a9b32 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java @@ -79,7 +79,7 @@ public class ResultSetLiveTest { } } - assertEquals("Employee information retreived by column ids.", expectedEmployee1, employee); + assertEquals("Employee information retreived by column ids:", expectedEmployee1, employee); } @Test From 474a3675f1575b244f15d1a812a94aa4d4ae52f3 Mon Sep 17 00:00:00 2001 From: Venkata Kiran Surapaneni Date: Fri, 25 Jan 2019 03:06:50 -0500 Subject: [PATCH 008/254] Fixed the name of the fetch example --- .../com/baeldung/jdbc/ResultSetLiveTest.java | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java index 7f714a9b32..2762aeda5e 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java @@ -79,7 +79,7 @@ public class ResultSetLiveTest { } } - assertEquals("Employee information retreived by column ids:", expectedEmployee1, employee); + assertEquals("Employee information retreived by column ids.", expectedEmployee1, employee); } @Test @@ -112,7 +112,7 @@ public class ResultSetLiveTest { @Test public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException { int numOfRows = 0; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE); ResultSet rs = pstmt.executeQuery()) { + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { rs.last(); numOfRows = rs.getRow(); } @@ -123,7 +123,7 @@ public class ResultSetLiveTest { @Test public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException { Employee secondEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE); ResultSet rs = pstmt.executeQuery()) { + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { rs.absolute(2); secondEmployee = populateResultSet(rs); } @@ -145,7 +145,7 @@ public class ResultSetLiveTest { @Test public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException { Employee firstEmployee = null; - try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE); ResultSet rs = pstmt.executeQuery()) { + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { Employee employee = populateResultSet(rs); } @@ -195,6 +195,7 @@ public class ResultSetLiveTest { @Test public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException { int numOfRows = 0; + dbConnection.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT)) { dbConnection.setAutoCommit(false); pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Michael',1200.0,'Consultant')"); @@ -211,15 +212,16 @@ public class ResultSetLiveTest { } @Test - public void givenDbConnectionL_whenDelete_thenCorrect() throws SQLException { + public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException { int numOfRows = 0; try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { rs.absolute(3); rs.deleteRow(); + } + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { rs.last(); numOfRows = rs.getRow(); } - assertEquals("Deleted row", 3, numOfRows); } @@ -296,13 +298,13 @@ public class ResultSetLiveTest { } @Test - public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException { + public void givenDbConnectionL_whenFetch_thenCorrect() throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; List listOfEmployees = new ArrayList(); try { - pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - pstmt.setFetchSize(2); + pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + pstmt.setFetchSize(1); rs = pstmt.executeQuery(); rs.setFetchSize(1); while (rs.next()) { @@ -318,7 +320,7 @@ public class ResultSetLiveTest { pstmt.close(); } - assertEquals(3, listOfEmployees.size()); + assertEquals(4, listOfEmployees.size()); } @AfterClass From 29452abde43333219fce7d4a229e8c152615b1fd Mon Sep 17 00:00:00 2001 From: Erhan KARAKAYA Date: Sun, 27 Jan 2019 03:27:38 +0300 Subject: [PATCH 009/254] Added tutorial sample for BAEL-2550 --- .../AbstractGenericService.java | 38 +++++++++++++ .../sampleabstract/AbstractService.java | 57 +++++++++++++++++++ .../org/baeldung/sampleabstract/BarBean.java | 12 ++++ .../org/baeldung/sampleabstract/DemoApp.java | 32 +++++++++++ .../baeldung/sampleabstract/FooBarBean.java | 12 ++++ .../org/baeldung/sampleabstract/FooBean.java | 12 ++++ .../sampleabstract/FooGenericService.java | 8 +++ .../baeldung/sampleabstract/FooService.java | 14 +++++ 8 files changed, 185 insertions(+) create mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/AbstractGenericService.java create mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/AbstractService.java create mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/BarBean.java create mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java create mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/FooBarBean.java create mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/FooBean.java create mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/FooGenericService.java create mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/FooService.java diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractGenericService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractGenericService.java new file mode 100644 index 0000000000..88451d5181 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractGenericService.java @@ -0,0 +1,38 @@ +package org.baeldung.sampleabstract; + +import org.springframework.beans.factory.annotation.Autowired; + +public abstract class AbstractGenericService { + + @Autowired + private T genericFieldT; + + private S genericFieldS; + + public T getGenericFieldT() { + + return genericFieldT; + } + + public void setGenericFieldT(T genericFieldT) { + + this.genericFieldT = genericFieldT; + } + + public S getGenericFieldS() { + + return genericFieldS; + } + + @Autowired + public void setGenericFieldS(S genericFieldS) { + + this.genericFieldS = genericFieldS; + } + + public void afterInitialize() { + + System.out.println(genericFieldT.getClass().getSimpleName()); + System.out.println(genericFieldS.getClass().getSimpleName()); + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractService.java new file mode 100644 index 0000000000..51882f20b3 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractService.java @@ -0,0 +1,57 @@ +package org.baeldung.sampleabstract; + +import org.springframework.beans.factory.annotation.Autowired; + + +public abstract class AbstractService { + + @Autowired + private FooBean fooBean; + + private BarBean barBean; + + private FooBarBean fooBarBean; + + public AbstractService(FooBarBean fooBarBean) { + + this.fooBarBean = fooBarBean; + } + + public FooBean getFooBean() { + + return fooBean; + } + + public void setFooBean(FooBean fooBean) { + + this.fooBean = fooBean; + } + + public BarBean getBarBean() { + + return barBean; + } + + @Autowired + public void setBarBean(BarBean barBean) { + + this.barBean = barBean; + } + + public FooBarBean getFooBarBean() { + + return fooBarBean; + } + + public void setFooBarBean(FooBarBean fooBarBean) { + + this.fooBarBean = fooBarBean; + } + + public void afterInitialize() { + + System.out.println(fooBean.value()); + System.out.println(barBean.value()); + System.out.println(fooBarBean.value()); + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/BarBean.java b/spring-all/src/main/java/org/baeldung/sampleabstract/BarBean.java new file mode 100644 index 0000000000..8aeb5d2001 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/BarBean.java @@ -0,0 +1,12 @@ +package org.baeldung.sampleabstract; + +import org.springframework.stereotype.Component; + +@Component +public class BarBean { + + public String value() { + + return "barBean"; + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java b/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java new file mode 100644 index 0000000000..f6e7fd47b5 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java @@ -0,0 +1,32 @@ +package org.baeldung.sampleabstract; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import javax.annotation.PostConstruct; + +@Configuration +@ComponentScan(basePackages = "org.baeldung.sampleabstract") +public class DemoApp { + + @Autowired + private FooService fooService; + + @Autowired + private FooGenericService fooGenericService; + + public static void main(String[] args) { + + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApp.class); + } + + @PostConstruct + public void afterInitialize() { + + fooService.afterInitialize(); + fooGenericService.afterInitialize(); + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/FooBarBean.java b/spring-all/src/main/java/org/baeldung/sampleabstract/FooBarBean.java new file mode 100644 index 0000000000..0f46518a41 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/FooBarBean.java @@ -0,0 +1,12 @@ +package org.baeldung.sampleabstract; + +import org.springframework.stereotype.Component; + +@Component +public class FooBarBean { + + public String value() { + + return "fooBarBean"; + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/FooBean.java b/spring-all/src/main/java/org/baeldung/sampleabstract/FooBean.java new file mode 100644 index 0000000000..5ef623b5af --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/FooBean.java @@ -0,0 +1,12 @@ +package org.baeldung.sampleabstract; + +import org.springframework.stereotype.Component; + +@Component +public class FooBean { + + public String value() { + + return "fooBean"; + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/FooGenericService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/FooGenericService.java new file mode 100644 index 0000000000..45ad15e33a --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/FooGenericService.java @@ -0,0 +1,8 @@ +package org.baeldung.sampleabstract; + +import org.springframework.stereotype.Component; + +@Component +public class FooGenericService extends AbstractGenericService { + +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/FooService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/FooService.java new file mode 100644 index 0000000000..8bc625e098 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/FooService.java @@ -0,0 +1,14 @@ +package org.baeldung.sampleabstract; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class FooService extends AbstractService { + + @Autowired + public FooService(FooBarBean fooBarBean) { + + super(fooBarBean); + } +} From 435f1982985b316d7f2653997ea7d3ec3a8b2175 Mon Sep 17 00:00:00 2001 From: Venkata Kiran Surapaneni Date: Mon, 28 Jan 2019 01:55:39 -0500 Subject: [PATCH 010/254] applied formatter --- .../main/java/com/baeldung/jdbc/Employee.java | 103 +++++++++--------- 1 file changed, 51 insertions(+), 52 deletions(-) diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java index 88af4902b5..27aef8b82f 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java @@ -3,69 +3,68 @@ package com.baeldung.jdbc; import java.util.Objects; public class Employee { - private int id; - private String name; - private String position; - private double salary; + private int id; + private String name; + private String position; + private double salary; - public Employee() { - } + public Employee() { + } - public Employee(int id, String name, double salary, String position) { - this.id = id; - this.name = name; - this.salary = salary; - this.position = position; - } + public Employee(int id, String name, double salary, String position) { + this.id = id; + this.name = name; + this.salary = salary; + this.position = position; + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public double getSalary() { - return salary; - } + public double getSalary() { + return salary; + } - public void setSalary(double salary) { - this.salary = salary; - } + public void setSalary(double salary) { + this.salary = salary; + } - public String getPosition() { - return position; - } + public String getPosition() { + return position; + } - public void setPosition(String position) { - this.position = position; - } + public void setPosition(String position) { + this.position = position; + } - @Override - public int hashCode() { - return Objects.hash(id, name, position, salary); - } + @Override + public int hashCode() { + return Objects.hash(id, name, position, salary); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Employee other = (Employee) obj; - return id == other.id && Objects.equals(name, other.name) && Objects.equals(position, other.position) - && Double.doubleToLongBits(salary) == Double.doubleToLongBits(other.salary); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Employee other = (Employee) obj; + return id == other.id && Objects.equals(name, other.name) && Objects.equals(position, other.position) && Double.doubleToLongBits(salary) == Double.doubleToLongBits(other.salary); + } } From 11bce96dc8da2da189f8da0df99ffe8fbe28c37f Mon Sep 17 00:00:00 2001 From: Erhan KARAKAYA Date: Sun, 3 Feb 2019 22:47:10 +0300 Subject: [PATCH 011/254] Removed generic examples --- .../AbstractGenericService.java | 38 ------------------- .../org/baeldung/sampleabstract/DemoApp.java | 4 -- .../sampleabstract/FooGenericService.java | 8 ---- 3 files changed, 50 deletions(-) delete mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/AbstractGenericService.java delete mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/FooGenericService.java diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractGenericService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractGenericService.java deleted file mode 100644 index 88451d5181..0000000000 --- a/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractGenericService.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.sampleabstract; - -import org.springframework.beans.factory.annotation.Autowired; - -public abstract class AbstractGenericService { - - @Autowired - private T genericFieldT; - - private S genericFieldS; - - public T getGenericFieldT() { - - return genericFieldT; - } - - public void setGenericFieldT(T genericFieldT) { - - this.genericFieldT = genericFieldT; - } - - public S getGenericFieldS() { - - return genericFieldS; - } - - @Autowired - public void setGenericFieldS(S genericFieldS) { - - this.genericFieldS = genericFieldS; - } - - public void afterInitialize() { - - System.out.println(genericFieldT.getClass().getSimpleName()); - System.out.println(genericFieldS.getClass().getSimpleName()); - } -} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java b/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java index f6e7fd47b5..0c3c4ea083 100644 --- a/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java @@ -15,9 +15,6 @@ public class DemoApp { @Autowired private FooService fooService; - @Autowired - private FooGenericService fooGenericService; - public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApp.class); @@ -27,6 +24,5 @@ public class DemoApp { public void afterInitialize() { fooService.afterInitialize(); - fooGenericService.afterInitialize(); } } diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/FooGenericService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/FooGenericService.java deleted file mode 100644 index 45ad15e33a..0000000000 --- a/spring-all/src/main/java/org/baeldung/sampleabstract/FooGenericService.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.sampleabstract; - -import org.springframework.stereotype.Component; - -@Component -public class FooGenericService extends AbstractGenericService { - -} From 648e66d9e3c799cc44e87d22d4199cb9e0debd55 Mon Sep 17 00:00:00 2001 From: Yatendra Goel Date: Sun, 10 Feb 2019 02:54:20 +0530 Subject: [PATCH 012/254] BAEL-1915: Upgraded from Boot1 to Boot2 --- spring-boot-security/pom.xml | 10 ++++++++-- .../basic_auth/SpringBootSecurityApplication.java | 2 +- .../basic_auth/config/BasicAuthConfiguration.java | 9 ++++++--- .../BasicAuthConfigurationIntegrationTest.java | 4 +--- 4 files changed, 16 insertions(+), 9 deletions(-) diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index b87189757a..ec442f8dd1 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -8,10 +8,10 @@ Spring Boot Security Auto-Configuration - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -22,6 +22,12 @@ org.springframework.security.oauth spring-security-oauth2 + 2.3.3.RELEASE + + + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + 2.1.2.RELEASE org.springframework.boot diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java index 2ecad4ae35..4666ca4fbd 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java @@ -2,7 +2,7 @@ package com.baeldung.springbootsecurity.basic_auth; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; @SpringBootApplication(exclude = { SecurityAutoConfiguration.class diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java index 993c573fb0..592ef5354d 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java @@ -5,6 +5,8 @@ import org.springframework.security.config.annotation.authentication.builders.Au import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity @@ -12,14 +14,15 @@ public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth + PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); + auth .inMemoryAuthentication() .withUser("user") - .password("password") + .password(encoder.encode("password")) .roles("USER") .and() .withUser("admin") - .password("admin") + .password(encoder.encode("admin")) .roles("USER", "ADMIN"); } diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java index 32c3fbdef4..94cf9f4148 100644 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java +++ b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java @@ -1,12 +1,11 @@ package com.baeldung.springbootsecurity.basic_auth; -import com.baeldung.springbootsecurity.basic_auth.SpringBootSecurityApplication; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; @@ -18,7 +17,6 @@ import java.net.URL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootSecurityApplication.class) public class BasicAuthConfigurationIntegrationTest { From b4041f577d9a42f7656f664ac42b010e76f470a8 Mon Sep 17 00:00:00 2001 From: Venkata Kiran Surapaneni Date: Mon, 11 Feb 2019 08:28:20 -0500 Subject: [PATCH 013/254] Made holdability example much clear. --- .../com/baeldung/jdbc/ResultSetLiveTest.java | 65 +++++++++++++------ 1 file changed, 46 insertions(+), 19 deletions(-) diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java index 2762aeda5e..4e10f8bd43 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java @@ -175,54 +175,60 @@ public class ResultSetLiveTest { @Test public void givenDbConnectionJ_whenClosedCursor_thenCorrect() throws SQLException { - int numOfRows = 0; + Employee employee = null; dbConnection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT)) { dbConnection.setAutoCommit(false); - pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Chris',2100.0,'Manager')"); ResultSet rs = pstmt.executeQuery("select * from employees"); - dbConnection.commit(); while (rs.next()) { - Employee employee = populateResultSet(rs); + if (rs.getString("name") + .equalsIgnoreCase("john")) { + rs.updateString("position", "Senior Engineer"); + rs.updateRow(); + dbConnection.commit(); + employee = populateResultSet(rs); + } } rs.last(); - numOfRows = rs.getRow(); } - assertEquals("Inserted using close cursor after commit", 3, numOfRows); + assertEquals("Update using closed cursor", "Senior Engineer", employee.getPosition()); } @Test public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException { - int numOfRows = 0; + Employee employee = null; dbConnection.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT)) { dbConnection.setAutoCommit(false); - pstmt.executeUpdate("INSERT INTO employees (name, salary,position) VALUES ('Michael',1200.0,'Consultant')"); ResultSet rs = pstmt.executeQuery("select * from employees"); - dbConnection.commit(); while (rs.next()) { - Employee employee = populateResultSet(rs); + if (rs.getString("name") + .equalsIgnoreCase("john")) { + rs.updateString("name", "John Doe"); + rs.updateRow(); + dbConnection.commit(); + employee = populateResultSet(rs); + } } rs.last(); - numOfRows = rs.getRow(); } - assertEquals("Inserted using hold cursor after commit", 4, numOfRows); + assertEquals("Update using open cursor", "John Doe", employee.getName()); } @Test public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException { int numOfRows = 0; try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { - rs.absolute(3); + rs.absolute(2); rs.deleteRow(); } try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { rs.last(); numOfRows = rs.getRow(); } - assertEquals("Deleted row", 3, numOfRows); + assertEquals("Deleted row", 1, numOfRows); } @Test @@ -231,12 +237,33 @@ public class ResultSetLiveTest { try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { - Assert.assertEquals(1000.0, rs.getDouble("salary")); + Assert.assertEquals(1100.0, rs.getDouble("salary")); - rs.updateDouble("salary", 1100.0); + rs.updateDouble("salary", 1200.0); rs.updateRow(); - Assert.assertEquals(1100.0, rs.getDouble("salary")); + Assert.assertEquals(1200.0, rs.getDouble("salary")); + + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } + } + + @Test + public void givenDbConnectionC_whenUpdateByIndex_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + + Assert.assertEquals(1000.0, rs.getDouble(4)); + + rs.updateDouble(4, 1100.0); + rs.updateRow(); + Assert.assertEquals(1100.0, rs.getDouble(4)); String name = rs.getString("name"); Integer empId = rs.getInt("emp_id"); @@ -320,7 +347,7 @@ public class ResultSetLiveTest { pstmt.close(); } - assertEquals(4, listOfEmployees.size()); + assertEquals(2, listOfEmployees.size()); } @AfterClass @@ -329,4 +356,4 @@ public class ResultSetLiveTest { deleteStmt.execute(); dbConnection.close(); } -} +} \ No newline at end of file From fc88c99537ce2f4bb3b08b9e3da1da82e5bc9ee6 Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Fri, 15 Feb 2019 22:53:52 +0100 Subject: [PATCH 014/254] fixed README file changed filter to match url pattern --- javax-servlets-3/Dockerfile | 2 +- javax-servlets-3/README.md | 3 ++- javax-servlets-3/pom.xml | 1 + .../servlets3/web/filters/EmptyParamFilter.java | 17 ++++------------- 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/javax-servlets-3/Dockerfile b/javax-servlets-3/Dockerfile index 97cc1897dd..27d1450acb 100644 --- a/javax-servlets-3/Dockerfile +++ b/javax-servlets-3/Dockerfile @@ -1,2 +1,2 @@ FROM tomcat -ADD ./target/javax-servlets-3-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/ \ No newline at end of file +ADD ./target/uppercasing-app.war /usr/local/tomcat/webapps/ \ No newline at end of file diff --git a/javax-servlets-3/README.md b/javax-servlets-3/README.md index ff310b5928..1f4855f4b3 100644 --- a/javax-servlets-3/README.md +++ b/javax-servlets-3/README.md @@ -3,7 +3,8 @@ mvn package ## Run with Tomcat on Docker container: docker build --tag my-tomcat . + docker run -it --rm -p 8080:8080 my-tomcat -### Relevant Articles: +## Relevant Articles: - [Java Web Application Without Web.xml] diff --git a/javax-servlets-3/pom.xml b/javax-servlets-3/pom.xml index 2b4fc37fc4..8c339ce6d4 100644 --- a/javax-servlets-3/pom.xml +++ b/javax-servlets-3/pom.xml @@ -31,6 +31,7 @@ 5.1.3.RELEASE + uppercasing-app org.apache.maven.plugins diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java index 2c9f603d2c..61a7e896cc 100644 --- a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java +++ b/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java @@ -8,9 +8,8 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import java.io.IOException; -import java.io.PrintWriter; -@WebFilter(servletNames = { "uppercaseServlet" }, filterName = "emptyParamFilter") +@WebFilter(servletNames = { "uppercaseServlet" }, urlPatterns = "/uppercase") public class EmptyParamFilter implements Filter { @Override @@ -22,21 +21,13 @@ public class EmptyParamFilter implements Filter { FilterChain filterChain) throws IOException, ServletException { String inputString = servletRequest.getParameter("input"); - if (inputString == null || inputString.isEmpty()) { - response(servletResponse); - } else { + if (inputString != null && inputString.matches("[A-Za-z0-9]+")) { filterChain.doFilter(servletRequest, servletResponse); + } else { + servletResponse.getWriter().println("Missing input parameter"); } } - private void response(ServletResponse response) throws IOException { - response.setContentType("text/html"); - - PrintWriter out = response.getWriter(); - - out.println("Missing input parameter"); - } - @Override public void destroy() { } From 062b959d5a4d127a168d56045d589f0e45d8d5da Mon Sep 17 00:00:00 2001 From: vsurapaneni Date: Tue, 19 Feb 2019 15:33:40 -0500 Subject: [PATCH 015/254] BAEL-2575 --- spring-boot-datasource-issue/pom.xml | 21 +++++++++ .../pom.xml | 36 +++++++++++++++ .../DataSourceIssueSolutionApplication.java | 15 +++++++ .../pom.xml | 36 +++++++++++++++ .../DataSourceIssueSolutionApplication.java | 13 ++++++ .../src/main/resources/application.properties | 2 + .../pom.xml | 45 +++++++++++++++++++ .../DataSourceIssueSolutionApplication.java | 13 ++++++ .../src/main/resources/application.yml | 4 ++ .../spring-boot-datasource-program/pom.xml | 36 +++++++++++++++ .../DataSourceIssueSolutionApplication.java | 13 ++++++ .../datasourcedemo/DatasourceConfig.java | 18 ++++++++ .../spring-boot-datasource-properties/pom.xml | 36 +++++++++++++++ .../DataSourceIssueSolutionApplication.java | 13 ++++++ .../src/main/resources/application.properties | 4 ++ .../spring-boot-datasource-yml/pom.xml | 45 +++++++++++++++++++ .../DataSourceIssueSolutionApplication.java | 13 ++++++ .../src/main/resources/application.yml | 6 +++ 18 files changed, 369 insertions(+) create mode 100644 spring-boot-datasource-issue/pom.xml create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-program/pom.xml create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/pom.xml create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/resources/application.properties create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/pom.xml create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/resources/application.yml create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-program/pom.xml create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DatasourceConfig.java create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-properties/pom.xml create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/resources/application.properties create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-yml/pom.xml create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java create mode 100644 spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/resources/application.yml diff --git a/spring-boot-datasource-issue/pom.xml b/spring-boot-datasource-issue/pom.xml new file mode 100644 index 0000000000..2316d86e70 --- /dev/null +++ b/spring-boot-datasource-issue/pom.xml @@ -0,0 +1,21 @@ + + 4.0.0 + spring-boot-datasource-issue + pom + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + spring-boot-datasource-properties + spring-boot-datasource-exclude-program + spring-boot-datasource-exclude-properties + spring-boot-datasource-exclude-yml + spring-boot-datasource-program + spring-boot-datasource-yml + + \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/pom.xml new file mode 100644 index 0000000000..8025cc8959 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + com.baeldung + spring-boot-datasource-issue + 0.0.1-SNAPSHOT + + spring-boot-datasource-exclude-program + spring-boot-datasource-exclude-program + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java new file mode 100644 index 0000000000..b6c81471c4 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.datasourcedemo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; + +@SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) +public class DataSourceIssueSolutionApplication { + + public static void main(String[] args) { + SpringApplication.run(DataSourceIssueSolutionApplication.class, args); + } + +} + diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/pom.xml new file mode 100644 index 0000000000..78d253c4f7 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + com.baeldung + spring-boot-datasource-issue + 0.0.1-SNAPSHOT + + spring-boot-datasource-exclude-properties + spring-boot-datasource-exclude-properties + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java new file mode 100644 index 0000000000..377a245b38 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.datasourcedemo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DataSourceIssueSolutionApplication { + + public static void main(String[] args) { + SpringApplication.run(DataSourceIssueSolutionApplication.class, args); + } + +} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/resources/application.properties b/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/resources/application.properties new file mode 100644 index 0000000000..ae2b359cd0 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration + diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/pom.xml new file mode 100644 index 0000000000..1d60ea3dbf --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + + com.baeldung + spring-boot-datasource-issue + 0.0.1-SNAPSHOT + + spring-boot-datasource-exclude-yml + spring-boot-datasource-exclude-yml + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime + + + org.yaml + snakeyaml + + + + + Sonatype-public + SnakeYAML repository + http://oss.sonatype.org/content/groups/public/ + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java new file mode 100644 index 0000000000..377a245b38 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.datasourcedemo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DataSourceIssueSolutionApplication { + + public static void main(String[] args) { + SpringApplication.run(DataSourceIssueSolutionApplication.class, args); + } + +} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/resources/application.yml b/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/resources/application.yml new file mode 100644 index 0000000000..c574bf01a7 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/resources/application.yml @@ -0,0 +1,4 @@ +spring: + autoconfigure: + exclude: + - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration diff --git a/spring-boot-datasource-issue/spring-boot-datasource-program/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-program/pom.xml new file mode 100644 index 0000000000..279fcc063b --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-program/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + com.baeldung + spring-boot-datasource-issue + 0.0.1-SNAPSHOT + + spring-boot-datasource-program + spring-boot-datasource-program + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java new file mode 100644 index 0000000000..377a245b38 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.datasourcedemo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DataSourceIssueSolutionApplication { + + public static void main(String[] args) { + SpringApplication.run(DataSourceIssueSolutionApplication.class, args); + } + +} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DatasourceConfig.java b/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DatasourceConfig.java new file mode 100644 index 0000000000..0eca032d42 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DatasourceConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.datasourcedemo; + + +import javax.sql.DataSource; + +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class DatasourceConfig { + @Bean + public DataSource datasource() { + return DataSourceBuilder.create().driverClassName("com.mysql.cj.jdbc.Driver"). + url("jdbc:mysql://localhost:3306/lonar").username("root").password("Chinna@1988").build(); + } + +} \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-properties/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-properties/pom.xml new file mode 100644 index 0000000000..8a7ca75bdd --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-properties/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + com.baeldung + spring-boot-datasource-issue + 0.0.1-SNAPSHOT + + spring-boot-datasource-properties + spring-boot-datasource-properties + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java new file mode 100644 index 0000000000..377a245b38 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.datasourcedemo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DataSourceIssueSolutionApplication { + + public static void main(String[] args) { + SpringApplication.run(DataSourceIssueSolutionApplication.class, args); + } + +} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/resources/application.properties b/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/resources/application.properties new file mode 100644 index 0000000000..90605e9258 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/resources/application.properties @@ -0,0 +1,4 @@ +spring.datasource.url=jdbc:mysql://localhost:3306/lonar +spring.datasource.username=root +spring.datasource.password=Chinna@1988 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver diff --git a/spring-boot-datasource-issue/spring-boot-datasource-yml/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-yml/pom.xml new file mode 100644 index 0000000000..6f474f76db --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-yml/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + + com.baeldung + spring-boot-datasource-issue + 0.0.1-SNAPSHOT + + spring-boot-datasource-yml + spring-boot-datasource-yml + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime + + + org.yaml + snakeyaml + + + + + Sonatype-public + SnakeYAML repository + http://oss.sonatype.org/content/groups/public/ + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java new file mode 100644 index 0000000000..377a245b38 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.datasourcedemo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DataSourceIssueSolutionApplication { + + public static void main(String[] args) { + SpringApplication.run(DataSourceIssueSolutionApplication.class, args); + } + +} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/resources/application.yml b/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/resources/application.yml new file mode 100644 index 0000000000..98d7c843e8 --- /dev/null +++ b/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + datasource: + driverClassName: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/lonar + username: root + password: Chinna@1988 From c5d9aceb86b450b2a022c39acc73ddc128b5fb11 Mon Sep 17 00:00:00 2001 From: vsurapaneni Date: Tue, 19 Feb 2019 16:09:52 -0500 Subject: [PATCH 016/254] fixed the mix up with another pr. --- spring-boot-datasource-issue/pom.xml | 21 --------- .../pom.xml | 36 --------------- .../DataSourceIssueSolutionApplication.java | 15 ------- .../pom.xml | 36 --------------- .../DataSourceIssueSolutionApplication.java | 13 ------ .../src/main/resources/application.properties | 2 - .../pom.xml | 45 ------------------- .../DataSourceIssueSolutionApplication.java | 13 ------ .../src/main/resources/application.yml | 4 -- .../spring-boot-datasource-program/pom.xml | 36 --------------- .../DataSourceIssueSolutionApplication.java | 13 ------ .../datasourcedemo/DatasourceConfig.java | 18 -------- .../spring-boot-datasource-properties/pom.xml | 36 --------------- .../DataSourceIssueSolutionApplication.java | 13 ------ .../src/main/resources/application.properties | 4 -- .../spring-boot-datasource-yml/pom.xml | 45 ------------------- .../DataSourceIssueSolutionApplication.java | 13 ------ .../src/main/resources/application.yml | 6 --- 18 files changed, 369 deletions(-) delete mode 100644 spring-boot-datasource-issue/pom.xml delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-program/pom.xml delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/pom.xml delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/resources/application.properties delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/pom.xml delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/resources/application.yml delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-program/pom.xml delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DatasourceConfig.java delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-properties/pom.xml delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/resources/application.properties delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-yml/pom.xml delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java delete mode 100644 spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/resources/application.yml diff --git a/spring-boot-datasource-issue/pom.xml b/spring-boot-datasource-issue/pom.xml deleted file mode 100644 index 2316d86e70..0000000000 --- a/spring-boot-datasource-issue/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - 4.0.0 - spring-boot-datasource-issue - pom - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - spring-boot-datasource-properties - spring-boot-datasource-exclude-program - spring-boot-datasource-exclude-properties - spring-boot-datasource-exclude-yml - spring-boot-datasource-program - spring-boot-datasource-yml - - \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/pom.xml deleted file mode 100644 index 8025cc8959..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - 4.0.0 - - com.baeldung - spring-boot-datasource-issue - 0.0.1-SNAPSHOT - - spring-boot-datasource-exclude-program - spring-boot-datasource-exclude-program - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - mysql - mysql-connector-java - runtime - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java deleted file mode 100644 index b6c81471c4..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-exclude-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.datasourcedemo; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; - -@SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) -public class DataSourceIssueSolutionApplication { - - public static void main(String[] args) { - SpringApplication.run(DataSourceIssueSolutionApplication.class, args); - } - -} - diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/pom.xml deleted file mode 100644 index 78d253c4f7..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - 4.0.0 - - com.baeldung - spring-boot-datasource-issue - 0.0.1-SNAPSHOT - - spring-boot-datasource-exclude-properties - spring-boot-datasource-exclude-properties - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - mysql - mysql-connector-java - runtime - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java deleted file mode 100644 index 377a245b38..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.datasourcedemo; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class DataSourceIssueSolutionApplication { - - public static void main(String[] args) { - SpringApplication.run(DataSourceIssueSolutionApplication.class, args); - } - -} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/resources/application.properties b/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/resources/application.properties deleted file mode 100644 index ae2b359cd0..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-exclude-properties/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration - diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/pom.xml deleted file mode 100644 index 1d60ea3dbf..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - 4.0.0 - - com.baeldung - spring-boot-datasource-issue - 0.0.1-SNAPSHOT - - spring-boot-datasource-exclude-yml - spring-boot-datasource-exclude-yml - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - mysql - mysql-connector-java - runtime - - - org.yaml - snakeyaml - - - - - Sonatype-public - SnakeYAML repository - http://oss.sonatype.org/content/groups/public/ - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java deleted file mode 100644 index 377a245b38..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.datasourcedemo; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class DataSourceIssueSolutionApplication { - - public static void main(String[] args) { - SpringApplication.run(DataSourceIssueSolutionApplication.class, args); - } - -} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/resources/application.yml b/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/resources/application.yml deleted file mode 100644 index c574bf01a7..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-exclude-yml/src/main/resources/application.yml +++ /dev/null @@ -1,4 +0,0 @@ -spring: - autoconfigure: - exclude: - - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration diff --git a/spring-boot-datasource-issue/spring-boot-datasource-program/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-program/pom.xml deleted file mode 100644 index 279fcc063b..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-program/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - 4.0.0 - - com.baeldung - spring-boot-datasource-issue - 0.0.1-SNAPSHOT - - spring-boot-datasource-program - spring-boot-datasource-program - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - mysql - mysql-connector-java - runtime - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java deleted file mode 100644 index 377a245b38..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.datasourcedemo; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class DataSourceIssueSolutionApplication { - - public static void main(String[] args) { - SpringApplication.run(DataSourceIssueSolutionApplication.class, args); - } - -} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DatasourceConfig.java b/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DatasourceConfig.java deleted file mode 100644 index 0eca032d42..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-program/src/main/java/com/baeldung/datasourcedemo/DatasourceConfig.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.datasourcedemo; - - -import javax.sql.DataSource; - -import org.springframework.boot.jdbc.DataSourceBuilder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class DatasourceConfig { - @Bean - public DataSource datasource() { - return DataSourceBuilder.create().driverClassName("com.mysql.cj.jdbc.Driver"). - url("jdbc:mysql://localhost:3306/lonar").username("root").password("Chinna@1988").build(); - } - -} \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-properties/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-properties/pom.xml deleted file mode 100644 index 8a7ca75bdd..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-properties/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - 4.0.0 - - com.baeldung - spring-boot-datasource-issue - 0.0.1-SNAPSHOT - - spring-boot-datasource-properties - spring-boot-datasource-properties - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - mysql - mysql-connector-java - runtime - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java deleted file mode 100644 index 377a245b38..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.datasourcedemo; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class DataSourceIssueSolutionApplication { - - public static void main(String[] args) { - SpringApplication.run(DataSourceIssueSolutionApplication.class, args); - } - -} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/resources/application.properties b/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/resources/application.properties deleted file mode 100644 index 90605e9258..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-properties/src/main/resources/application.properties +++ /dev/null @@ -1,4 +0,0 @@ -spring.datasource.url=jdbc:mysql://localhost:3306/lonar -spring.datasource.username=root -spring.datasource.password=Chinna@1988 -spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver diff --git a/spring-boot-datasource-issue/spring-boot-datasource-yml/pom.xml b/spring-boot-datasource-issue/spring-boot-datasource-yml/pom.xml deleted file mode 100644 index 6f474f76db..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-yml/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - 4.0.0 - - com.baeldung - spring-boot-datasource-issue - 0.0.1-SNAPSHOT - - spring-boot-datasource-yml - spring-boot-datasource-yml - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - mysql - mysql-connector-java - runtime - - - org.yaml - snakeyaml - - - - - Sonatype-public - SnakeYAML repository - http://oss.sonatype.org/content/groups/public/ - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java b/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java deleted file mode 100644 index 377a245b38..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/java/com/baeldung/datasourcedemo/DataSourceIssueSolutionApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.datasourcedemo; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class DataSourceIssueSolutionApplication { - - public static void main(String[] args) { - SpringApplication.run(DataSourceIssueSolutionApplication.class, args); - } - -} diff --git a/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/resources/application.yml b/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/resources/application.yml deleted file mode 100644 index 98d7c843e8..0000000000 --- a/spring-boot-datasource-issue/spring-boot-datasource-yml/src/main/resources/application.yml +++ /dev/null @@ -1,6 +0,0 @@ -spring: - datasource: - driverClassName: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://localhost:3306/lonar - username: root - password: Chinna@1988 From 249f2f0ed06a343e81ef101eea500af585c8e70b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 20 Feb 2019 20:47:13 +0200 Subject: [PATCH 017/254] Update SpringBootSecurityApplication.java --- .../basic_auth/SpringBootSecurityApplication.java | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java index 4666ca4fbd..7007c15596 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java @@ -9,7 +9,6 @@ import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfi // ,ManagementWebSecurityAutoConfiguration.class }, scanBasePackages = "com.baeldung.springbootsecurity.basic_auth") public class SpringBootSecurityApplication { - public static void main(String[] args) { SpringApplication.run(SpringBootSecurityApplication.class, args); } From f14c3fbab33ce21cb99978e1813366338059745a Mon Sep 17 00:00:00 2001 From: Jon Cook Date: Wed, 20 Feb 2019 20:55:15 +0100 Subject: [PATCH 018/254] BAEL-2541 - Guide to ProcessBuilder API --- .../ProcessBuilderUnitTest.java | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java b/core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java new file mode 100644 index 0000000000..89a42b5d5c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java @@ -0,0 +1,159 @@ +package com.baeldung.processbuilder; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.ProcessBuilder.Redirect; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +public class ProcessBuilderUnitTest { + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + @Test + public void givenProcessBuilder_whenInvokeStart_thenSuccess() throws IOException, InterruptedException, ExecutionException { + ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); + processBuilder.redirectErrorStream(true); + + Process process = processBuilder.start(); + + List results = readOutput(process.getInputStream()); + assertThat("Results should not be empty", results, is(not(empty()))); + assertThat("Results should contain java version: ", results, hasItem(containsString("java version"))); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + @Test + public void givenProcessBuilder_whenModifyEnvironment_thenSuccess() throws IOException, InterruptedException { + ProcessBuilder processBuilder = new ProcessBuilder(); + Map environment = processBuilder.environment(); + environment.forEach((key, value) -> System.out.println(key + value)); + + environment.put("GREETING", "Hola Mundo"); + + processBuilder.command("/bin/bash", "-c", "echo $GREETING"); + Process process = processBuilder.start(); + + List results = readOutput(process.getInputStream()); + assertThat("Results should not be empty", results, is(not(empty()))); + assertThat("Results should contain a greeting ", results, hasItem(containsString("Hola Mundo"))); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + @Test + public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() throws IOException, InterruptedException { + ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "ls"); + + processBuilder.directory(new File("src")); + Process process = processBuilder.start(); + + List results = readOutput(process.getInputStream()); + assertThat("Results should not be empty", results, is(not(empty()))); + assertThat("Results should contain directory listing: ", results, contains("main", "test")); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + @Test + public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessWriting() throws IOException, InterruptedException { + ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); + + processBuilder.redirectErrorStream(true); + File log = tempFolder.newFile("java-version.log"); + processBuilder.redirectOutput(log); + + Process process = processBuilder.start(); + + assertEquals("If redirected, should be -1 ", -1, process.getInputStream() + .read()); + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + + List lines = Files.lines(log.toPath()) + .collect(Collectors.toList()); + + assertThat("Results should not be empty", lines, is(not(empty()))); + assertThat("Results should contain java version: ", lines, hasItem(containsString("java version"))); + } + + @Test + public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessAppending() throws IOException, InterruptedException { + ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); + + File log = tempFolder.newFile("java-version-append.log"); + processBuilder.redirectErrorStream(true); + processBuilder.redirectOutput(Redirect.appendTo(log)); + + Process process = processBuilder.start(); + + assertEquals("If redirected output, should be -1 ", -1, process.getInputStream() + .read()); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + + List lines = Files.lines(log.toPath()) + .collect(Collectors.toList()); + + assertThat("Results should not be empty", lines, is(not(empty()))); + assertThat("Results should contain java version: ", lines, hasItem(containsString("java version"))); + } + + @Test + public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException { + List builders = Arrays.asList( + new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), + new ProcessBuilder("wc", "-l")); + + List processes = ProcessBuilder.startPipeline(builders); + Process last = processes.get(processes.size() - 1); + + List output = readOutput(last.getInputStream()); + assertThat("Results should not be empty", output, is(not(empty()))); + } + + @Test + public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException { + ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "echo hello"); + + processBuilder.inheritIO(); + Process process = processBuilder.start(); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + private List readOutput(InputStream inputStream) throws IOException { + try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) { + return output.lines() + .collect(Collectors.toList()); + } + } + +} From 1dac10b24782ab46aff992cebc75c705df962d1e Mon Sep 17 00:00:00 2001 From: Jonathan Paul Cook Date: Wed, 20 Feb 2019 22:58:18 +0100 Subject: [PATCH 019/254] BAEL-2541 - Guide to ProcessBuilder API - Update test commands to work on windows --- .../ProcessBuilderUnitTest.java | 340 ++++++++++-------- 1 file changed, 181 insertions(+), 159 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java b/core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java index 89a42b5d5c..a18cc3e368 100644 --- a/core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java +++ b/core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java @@ -1,159 +1,181 @@ -package com.baeldung.processbuilder; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.ProcessBuilder.Redirect; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -public class ProcessBuilderUnitTest { - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - @Test - public void givenProcessBuilder_whenInvokeStart_thenSuccess() throws IOException, InterruptedException, ExecutionException { - ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); - processBuilder.redirectErrorStream(true); - - Process process = processBuilder.start(); - - List results = readOutput(process.getInputStream()); - assertThat("Results should not be empty", results, is(not(empty()))); - assertThat("Results should contain java version: ", results, hasItem(containsString("java version"))); - - int exitCode = process.waitFor(); - assertEquals("No errors should be detected", 0, exitCode); - } - - @Test - public void givenProcessBuilder_whenModifyEnvironment_thenSuccess() throws IOException, InterruptedException { - ProcessBuilder processBuilder = new ProcessBuilder(); - Map environment = processBuilder.environment(); - environment.forEach((key, value) -> System.out.println(key + value)); - - environment.put("GREETING", "Hola Mundo"); - - processBuilder.command("/bin/bash", "-c", "echo $GREETING"); - Process process = processBuilder.start(); - - List results = readOutput(process.getInputStream()); - assertThat("Results should not be empty", results, is(not(empty()))); - assertThat("Results should contain a greeting ", results, hasItem(containsString("Hola Mundo"))); - - int exitCode = process.waitFor(); - assertEquals("No errors should be detected", 0, exitCode); - } - - @Test - public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() throws IOException, InterruptedException { - ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "ls"); - - processBuilder.directory(new File("src")); - Process process = processBuilder.start(); - - List results = readOutput(process.getInputStream()); - assertThat("Results should not be empty", results, is(not(empty()))); - assertThat("Results should contain directory listing: ", results, contains("main", "test")); - - int exitCode = process.waitFor(); - assertEquals("No errors should be detected", 0, exitCode); - } - - @Test - public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessWriting() throws IOException, InterruptedException { - ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); - - processBuilder.redirectErrorStream(true); - File log = tempFolder.newFile("java-version.log"); - processBuilder.redirectOutput(log); - - Process process = processBuilder.start(); - - assertEquals("If redirected, should be -1 ", -1, process.getInputStream() - .read()); - int exitCode = process.waitFor(); - assertEquals("No errors should be detected", 0, exitCode); - - List lines = Files.lines(log.toPath()) - .collect(Collectors.toList()); - - assertThat("Results should not be empty", lines, is(not(empty()))); - assertThat("Results should contain java version: ", lines, hasItem(containsString("java version"))); - } - - @Test - public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessAppending() throws IOException, InterruptedException { - ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); - - File log = tempFolder.newFile("java-version-append.log"); - processBuilder.redirectErrorStream(true); - processBuilder.redirectOutput(Redirect.appendTo(log)); - - Process process = processBuilder.start(); - - assertEquals("If redirected output, should be -1 ", -1, process.getInputStream() - .read()); - - int exitCode = process.waitFor(); - assertEquals("No errors should be detected", 0, exitCode); - - List lines = Files.lines(log.toPath()) - .collect(Collectors.toList()); - - assertThat("Results should not be empty", lines, is(not(empty()))); - assertThat("Results should contain java version: ", lines, hasItem(containsString("java version"))); - } - - @Test - public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException { - List builders = Arrays.asList( - new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), - new ProcessBuilder("wc", "-l")); - - List processes = ProcessBuilder.startPipeline(builders); - Process last = processes.get(processes.size() - 1); - - List output = readOutput(last.getInputStream()); - assertThat("Results should not be empty", output, is(not(empty()))); - } - - @Test - public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException { - ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "echo hello"); - - processBuilder.inheritIO(); - Process process = processBuilder.start(); - - int exitCode = process.waitFor(); - assertEquals("No errors should be detected", 0, exitCode); - } - - private List readOutput(InputStream inputStream) throws IOException { - try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) { - return output.lines() - .collect(Collectors.toList()); - } - } - -} +package com.baeldung.processbuilder; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.ProcessBuilder.Redirect; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +public class ProcessBuilderUnitTest { + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + @Test + public void givenProcessBuilder_whenInvokeStart_thenSuccess() throws IOException, InterruptedException, ExecutionException { + ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); + processBuilder.redirectErrorStream(true); + + Process process = processBuilder.start(); + + List results = readOutput(process.getInputStream()); + assertThat("Results should not be empty", results, is(not(empty()))); + assertThat("Results should contain java version: ", results, hasItem(containsString("java version"))); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + @Test + public void givenProcessBuilder_whenModifyEnvironment_thenSuccess() throws IOException, InterruptedException { + ProcessBuilder processBuilder = new ProcessBuilder(); + Map environment = processBuilder.environment(); + environment.forEach((key, value) -> System.out.println(key + value)); + + environment.put("GREETING", "Hola Mundo"); + + List command = getGreetingCommand(); + processBuilder.command(command); + Process process = processBuilder.start(); + + List results = readOutput(process.getInputStream()); + assertThat("Results should not be empty", results, is(not(empty()))); + assertThat("Results should contain a greeting ", results, hasItem(containsString("Hola Mundo"))); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + @Test + public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() throws IOException, InterruptedException { + List command = getDirectoryListingCommand(); + ProcessBuilder processBuilder = new ProcessBuilder(command); + + processBuilder.directory(new File("src")); + Process process = processBuilder.start(); + + List results = readOutput(process.getInputStream()); + assertThat("Results should not be empty", results, is(not(empty()))); + assertThat("Results should contain directory listing: ", results, hasItems(containsString("main"), containsString("test"))); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + private List getDirectoryListingCommand() { + return isWindows() ? Arrays.asList("cmd.exe", "/c", "dir") : Arrays.asList("/bin/sh", "-c", "ls"); + } + + private List getGreetingCommand() { + return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo %GREETING%") : Arrays.asList("/bin/bash", "-c", "echo $GREETING"); + } + + private List getEchoCommand() { + return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo hello") : Arrays.asList("/bin/sh", "-c", "echo hello"); + } + + private boolean isWindows() { + return System.getProperty("os.name") + .toLowerCase() + .startsWith("windows"); + } + + @Test + public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessWriting() throws IOException, InterruptedException { + ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); + + processBuilder.redirectErrorStream(true); + File log = tempFolder.newFile("java-version.log"); + processBuilder.redirectOutput(log); + + Process process = processBuilder.start(); + + assertEquals("If redirected, should be -1 ", -1, process.getInputStream() + .read()); + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + + List lines = Files.lines(log.toPath()) + .collect(Collectors.toList()); + + assertThat("Results should not be empty", lines, is(not(empty()))); + assertThat("Results should contain java version: ", lines, hasItem(containsString("java version"))); + } + + @Test + public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessAppending() throws IOException, InterruptedException { + ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); + + File log = tempFolder.newFile("java-version-append.log"); + processBuilder.redirectErrorStream(true); + processBuilder.redirectOutput(Redirect.appendTo(log)); + + Process process = processBuilder.start(); + + assertEquals("If redirected output, should be -1 ", -1, process.getInputStream() + .read()); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + + List lines = Files.lines(log.toPath()) + .collect(Collectors.toList()); + + assertThat("Results should not be empty", lines, is(not(empty()))); + assertThat("Results should contain java version: ", lines, hasItem(containsString("java version"))); + } + +/* @Test + public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException { + List builders = Arrays.asList( + new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), + new ProcessBuilder("wc", "-l")); + + List processes = ProcessBuilder.startPipeline(builders); + Process last = processes.get(processes.size() - 1); + + List output = readOutput(last.getInputStream()); + assertThat("Results should not be empty", output, is(not(empty()))); + }*/ + + @Test + public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException { + List command = getEchoCommand(); + ProcessBuilder processBuilder = new ProcessBuilder(command); + + processBuilder.inheritIO(); + Process process = processBuilder.start(); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + private List readOutput(InputStream inputStream) throws IOException { + try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) { + return output.lines() + .collect(Collectors.toList()); + } + } + +} From 95c0513cfcea05a9a79f3ea03b46ef8f941c391a Mon Sep 17 00:00:00 2001 From: Jon Cook Date: Wed, 20 Feb 2019 23:17:09 +0100 Subject: [PATCH 020/254] BAEL-2541 - Guide to ProcessBuilder API - Move ProcessBuilderUnitTest to core-java-9 --- .../ProcessBuilderUnitTest.java | 57 ++++++++++--------- 1 file changed, 29 insertions(+), 28 deletions(-) rename {core-java => core-java-9}/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java (90%) diff --git a/core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java b/core-java-9/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java rename to core-java-9/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java index a18cc3e368..0458383e99 100644 --- a/core-java/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java +++ b/core-java-9/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.processbuilder; -import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasItem; @@ -83,24 +82,6 @@ public class ProcessBuilderUnitTest { assertEquals("No errors should be detected", 0, exitCode); } - private List getDirectoryListingCommand() { - return isWindows() ? Arrays.asList("cmd.exe", "/c", "dir") : Arrays.asList("/bin/sh", "-c", "ls"); - } - - private List getGreetingCommand() { - return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo %GREETING%") : Arrays.asList("/bin/bash", "-c", "echo $GREETING"); - } - - private List getEchoCommand() { - return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo hello") : Arrays.asList("/bin/sh", "-c", "echo hello"); - } - - private boolean isWindows() { - return System.getProperty("os.name") - .toLowerCase() - .startsWith("windows"); - } - @Test public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessWriting() throws IOException, InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); @@ -146,18 +127,20 @@ public class ProcessBuilderUnitTest { assertThat("Results should contain java version: ", lines, hasItem(containsString("java version"))); } -/* @Test + @Test public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException { - List builders = Arrays.asList( - new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), - new ProcessBuilder("wc", "-l")); + if (!isWindows()) { + List builders = Arrays.asList( + new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), + new ProcessBuilder("wc", "-l")); - List processes = ProcessBuilder.startPipeline(builders); - Process last = processes.get(processes.size() - 1); + List processes = ProcessBuilder.startPipeline(builders); + Process last = processes.get(processes.size() - 1); - List output = readOutput(last.getInputStream()); - assertThat("Results should not be empty", output, is(not(empty()))); - }*/ + List output = readOutput(last.getInputStream()); + assertThat("Results should not be empty", output, is(not(empty()))); + } + } @Test public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException { @@ -178,4 +161,22 @@ public class ProcessBuilderUnitTest { } } + private List getDirectoryListingCommand() { + return isWindows() ? Arrays.asList("cmd.exe", "/c", "dir") : Arrays.asList("/bin/sh", "-c", "ls"); + } + + private List getGreetingCommand() { + return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo %GREETING%") : Arrays.asList("/bin/bash", "-c", "echo $GREETING"); + } + + private List getEchoCommand() { + return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo hello") : Arrays.asList("/bin/sh", "-c", "echo hello"); + } + + private boolean isWindows() { + return System.getProperty("os.name") + .toLowerCase() + .startsWith("windows"); + } + } From c636b0d4b73ba3954c973766ec8d1dc63357733f Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Thu, 21 Feb 2019 23:56:32 +0100 Subject: [PATCH 021/254] java web application without web.xml - servlets 3.0 --- javax-servlets-3/.gitignore | 6 --- javax-servlets-3/Dockerfile | 2 - javax-servlets-3/README.md | 10 ---- javax-servlets-3/pom.xml | 52 ------------------- .../servlets3/spring/AppInitializer.java | 27 ---------- .../servlets3/spring/config/AppConfig.java | 11 ---- .../controllers/UppercaseController.java | 17 ------ .../baeldung}/filters/EmptyParamFilter.java | 4 +- .../com/baeldung}/listeners/AppListener.java | 2 +- .../baeldung}/listeners/RequestListener.java | 2 +- .../baeldung}/servlets/CounterServlet.java | 6 +-- .../baeldung}/servlets/UppercaseServlet.java | 6 +-- 12 files changed, 6 insertions(+), 139 deletions(-) delete mode 100644 javax-servlets-3/.gitignore delete mode 100644 javax-servlets-3/Dockerfile delete mode 100644 javax-servlets-3/README.md delete mode 100644 javax-servlets-3/pom.xml delete mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/AppInitializer.java delete mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/config/AppConfig.java delete mode 100644 javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/controllers/UppercaseController.java rename {javax-servlets-3/src/main/java/com/baeldung/servlets3/web => javax-servlets/src/main/java/com/baeldung}/filters/EmptyParamFilter.java (88%) rename {javax-servlets-3/src/main/java/com/baeldung/servlets3/web => javax-servlets/src/main/java/com/baeldung}/listeners/AppListener.java (91%) rename {javax-servlets-3/src/main/java/com/baeldung/servlets3/web => javax-servlets/src/main/java/com/baeldung}/listeners/RequestListener.java (94%) rename {javax-servlets-3/src/main/java/com/baeldung/servlets3/web => javax-servlets/src/main/java/com/baeldung}/servlets/CounterServlet.java (78%) rename {javax-servlets-3/src/main/java/com/baeldung/servlets3/web => javax-servlets/src/main/java/com/baeldung}/servlets/UppercaseServlet.java (78%) diff --git a/javax-servlets-3/.gitignore b/javax-servlets-3/.gitignore deleted file mode 100644 index dfbd063287..0000000000 --- a/javax-servlets-3/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# Created by .ignore support plugin (hsz.mobi) -.idea -classes -target -*.iml -out \ No newline at end of file diff --git a/javax-servlets-3/Dockerfile b/javax-servlets-3/Dockerfile deleted file mode 100644 index 27d1450acb..0000000000 --- a/javax-servlets-3/Dockerfile +++ /dev/null @@ -1,2 +0,0 @@ -FROM tomcat -ADD ./target/uppercasing-app.war /usr/local/tomcat/webapps/ \ No newline at end of file diff --git a/javax-servlets-3/README.md b/javax-servlets-3/README.md deleted file mode 100644 index 1f4855f4b3..0000000000 --- a/javax-servlets-3/README.md +++ /dev/null @@ -1,10 +0,0 @@ -## Build with maven: -mvn package - -## Run with Tomcat on Docker container: -docker build --tag my-tomcat . - -docker run -it --rm -p 8080:8080 my-tomcat - -## Relevant Articles: -- [Java Web Application Without Web.xml] diff --git a/javax-servlets-3/pom.xml b/javax-servlets-3/pom.xml deleted file mode 100644 index 8c339ce6d4..0000000000 --- a/javax-servlets-3/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - 4.0.0 - javax-servlets-3 - 1.0-SNAPSHOT - javax-servlets-3 - war - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - - 4.0.1 - 5.1.3.RELEASE - - - uppercasing-app - - - org.apache.maven.plugins - maven-war-plugin - 3.1.0 - - - default-war - prepare-package - - false - - - - - - - diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/AppInitializer.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/AppInitializer.java deleted file mode 100644 index 837d439cf4..0000000000 --- a/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/AppInitializer.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.servlets3.spring; - -import com.baeldung.servlets3.spring.config.AppConfig; -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -public class AppInitializer implements WebApplicationInitializer { - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.register(AppConfig.class); - - servletContext.addListener(new ContextLoaderListener(context)); - - ServletRegistration.Dynamic dispatcher = servletContext.addServlet("spring-dispatcher", - new DispatcherServlet(context)); - - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/spring/*"); - } -} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/config/AppConfig.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/config/AppConfig.java deleted file mode 100644 index 0088bad770..0000000000 --- a/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/config/AppConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.servlets3.spring.config; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -@Configuration -@EnableWebMvc -@ComponentScan("com.baeldung.servlets3.spring") -public class AppConfig { -} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/controllers/UppercaseController.java b/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/controllers/UppercaseController.java deleted file mode 100644 index 74585e6b5e..0000000000 --- a/javax-servlets-3/src/main/java/com/baeldung/servlets3/spring/controllers/UppercaseController.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.servlets3.spring.controllers; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/uppercase") -public class UppercaseController { - - @GetMapping(produces = "text/html") - public String getUppercase(@RequestParam(required = false)String param) { - String response = param != null ? param.toUpperCase() : "Missing param"; - return "From Spring: " + response; - } -} diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java b/javax-servlets/src/main/java/com/baeldung/filters/EmptyParamFilter.java similarity index 88% rename from javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java rename to javax-servlets/src/main/java/com/baeldung/filters/EmptyParamFilter.java index 61a7e896cc..b0b5392237 100644 --- a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/filters/EmptyParamFilter.java +++ b/javax-servlets/src/main/java/com/baeldung/filters/EmptyParamFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.servlets3.web.filters; +package com.baeldung.filters; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -9,7 +9,7 @@ import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import java.io.IOException; -@WebFilter(servletNames = { "uppercaseServlet" }, urlPatterns = "/uppercase") +@WebFilter(urlPatterns = "/uppercase") public class EmptyParamFilter implements Filter { @Override diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/AppListener.java b/javax-servlets/src/main/java/com/baeldung/listeners/AppListener.java similarity index 91% rename from javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/AppListener.java rename to javax-servlets/src/main/java/com/baeldung/listeners/AppListener.java index d61af65c31..ed16dd1654 100644 --- a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/AppListener.java +++ b/javax-servlets/src/main/java/com/baeldung/listeners/AppListener.java @@ -1,4 +1,4 @@ -package com.baeldung.servlets3.web.listeners; +package com.baeldung.listeners; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/RequestListener.java b/javax-servlets/src/main/java/com/baeldung/listeners/RequestListener.java similarity index 94% rename from javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/RequestListener.java rename to javax-servlets/src/main/java/com/baeldung/listeners/RequestListener.java index aeebf482fb..7f0c37b666 100644 --- a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/listeners/RequestListener.java +++ b/javax-servlets/src/main/java/com/baeldung/listeners/RequestListener.java @@ -1,4 +1,4 @@ -package com.baeldung.servlets3.web.listeners; +package com.baeldung.listeners; import javax.servlet.ServletContext; import javax.servlet.ServletRequestEvent; diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/CounterServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java similarity index 78% rename from javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/CounterServlet.java rename to javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java index 4bb92bbf77..b9ea55de73 100644 --- a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/CounterServlet.java +++ b/javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java @@ -1,4 +1,4 @@ -package com.baeldung.servlets3.web.servlets; +package com.baeldung.servlets; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -10,10 +10,6 @@ import java.io.PrintWriter; @WebServlet(urlPatterns = "/counter", name = "counterServlet") public class CounterServlet extends HttpServlet { - public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { - doGet(request, response); - } - public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); diff --git a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/UppercaseServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java similarity index 78% rename from javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/UppercaseServlet.java rename to javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java index 9b948cd994..0357ab28b5 100644 --- a/javax-servlets-3/src/main/java/com/baeldung/servlets3/web/servlets/UppercaseServlet.java +++ b/javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java @@ -1,4 +1,4 @@ -package com.baeldung.servlets3.web.servlets; +package com.baeldung.servlets; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -10,10 +10,6 @@ import java.io.PrintWriter; @WebServlet(urlPatterns = "/uppercase", name = "uppercaseServlet") public class UppercaseServlet extends HttpServlet { - public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { - doGet(request, response); - } - public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String inputString = request.getParameter("input").toUpperCase(); From 6a36c90be5f8cde0e93f4bd44ed8840e21797e37 Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Sat, 23 Feb 2019 22:07:49 +0100 Subject: [PATCH 022/254] removed content type set in servlets --- .../src/main/java/com/baeldung/servlets/CounterServlet.java | 2 -- .../src/main/java/com/baeldung/servlets/UppercaseServlet.java | 2 -- 2 files changed, 4 deletions(-) diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java index b9ea55de73..a11f084db2 100644 --- a/javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java +++ b/javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java @@ -11,8 +11,6 @@ import java.io.PrintWriter; public class CounterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); int count = (int)request.getServletContext().getAttribute("counter"); diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java index 0357ab28b5..766ec2e6ff 100644 --- a/javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java +++ b/javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java @@ -13,8 +13,6 @@ public class UppercaseServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String inputString = request.getParameter("input").toUpperCase(); - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); out.println(inputString); From b8411e44a3ca93797eaf2d15a4a8c3884a6f7939 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 27 Feb 2019 15:33:20 +0800 Subject: [PATCH 023/254] Update README.md --- spring-rest-full/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index 32b65ccc6a..ed6df1675f 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -12,7 +12,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Project Configuration with Spring](http://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) -- [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) +- [Bootstrap a Web Application with Spring 5](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) From dbb7b45460e7e1f60b909e37a6b28561ede9d523 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 27 Feb 2019 16:17:25 +0800 Subject: [PATCH 024/254] Update README.md --- aws/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/aws/README.md b/aws/README.md index 2c61928095..d14ea8a75e 100644 --- a/aws/README.md +++ b/aws/README.md @@ -4,7 +4,6 @@ - [AWS S3 with Java](http://www.baeldung.com/aws-s3-java) - [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda) - [Managing EC2 Instances in Java](http://www.baeldung.com/ec2-java) -- [http://www.baeldung.com/aws-s3-multipart-upload](https://github.com/eugenp/tutorials/tree/master/aws) - [Multipart Uploads in Amazon S3 with Java](http://www.baeldung.com/aws-s3-multipart-upload) - [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests) - [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3) From e60c69198eb27ca097894ac5cb3b2d143e139480 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 27 Feb 2019 16:46:15 +0800 Subject: [PATCH 025/254] Update README.md --- core-java-9/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-9/README.md b/core-java-9/README.md index d9586ba684..904782819c 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -16,7 +16,7 @@ - [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams) - [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new) - [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles) -- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client) +- [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client) - [Method Handles in Java](http://www.baeldung.com/java-method-handles) - [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) - [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity) From 3fe623dcabeba47b36fe5d50b7c1ff21ece4afe9 Mon Sep 17 00:00:00 2001 From: PranayJain Date: Wed, 27 Feb 2019 15:00:02 +0530 Subject: [PATCH 026/254] BAEL-2719: Spring Boot - Properties file outside jar --- .../ExternalPropertyFileLoader.java | 17 +++++++++++++ .../main/resources/external/conf.properties | 4 +++ .../ExternalPropertyFileLoaderUnitTest.java | 25 +++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java create mode 100644 spring-boot-ops/src/main/resources/external/conf.properties create mode 100644 spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderUnitTest.java diff --git a/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java new file mode 100644 index 0000000000..233ddc0195 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java @@ -0,0 +1,17 @@ +package com.baeldung.properties; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; + +@SpringBootApplication +public class ExternalPropertyFileLoader { + public static void main(String[] args) { + ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(ExternalPropertyFileLoader.class).properties("spring.config.name:conf", "spring.config.location:file:src/main/resources/external/") + .build() + .run(args); + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + environment.getProperty("username"); + } +} diff --git a/spring-boot-ops/src/main/resources/external/conf.properties b/spring-boot-ops/src/main/resources/external/conf.properties new file mode 100644 index 0000000000..a724b878b4 --- /dev/null +++ b/spring-boot-ops/src/main/resources/external/conf.properties @@ -0,0 +1,4 @@ +url=jdbc:postgresql://localhost:5432/ +username=admin +password=root +spring.main.allow-bean-definition-overriding=true diff --git a/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderUnitTest.java b/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderUnitTest.java new file mode 100644 index 0000000000..656d8561ec --- /dev/null +++ b/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.properties; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +public class ExternalPropertyFileLoaderUnitTest { + + @Test + public void whenExternalisedPropertiesLoaded_thenReadValues() { + ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(ExternalPropertyFileLoader.class).properties("spring.config.name:conf", "spring.config.location:file:src/main/resources/external/") + .build() + .run(); + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + Assert.assertEquals(environment.getProperty("url"), "jdbc:postgresql://localhost:5432/"); + Assert.assertEquals(environment.getProperty("username"), "admin"); + Assert.assertEquals(environment.getProperty("password"), "root"); + } + +} From 072e2232b08aaf27c194be5e86f527decd386b1e Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 17:00:45 +0800 Subject: [PATCH 027/254] Update README.MD --- persistence-modules/spring-boot-persistence/README.MD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-boot-persistence/README.MD b/persistence-modules/spring-boot-persistence/README.MD index 6fe5e6f05f..f62ca57a19 100644 --- a/persistence-modules/spring-boot-persistence/README.MD +++ b/persistence-modules/spring-boot-persistence/README.MD @@ -2,7 +2,7 @@ - [Spring Boot with Multiple SQL Import Files](http://www.baeldung.com/spring-boot-sql-import-files) - [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source) -- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) +- [Quick Guide on Loading Initial Data with Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) - [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool) - [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot) - [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb) From 397ca5b59f946312255e7c0f289554c2614a2cce Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 17:18:43 +0800 Subject: [PATCH 028/254] Update README.MD --- spring-cloud/spring-cloud-gateway/README.MD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-cloud/spring-cloud-gateway/README.MD b/spring-cloud/spring-cloud-gateway/README.MD index 48fbf41b8e..d945ae949c 100644 --- a/spring-cloud/spring-cloud-gateway/README.MD +++ b/spring-cloud/spring-cloud-gateway/README.MD @@ -1,2 +1,2 @@ ### Relevant Articles: -- [Explore the new Spring Cloud Gateway](http://www.baeldung.com/spring-cloud-gateway) +- [Exploring the new Spring Cloud Gateway](http://www.baeldung.com/spring-cloud-gateway) From 0661a109c7226a97b052599ae74ced53eb8b58a1 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 17:23:21 +0800 Subject: [PATCH 029/254] Update README.md --- jooby/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jooby/README.md b/jooby/README.md index 032e595354..aa867b2c56 100644 --- a/jooby/README.md +++ b/jooby/README.md @@ -1,3 +1,3 @@ ## Relevant articles: -- [Introduction to Jooby Project](http://www.baeldung.com/jooby) +- [Introduction to Jooby](http://www.baeldung.com/jooby) From b41efaaf6b851d7147185616f17a3548f3bb203e Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 17:30:09 +0800 Subject: [PATCH 030/254] Update README.md --- vavr/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vavr/README.md b/vavr/README.md index 0857765ec6..266cae91bb 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -4,7 +4,7 @@ - [Guide to Pattern Matching in Vavr](http://www.baeldung.com/vavr-pattern-matching) - [Property Testing Example With Vavr](http://www.baeldung.com/vavr-property-testing) - [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr) -- [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr) +- [Vavr Support in Spring Data](http://www.baeldung.com/spring-vavr) - [Introduction to Vavr’s Validation API](http://www.baeldung.com/vavr-validation-api) - [Guide to Collections API in Vavr](http://www.baeldung.com/vavr-collections) - [Collection Factory Methods for Vavr](http://www.baeldung.com/vavr-collection-factory-methods) From dad532bb537432a225f39b9814f326eefeafc324 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 17:32:45 +0800 Subject: [PATCH 031/254] Update README.md --- testing-modules/junit-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 4ed01e7fa9..e68d72efe3 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -3,7 +3,7 @@ - [A Guide to JUnit 5](http://www.baeldung.com/junit-5) - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) -- [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) +- [A Guide to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) - [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) - [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) - [JUnit 5 – @RunWith](http://www.baeldung.com/junit-5-runwith) From f7e2c8062304e551e9fa0bb62fd92a90ead9b17b Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 17:35:28 +0800 Subject: [PATCH 032/254] Update README.md --- spring-5-reactive/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index c39bb616f8..119e57f256 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -7,7 +7,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) - [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) -- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) +- [Exploring the Spring 5 MVC URL Matching](http://www.baeldung.com/spring-5-mvc-url-matching) - [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) From af1f80f1469730055ea81a94652cd564f0d94084 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 17:46:06 +0800 Subject: [PATCH 033/254] Update README.md --- core-kotlin/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 6ee79b2a2e..45163b3f99 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -4,7 +4,7 @@ - [A guide to the “when{}” block in Kotlin](http://www.baeldung.com/kotlin-when) - [Comprehensive Guide to Null Safety in Kotlin](http://www.baeldung.com/kotlin-null-safety) - [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability) -- [Difference Between “==” and “===” in Kotlin](http://www.baeldung.com/kotlin-equality-operators) +- [Difference Between “==” and “===” operators in Kotlin](http://www.baeldung.com/kotlin-equality-operators) - [Generics in Kotlin](http://www.baeldung.com/kotlin-generics) - [Introduction to Kotlin Coroutines](http://www.baeldung.com/kotlin-coroutines) - [Destructuring Declarations in Kotlin](http://www.baeldung.com/kotlin-destructuring-declarations) From df5e2493c1c05f1016283fd36058d02791734973 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 17:53:09 +0800 Subject: [PATCH 034/254] Update README.md --- core-java-networking/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-networking/README.md b/core-java-networking/README.md index b2367782b6..dd4ee1e151 100644 --- a/core-java-networking/README.md +++ b/core-java-networking/README.md @@ -13,4 +13,4 @@ - [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding) -- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) \ No newline at end of file +- [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) From 9ac6c2c8de8bf5fd27da13e9d8ba0bbe187e4791 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 19:23:55 +0800 Subject: [PATCH 035/254] Update README.md --- spring-rest/src/main/java/com/baeldung/produceimage/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-rest/src/main/java/com/baeldung/produceimage/README.md b/spring-rest/src/main/java/com/baeldung/produceimage/README.md index acd546598d..4aeadea546 100644 --- a/spring-rest/src/main/java/com/baeldung/produceimage/README.md +++ b/spring-rest/src/main/java/com/baeldung/produceimage/README.md @@ -1,3 +1,3 @@ ### Relevant articles -- [Returning an Image or a File with Spring](http://www.baeldung.com/spring-controller-return-image-file) +- [Download an Image or a File with Spring MVC](http://www.baeldung.com/spring-controller-return-image-file) From c9c6f879d08a72e0ce89d9e03ef98acdf9cd4048 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 19:45:23 +0800 Subject: [PATCH 036/254] Update README.md --- spark-java/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spark-java/README.md b/spark-java/README.md index 711607bd4e..5abe78263c 100644 --- a/spark-java/README.md +++ b/spark-java/README.md @@ -3,4 +3,4 @@ ## Spark Java Framework Tutorial Sample Project ### Relevant Articles -- [Intro to Spark Java Framework](http://www.baeldung.com/spark-framework-rest-api) +- [Building an API With the Spark Java Framework](http://www.baeldung.com/spark-framework-rest-api) From ffe5768eef005a83b8429620e78f961042c999e2 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 19:50:20 +0800 Subject: [PATCH 037/254] Update README.md --- spring-security-core/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-core/README.md b/spring-security-core/README.md index f7b3f6dffe..b38dc061b4 100644 --- a/spring-security-core/README.md +++ b/spring-security-core/README.md @@ -7,6 +7,6 @@ mvn clean install ``` ### Relevant Articles: -- [Intro to @PreFilter and @PostFilter in Spring Security](http://www.baeldung.com/spring-security-prefilter-postfilter) +- [Spring Security – @PreFilter and @PostFilter](http://www.baeldung.com/spring-security-prefilter-postfilter) - [Spring Boot Authentication Auditing Support](http://www.baeldung.com/spring-boot-authentication-audit) - [Introduction to Spring Method Security](http://www.baeldung.com/spring-security-method-security) From 0f5d447fac99e8506461ff11b6332a9e688cfd3e Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 19:53:36 +0800 Subject: [PATCH 038/254] Update README.md --- core-java-networking/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-networking/README.md b/core-java-networking/README.md index dd4ee1e151..f6ce44d72f 100644 --- a/core-java-networking/README.md +++ b/core-java-networking/README.md @@ -12,5 +12,5 @@ - [A Guide to the Java URL](http://www.baeldung.com/java-url) - [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) -- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding) +- [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding) - [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) From 433af3993b093cd9a1bab12fc7fd629bcb118016 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 19:55:45 +0800 Subject: [PATCH 039/254] Update README.md --- core-java-io/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-io/README.md b/core-java-io/README.md index 9a25009849..ac6d5c4eee 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -11,7 +11,7 @@ - [Java – Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer) - [Java – Directory Size](http://www.baeldung.com/java-folder-size) - [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library) -- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size) +- [File Size in Java](http://www.baeldung.com/java-file-size) - [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path) - [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer) - [Copy a File with Java](http://www.baeldung.com/java-copy-file) From dea68e021be5601723e094967ed76429083b9afa Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 19:57:32 +0800 Subject: [PATCH 040/254] Update README.md --- core-java-lang-syntax/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-lang-syntax/README.md b/core-java-lang-syntax/README.md index 99c8613929..e77a8a58cb 100644 --- a/core-java-lang-syntax/README.md +++ b/core-java-lang-syntax/README.md @@ -3,7 +3,7 @@ ## Core Java Lang Syntax Cookbooks and Examples ### Relevant Articles: -- [Introduction to Java Generics](http://www.baeldung.com/java-generics) +- [The Basics of Java Generics](http://www.baeldung.com/java-generics) - [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions) - [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization) - [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator) From 296f70dde9c1f9632a0c9b625d2ffc973358119d Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 19:58:41 +0800 Subject: [PATCH 041/254] Update README.md --- core-java-security/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-security/README.md b/core-java-security/README.md index d3343f79ca..9526b15be5 100644 --- a/core-java-security/README.md +++ b/core-java-security/README.md @@ -8,5 +8,5 @@ - [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) - [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures) -- [SHA-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) +- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) - [Enabling TLS v1.2 in Java 7](https://www.baeldung.com/java-7-tls-v12) From 76ecabe9614050691e4bbda9e83d5f7eb901ab34 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:04:22 +0800 Subject: [PATCH 042/254] Update README.md --- spring-security-rest-basic-auth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-rest-basic-auth/README.md b/spring-security-rest-basic-auth/README.md index f92fcfe36b..0c97b9b592 100644 --- a/spring-security-rest-basic-auth/README.md +++ b/spring-security-rest-basic-auth/README.md @@ -9,5 +9,5 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/how-to-use-resttemplate-with-basic-authentication-in-spring) - [HttpClient Timeout](http://www.baeldung.com/httpclient-timeout) - [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) -- [Writing a Custom Filter in Spring Security](http://www.baeldung.com/spring-security-custom-filter) +- [A Custom Filter in the Spring Security Filter Chain](http://www.baeldung.com/spring-security-custom-filter) - [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication) From 44c22f4fe77e283edad111dab826616d6712d9df Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:05:37 +0800 Subject: [PATCH 043/254] Update README.md --- spring-jms/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-jms/README.md b/spring-jms/README.md index b942cc72a0..55e74f18ff 100644 --- a/spring-jms/README.md +++ b/spring-jms/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: -- [An Introduction To Spring JMS](http://www.baeldung.com/spring-jms) +- [Getting Started with Spring JMS](http://www.baeldung.com/spring-jms) From 2480c458b9d05e6bc9218b2419ce583941b4f5f1 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:09:34 +0800 Subject: [PATCH 044/254] Update README.md --- core-java-collections-list/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-collections-list/README.md b/core-java-collections-list/README.md index 3a4a7c69e8..5fe84480db 100644 --- a/core-java-collections-list/README.md +++ b/core-java-collections-list/README.md @@ -5,7 +5,7 @@ ### Relevant Articles: - [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list) - [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) -- [Random List Element](http://www.baeldung.com/java-random-list-element) +- [Java – Get Random Item/Element From a List](http://www.baeldung.com/java-random-list-element) - [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list) - [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list) - [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list) From 98325175c57c78cbd246c7d3978d2e463ead77ec Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:16:14 +0800 Subject: [PATCH 045/254] Update README.md --- core-java-8/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-8/README.md b/core-java-8/README.md index 892dc71f76..fb4f54222d 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -4,7 +4,7 @@ ### Relevant Articles: - [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) -- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) +- [Functional Interfaces in Java 8](http://www.baeldung.com/java-8-functional-interfaces) - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) - [Java 8 New Features](http://www.baeldung.com/java-8-new-features) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) From 1a020467280fd9d3f465b84fcf4c9cd98e83a21d Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:18:10 +0800 Subject: [PATCH 046/254] Update README.md --- spring-all/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-all/README.md b/spring-all/README.md index 0d78efdcf2..791af2cb58 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -15,7 +15,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Profiles](http://www.baeldung.com/spring-profiles) - [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) - [What's New in Spring 4.3?](http://www.baeldung.com/whats-new-in-spring-4-3) -- [Guide To Running Logic on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) +- [Running Setup Data on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) - [Introduction To Ehcache](http://www.baeldung.com/ehcache) From 295bc9d070a1f9a9a8ec674acd89cb975543fbf3 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:19:16 +0800 Subject: [PATCH 047/254] Update README.md --- jsf/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jsf/README.md b/jsf/README.md index 6e0891182d..d96c1eb8e3 100644 --- a/jsf/README.md +++ b/jsf/README.md @@ -1,5 +1,5 @@ ### Relevant Articles: -- [Introduction to JSF Expression Language 3.0](http://www.baeldung.com/jsf-expression-language-el-3) +- [Guide to JSF Expression Language 3.0](http://www.baeldung.com/jsf-expression-language-el-3) - [Introduction to JSF EL 2](http://www.baeldung.com/intro-to-jsf-expression-language) - [JavaServer Faces (JSF) with Spring](http://www.baeldung.com/spring-jsf) - [Introduction to Primefaces](http://www.baeldung.com/jsf-primefaces) From 53d1331ea8eafd8f3ee4bfb7ea834c43b7f547d1 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:20:47 +0800 Subject: [PATCH 048/254] Update README.md --- persistence-modules/spring-hibernate-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index 5e287919f1..c48e58fcca 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -2,4 +2,4 @@ - [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) +- [JPA Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) From 44f84c548510f93ba7b5705ebea78d0d3d7763e8 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:23:44 +0800 Subject: [PATCH 049/254] Update README.md --- testing-modules/testing/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/testing/README.md b/testing-modules/testing/README.md index 849b578a55..e96b26ab41 100644 --- a/testing-modules/testing/README.md +++ b/testing-modules/testing/README.md @@ -3,7 +3,7 @@ ## Mutation Testing ### Relevant Articles: -- [Introduction to Mutation Testing Using the PITest Library](http://www.baeldung.com/java-mutation-testing-with-pitest) +- [Mutation Testing with PITest](http://www.baeldung.com/java-mutation-testing-with-pitest) - [Intro to JaCoCo](http://www.baeldung.com/jacoco) - [AssertJ’s Java 8 Features](http://www.baeldung.com/assertJ-java-8-features) - [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava) From cc5a956133d0b7b6bb426a15c2fce43d52a43ea7 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:25:32 +0800 Subject: [PATCH 050/254] Update README.md --- java-streams/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-streams/README.md b/java-streams/README.md index 15ea1c742a..b931c0d7d9 100644 --- a/java-streams/README.md +++ b/java-streams/README.md @@ -3,7 +3,7 @@ ## Java Streams Cookbooks and Examples ### Relevant Articles: -- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) +- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams) - [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) - [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) - [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany) From 850c0096662ae04b6db9a02026db9b5c6a909825 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:29:55 +0800 Subject: [PATCH 051/254] Update README.md --- core-java-8/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-8/README.md b/core-java-8/README.md index fb4f54222d..f601ea9d37 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -6,7 +6,7 @@ - [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) - [Functional Interfaces in Java 8](http://www.baeldung.com/java-8-functional-interfaces) - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) -- [Java 8 New Features](http://www.baeldung.com/java-8-new-features) +- [New Features in Java 8](http://www.baeldung.com/java-8-new-features) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector) From b0eac9be89ede158fc9b139797ef2d1545641781 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:33:41 +0800 Subject: [PATCH 052/254] Update README.md --- persistence-modules/spring-data-couchbase-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-data-couchbase-2/README.md b/persistence-modules/spring-data-couchbase-2/README.md index 2e56b25fef..2b6a1faddf 100644 --- a/persistence-modules/spring-data-couchbase-2/README.md +++ b/persistence-modules/spring-data-couchbase-2/README.md @@ -1,7 +1,7 @@ ## Spring Data Couchbase Tutorial Project ### Relevant Articles: -- [Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase) +- [Intro to Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase) - [Entity Validation, Query Consistency, and Optimistic Locking in Spring Data Couchbase](http://www.baeldung.com/entity-validation-locking-and-query-consistency-in-spring-data-couchbase) - [Multiple Buckets and Spatial View Queries in Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase-buckets-and-spatial-view-queries) From 5ebfdee1501256f1c403ecfcb3132cf8bc0cb97f Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:35:00 +0800 Subject: [PATCH 053/254] Update README.md --- spring-katharsis/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-katharsis/README.md b/spring-katharsis/README.md index cf2a001760..2082de2dda 100644 --- a/spring-katharsis/README.md +++ b/spring-katharsis/README.md @@ -6,4 +6,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [JSON API in a Java Web Application](http://www.baeldung.com/json-api-java-spring-web-app) +- [JSON API in a Spring Application](http://www.baeldung.com/json-api-java-spring-web-app) From 847d694adfef47554d37f3cc8c4474b3e272d6a0 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:36:16 +0800 Subject: [PATCH 054/254] Update README.md --- spring-resttemplate/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md index 1c8ddf73f9..353e9f955e 100644 --- a/spring-resttemplate/README.md +++ b/spring-resttemplate/README.md @@ -4,7 +4,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) +- [The Guide to RestTemplate](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) From fd4104c8fd668f3c89b9eb2bb8458f867ab397b7 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:39:35 +0800 Subject: [PATCH 055/254] Update README.md --- jackson/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jackson/README.md b/jackson/README.md index e201a06727..0806575367 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -17,7 +17,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Jackson JSON Tutorial](http://www.baeldung.com/jackson) - [Jackson – Working with Maps and nulls](http://www.baeldung.com/jackson-map-null-values-or-null-key) - [Jackson – Decide What Fields Get Serialized/Deserializaed](http://www.baeldung.com/jackson-field-serializable-deserializable-or-not) -- [A Guide to Jackson Annotations](http://www.baeldung.com/jackson-annotations) +- [Jackson Annotation Examples](http://www.baeldung.com/jackson-annotations) - [Working with Tree Model Nodes in Jackson](http://www.baeldung.com/jackson-json-node-tree-model) - [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) - [Intro to the Jackson ObjectMapper](http://www.baeldung.com/jackson-object-mapper-tutorial) From d9debd5daf484dc9e15a78da3401952f1888e88e Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:42:40 +0800 Subject: [PATCH 056/254] Update README.md --- testing-modules/mockito/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index 158a1918e7..59954784f9 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -7,7 +7,7 @@ - [Mockito Verify Cookbook](http://www.baeldung.com/mockito-verify) - [Mockito When/Then Cookbook](http://www.baeldung.com/mockito-behavior) - [Mockito – Using Spies](http://www.baeldung.com/mockito-spy) -- [Mockito – @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations) +- [Getting Started with Mockito @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations) - [Mockito’s Mock Methods](http://www.baeldung.com/mockito-mock-methods) - [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock) - [Mocking Exception Throwing using Mockito](http://www.baeldung.com/mockito-exceptions) From 3728f2e2618000ba40a6186aba3ef78655aee0e1 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:47:08 +0800 Subject: [PATCH 057/254] Update README.md --- spring-security-rest-basic-auth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-rest-basic-auth/README.md b/spring-security-rest-basic-auth/README.md index 0c97b9b592..30da3afbcf 100644 --- a/spring-security-rest-basic-auth/README.md +++ b/spring-security-rest-basic-auth/README.md @@ -6,7 +6,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: -- [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/how-to-use-resttemplate-with-basic-authentication-in-spring) +- [Basic Authentication with the RestTemplate](http://www.baeldung.com/how-to-use-resttemplate-with-basic-authentication-in-spring) - [HttpClient Timeout](http://www.baeldung.com/httpclient-timeout) - [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) - [A Custom Filter in the Spring Security Filter Chain](http://www.baeldung.com/spring-security-custom-filter) From f463cc341e48444cd0ae32ce1cde7fb2c8c6abfa Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:48:31 +0800 Subject: [PATCH 058/254] Update README.md --- httpclient/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/httpclient/README.md b/httpclient/README.md index 93e0f3c9e1..19886be750 100644 --- a/httpclient/README.md +++ b/httpclient/README.md @@ -14,7 +14,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Unshorten URLs with HttpClient](http://www.baeldung.com/unshorten-url-httpclient) - [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) - [HttpClient 4 – Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post) -- [HttpClient – Set Custom Header](http://www.baeldung.com/httpclient-custom-http-header) +- [Custom HTTP Header with the HttpClient](http://www.baeldung.com/httpclient-custom-http-header) - [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication) - [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload) - [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial) From ffc4ab61b4421e4c4f72bcf5f5a5e47e8ea3d81c Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:49:57 +0800 Subject: [PATCH 059/254] Update README.md --- jackson/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jackson/README.md b/jackson/README.md index 0806575367..519673738f 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -10,7 +10,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array) - [Jackson Unmarshalling json with Unknown Properties](http://www.baeldung.com/jackson-deserialize-json-unknown-properties) - [Jackson – Custom Serializer](http://www.baeldung.com/jackson-custom-serialization) -- [Jackson – Custom Deserializer](http://www.baeldung.com/jackson-deserialization) +- [Getting Started with Custom Deserialization in Jackson](http://www.baeldung.com/jackson-deserialization) - [Jackson Exceptions – Problems and Solutions](http://www.baeldung.com/jackson-exception) - [Jackson Date](http://www.baeldung.com/jackson-serialize-dates) - [Jackson – Bidirectional Relationships](http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion) From 5b65fc65dc0a37465c414b7840fd5907dccb747a Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:51:04 +0800 Subject: [PATCH 060/254] Update README.md --- core-java-io/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-io/README.md b/core-java-io/README.md index ac6d5c4eee..5e0f7bfbd1 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -3,7 +3,7 @@ ## Core Java IO Cookbooks and Examples ### Relevant Articles: -- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file) +- [How to Read a Large File Efficiently with Java](http://www.baeldung.com/java-read-lines-large-file) - [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string) - [Java – Write to File](http://www.baeldung.com/java-write-to-file) - [Java - Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream) From 1b8f5e1837834c1506ebe269b8993150eed29336 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:54:45 +0800 Subject: [PATCH 061/254] Update README.md --- httpclient/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/httpclient/README.md b/httpclient/README.md index 19886be750..7c5122c5b8 100644 --- a/httpclient/README.md +++ b/httpclient/README.md @@ -21,4 +21,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide) - [Advanced HttpClient Configuration](http://www.baeldung.com/httpclient-advanced-config) - [HttpClient 4 – Do Not Follow Redirects](http://www.baeldung.com/httpclient-stop-follow-redirect) -- [HttpClient 4 – Setting a Custom User-Agent](http://www.baeldung.com/httpclient-user-agent-header) +- [Custom User-Agent in HttpClient 4](http://www.baeldung.com/httpclient-user-agent-header) From 4ddb3c8c6f936fcea37541d1d1287c79f84cbd69 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:56:39 +0800 Subject: [PATCH 062/254] Update README.md --- spring-all/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-all/README.md b/spring-all/README.md index 791af2cb58..6e392088d9 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -11,7 +11,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant articles: - [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire) -- [Properties with Spring](http://www.baeldung.com/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage +- [Properties with Spring and Spring Boot](http://www.baeldung.com/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage - [Spring Profiles](http://www.baeldung.com/spring-profiles) - [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) - [What's New in Spring 4.3?](http://www.baeldung.com/whats-new-in-spring-4-3) From db2454c10f6ebbca45a678e54b8a677174bb8157 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:57:35 +0800 Subject: [PATCH 063/254] Update README.md --- spring-mvc-xml/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 3199118281..dbc6125424 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -8,7 +8,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) +- [Java 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) - [Guide to JavaServer Pages (JSP)](http://www.baeldung.com/jsp) From 10fe310a930aae4bef7bf7954cd10e3017006931 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 20:59:23 +0800 Subject: [PATCH 064/254] Update README.md --- spring-security-mvc-session/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-session/README.md b/spring-security-mvc-session/README.md index fc44209640..ce40ed5f5f 100644 --- a/spring-security-mvc-session/README.md +++ b/spring-security-mvc-session/README.md @@ -7,7 +7,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [HttpSessionListener Example – Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics) -- [Spring Security Session Management](http://www.baeldung.com/spring-security-session) +- [Control the Session with Spring Security](http://www.baeldung.com/spring-security-session) ### Build the Project From 4df758c4e217ad57842ce0a61fbeb28b1b233510 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 21:00:50 +0800 Subject: [PATCH 065/254] Update README.md --- persistence-modules/spring-hibernate4/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index 57a341ed45..c6d846a18d 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -3,7 +3,7 @@ ## Spring with Hibernate 4 Example Project ### Relevant Articles: -- [Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring) +- [Guide to Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring) - [The DAO with Spring 3 and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination) - [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort) From e3ba00d4fdd6fdfada6b38dae2c17fdc26b11c8f Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 21:01:26 +0800 Subject: [PATCH 066/254] Update README.md --- persistence-modules/spring-hibernate4/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index c6d846a18d..f2553ad229 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -4,7 +4,7 @@ ### Relevant Articles: - [Guide to Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring) -- [The DAO with Spring 3 and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination) - [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort) - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) From 60d198882476d3579693929fad8e4755c94d4cfd Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 21:05:52 +0800 Subject: [PATCH 067/254] Update README.md --- core-java-lang-syntax/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-lang-syntax/README.md b/core-java-lang-syntax/README.md index e77a8a58cb..81c3d6c354 100644 --- a/core-java-lang-syntax/README.md +++ b/core-java-lang-syntax/README.md @@ -8,7 +8,7 @@ - [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization) - [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator) - [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break) -- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) +- [A Guide to Creating Objects in Java](http://www.baeldung.com/java-initialization) - [A Guide to Java Loops](http://www.baeldung.com/java-loops) - [Varargs in Java](http://www.baeldung.com/java-varargs) - [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) From d7c44430102f40540414b1941c43f3af69e4d688 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 21:15:55 +0800 Subject: [PATCH 068/254] Update README.md --- testing-modules/junit-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index e68d72efe3..abd50261e7 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -8,7 +8,7 @@ - [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) - [JUnit 5 – @RunWith](http://www.baeldung.com/junit-5-runwith) - [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) -- [JUnit Assert an Exception is Thrown](http://www.baeldung.com/junit-assert-exception) +- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) - [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) - [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) - [JUnit5 Programmatic Extension Registration with @RegisterExtension](http://www.baeldung.com/junit-5-registerextension-annotation) From ffc06440554a22eae0e94634695168831c9ec979 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 21:17:44 +0800 Subject: [PATCH 069/254] Update README.md --- spring-all/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-all/README.md b/spring-all/README.md index 6e392088d9..81dd435007 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -28,7 +28,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view) - [A Guide To Caching in Spring](http://www.baeldung.com/spring-cache-tutorial) - [How To Do @Async in Spring](http://www.baeldung.com/spring-async) -- [Quick Guide to the Spring @Order Annotation](http://www.baeldung.com/spring-order) +- [@Order in Spring](http://www.baeldung.com/spring-order) - [Spring Web Contexts](http://www.baeldung.com/spring-web-contexts) - [Spring Cache – Creating a Custom KeyGenerator](http://www.baeldung.com/spring-cache-custom-keygenerator) - [Spring @Primary Annotation](http://www.baeldung.com/spring-primary) From 1e8cc42e2072f0a39e77e4b8d7031120ff4f26b6 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 21:20:04 +0800 Subject: [PATCH 070/254] Update README.md --- java-strings/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-strings/README.md b/java-strings/README.md index 1ab5e098f6..fc9748cd2c 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -22,7 +22,7 @@ - [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) - [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) - [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) -- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords) +- [Use char[] Array Over a String for Manipulating Passwords in Java?](http://www.baeldung.com/java-storing-passwords) - [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case) - [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) - [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) From df9935ce979d952bf2c5e8be4de5a95853698f82 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 21:22:25 +0800 Subject: [PATCH 071/254] Update README.md --- persistence-modules/hibernate5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index a4e95a9062..b7f2cd8387 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -18,7 +18,7 @@ - [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) - [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy) - [Proxy in Hibernate load() Method](https://www.baeldung.com/hibernate-proxy-load-method) -- [Custom Types in Hibernate](https://www.baeldung.com/hibernate-custom-types) +- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) - [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) - [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) - [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api) From ee475e09d703591f8262941de6ebd6ef4540f7d0 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Thu, 28 Feb 2019 21:54:27 +0800 Subject: [PATCH 072/254] Update README.md --- spring-boot-bootstrap/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 2186aa8fec..70fcd90118 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -1,5 +1,5 @@ ### Relevant Articles: -- [Bootstrap a Simple Application using Spring Boot](http://www.baeldung.com/spring-boot-start) +- [Spring Boot Tutorial – Bootstrap a Simple Application](http://www.baeldung.com/spring-boot-start) - [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) - [Thin JARs with Spring Boot](http://www.baeldung.com/spring-boot-thin-jar) - [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry) From d62fd333b0b8f6a0eb953d6b7720093f3b58b977 Mon Sep 17 00:00:00 2001 From: Jonathan Paul Cook Date: Thu, 28 Feb 2019 17:09:00 +0100 Subject: [PATCH 073/254] BAEL-2512 - Add a new section in Mockito Spy article --- .../misusing/MockitoMisusingUnitTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java new file mode 100644 index 0000000000..e2de23aa14 --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java @@ -0,0 +1,30 @@ +package org.baeldung.mockito.misusing; + +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.exceptions.misusing.NotAMockException; + +public class MockitoMisusingUnitTest { + + @Test + public void givenNotASpy_whenDoReturn_thenThrowNotAMock() { + try { + List list = new ArrayList(); + Mockito.doReturn(100) + .when(list) + .size(); + + fail("Should have thrown a NotAMockException because 'list' is not a mock!"); + } catch (NotAMockException e) { + assertThat(e.getMessage(), containsString("Argument passed to when() is not a mock!")); + } + } + +} From f067f5a0f5f254ec919c09b6d0a851abc0ebffaa Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Thu, 28 Feb 2019 22:15:51 +0530 Subject: [PATCH 074/254] BAEL-10890 Added aggregator poms in several projects, cleaned up main pom.xml --- cas/pom.xml | 21 ++++ guava-modules/pom.xml | 22 ++++ logging-modules/pom.xml | 23 ++++ persistence-modules/pom.xml | 58 ++++++++++ pom.xml | 198 ++++----------------------------- rule-engines/pom.xml | 22 ++++ spring-security-client/pom.xml | 25 +++++ testing-modules/pom.xml | 36 ++++++ 8 files changed, 230 insertions(+), 175 deletions(-) create mode 100644 cas/pom.xml create mode 100644 guava-modules/pom.xml create mode 100644 logging-modules/pom.xml create mode 100644 persistence-modules/pom.xml create mode 100644 rule-engines/pom.xml create mode 100644 spring-security-client/pom.xml create mode 100644 testing-modules/pom.xml diff --git a/cas/pom.xml b/cas/pom.xml new file mode 100644 index 0000000000..ac766ae5bf --- /dev/null +++ b/cas/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + cas + cas + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + cas-secured-app + cas-server + + + diff --git a/guava-modules/pom.xml b/guava-modules/pom.xml new file mode 100644 index 0000000000..7a5f217c15 --- /dev/null +++ b/guava-modules/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + guava-modules + guava-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + guava-18 + guava-19 + guava-21 + + + diff --git a/logging-modules/pom.xml b/logging-modules/pom.xml new file mode 100644 index 0000000000..d48955b1b8 --- /dev/null +++ b/logging-modules/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + logging-modules + logging-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + log4j + log4j2 + logback + log-mdc + + + diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml new file mode 100644 index 0000000000..beba135d7f --- /dev/null +++ b/persistence-modules/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + persistence-modules + persistence-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + activejdbc + apache-cayenne + core-java-persistence + deltaspike + flyway + hbase + hibernate5 + hibernate-ogm + influxdb + java-cassandra + java-cockroachdb + java-jdbi + java-jpa + java-mongodb + jnosql + liquibase + orientdb + querydsl + redis + solr + spring-boot-h2/spring-boot-h2-database + spring-boot-persistence + spring-boot-persistence-mongodb + spring-data-cassandra + spring-data-cassandra-reactive + spring-data-couchbase-2 + spring-data-dynamodb + spring-data-eclipselink + spring-data-elasticsearch + spring-data-gemfire + spring-data-jpa + spring-data-keyvalue + spring-data-mongodb + spring-data-neo4j + spring-data-redis + spring-data-solr + spring-hibernate-3 + spring-hibernate-5 + spring-hibernate4 + spring-jpa + + diff --git a/pom.xml b/pom.xml index 0a401299ba..d26b96ea8e 100644 --- a/pom.xml +++ b/pom.xml @@ -371,8 +371,7 @@ bootique - cas/cas-secured-app - cas/cas-server + cas cdi checker-plugin core-groovy @@ -422,9 +421,7 @@ gson guava guava-collections - guava-modules/guava-18 - guava-modules/guava-19 - guava-modules/guava-21 + guava-modules guice @@ -475,16 +472,13 @@ kotlin-libraries - libraries + libraries libraries-data libraries-apache-commons libraries-security libraries-server linkrest - logging-modules/log4j - logging-modules/log4j2 - logging-modules/logback - logging-modules/log-mdc + logging-modules lombok lucene @@ -515,45 +509,7 @@ 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-elasticsearch - persistence-modules/spring-data-gemfire - persistence-modules/spring-data-jpa - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-mongodb - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-redis - persistence-modules/spring-data-solr - persistence-modules/spring-hibernate-3 - persistence-modules/spring-hibernate-5 - persistence-modules/spring-hibernate4 - persistence-modules/spring-jpa + persistence-modules rabbitmq @@ -563,9 +519,7 @@ resteasy restx - rule-engines/easy-rules - rule-engines/openl-tablets - rule-engines/rulebook + rule-engines rsocket rxjava rxjava-2 @@ -721,13 +675,7 @@ 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-client spring-security-core spring-security-mvc-boot @@ -773,24 +721,7 @@ 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 + testing-modules twilio Twitter4J @@ -849,8 +780,7 @@ spring-apache-camel spring-batch spring-bom - spring-boot-admin/spring-boot-admin-client - spring-boot-admin/spring-boot-admin-server + spring-boot-admin spring-boot-bootstrap spring-boot-bootstrap spring-boot-camel @@ -862,22 +792,18 @@ spring-boot-jasypt spring-boot-keycloak spring-boot-mvc - spring-boot-property-exp/property-exp-custom-config - spring-boot-property-exp/property-exp-default-config + spring-boot-property-exp spring-boot-vue spring-cloud spring-cloud/spring-cloud-archaius/basic-config spring-cloud/spring-cloud-archaius/extra-configs spring-cloud/spring-cloud-bootstrap/config - spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer - spring-cloud/spring-cloud-contract/spring-cloud-contract-producer + spring-cloud/spring-cloud-contract spring-cloud/spring-cloud-gateway spring-cloud/spring-cloud-kubernetes/demo-backend spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server spring-cloud/spring-cloud-ribbon-client - spring-cloud/spring-cloud-security/auth-client - spring-cloud/spring-cloud-security/auth-resource - spring-cloud/spring-cloud-security/auth-server + spring-cloud/spring-cloud-security spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit spring-cloud/spring-cloud-task/springcloudtasksink spring-cloud/spring-cloud-zookeeper @@ -925,13 +851,7 @@ spring-security-acl spring-security-angular spring-security-cache-control - spring-security-client/spring-security-jsp-authentication - spring-security-client/spring-security-jsp-authorize - spring-security-client/spring-security-jsp-config - spring-security-client/spring-security-mvc - spring-security-client/spring-security-thymeleaf-authentication - spring-security-client/spring-security-thymeleaf-authorize - spring-security-client/spring-security-thymeleaf-config + spring-security-client spring-security-core spring-security-mvc-boot spring-security-mvc-custom @@ -941,14 +861,11 @@ spring-security-mvc-session spring-security-mvc-socket spring-security-rest - spring-security-sso/spring-security-sso-auth-server - spring-security-sso/spring-security-sso-ui - spring-security-sso/spring-security-sso-ui-2 + spring-security-sso spring-security-thymeleaf/spring-security-thymeleaf-authentication spring-security-thymeleaf/spring-security-thymeleaf-authorize spring-security-thymeleaf/spring-security-thymeleaf-config - spring-security-x509/spring-security-x509-basic-auth - spring-security-x509/spring-security-x509-client-auth + spring-security-x509 spring-session/spring-session-jdbc spring-sleuth spring-social-login @@ -1090,8 +1007,7 @@ bootique - cas/cas-secured-app - cas/cas-server + cas cdi checker-plugin core-groovy @@ -1140,9 +1056,7 @@ gson guava guava-collections - guava-modules/guava-18 - guava-modules/guava-19 - guava-modules/guava-21 + guava-modules guice @@ -1199,10 +1113,7 @@ libraries-security libraries-server linkrest - logging-modules/log4j - logging-modules/log4j2 - logging-modules/logback - logging-modules/log-mdc + logging-modules lombok lucene @@ -1233,46 +1144,8 @@ 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-elasticsearch - persistence-modules/spring-data-gemfire - persistence-modules/spring-data-jpa - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-mongodb - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-redis - persistence-modules/spring-data-solr - persistence-modules/spring-hibernate-3 - persistence-modules/spring-hibernate-5 - persistence-modules/spring-hibernate4 - persistence-modules/spring-jpa - + persistence-modules + rabbitmq ratpack @@ -1281,9 +1154,7 @@ resteasy restx - rule-engines/easy-rules - rule-engines/openl-tablets - rule-engines/rulebook + rule-engines rsocket rxjava rxjava-2 @@ -1434,13 +1305,7 @@ 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-client spring-security-core spring-security-mvc-boot @@ -1485,24 +1350,7 @@ 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 + testing-modules twilio Twitter4J diff --git a/rule-engines/pom.xml b/rule-engines/pom.xml new file mode 100644 index 0000000000..2b3f2f530b --- /dev/null +++ b/rule-engines/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + rule-engines + rule-engines + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + easy-rules + openl-tablets + rulebook + + + diff --git a/spring-security-client/pom.xml b/spring-security-client/pom.xml new file mode 100644 index 0000000000..aa424ca759 --- /dev/null +++ b/spring-security-client/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + spring-security-client + spring-security-client + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + spring-security-jsp-authentication + spring-security-jsp-authorize + spring-security-jsp-config + spring-security-mvc + spring-security-thymeleaf-authentication + spring-security-thymeleaf-authorize + spring-security-thymeleaf-config + + diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml new file mode 100644 index 0000000000..6a3c2399f8 --- /dev/null +++ b/testing-modules/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + testing-modules + testing-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + gatling + groovy-spock + junit-5 + junit5-migration + load-testing-comparison + mockito + mockito-2 + mocks + mockserver + parallel-tests-junit + rest-assured + rest-testing + + selenium-junit-testng + spring-testing + test-containers + testing + testng + + From a2f1f59e1f3cae524892ed515dcfee58bc543bab Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Thu, 28 Feb 2019 22:21:29 +0530 Subject: [PATCH 075/254] BAEL-10890 Fixed minor formatting --- cas/pom.xml | 2 +- guava-modules/pom.xml | 4 ++-- logging-modules/pom.xml | 6 +++--- persistence-modules/pom.xml | 2 +- rule-engines/pom.xml | 4 ++-- spring-security-client/pom.xml | 2 +- testing-modules/pom.xml | 2 +- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/cas/pom.xml b/cas/pom.xml index ac766ae5bf..6d141277c5 100644 --- a/cas/pom.xml +++ b/cas/pom.xml @@ -15,7 +15,7 @@ cas-secured-app - cas-server + cas-server diff --git a/guava-modules/pom.xml b/guava-modules/pom.xml index 7a5f217c15..fed9e446f7 100644 --- a/guava-modules/pom.xml +++ b/guava-modules/pom.xml @@ -15,8 +15,8 @@ guava-18 - guava-19 - guava-21 + guava-19 + guava-21 diff --git a/logging-modules/pom.xml b/logging-modules/pom.xml index d48955b1b8..a303e50ff1 100644 --- a/logging-modules/pom.xml +++ b/logging-modules/pom.xml @@ -15,9 +15,9 @@ log4j - log4j2 - logback - log-mdc + log4j2 + logback + log-mdc diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index beba135d7f..47c733d8a7 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -54,5 +54,5 @@ spring-hibernate-5 spring-hibernate4 spring-jpa - + diff --git a/rule-engines/pom.xml b/rule-engines/pom.xml index 2b3f2f530b..2ce82ed22b 100644 --- a/rule-engines/pom.xml +++ b/rule-engines/pom.xml @@ -15,8 +15,8 @@ easy-rules - openl-tablets - rulebook + openl-tablets + rulebook diff --git a/spring-security-client/pom.xml b/spring-security-client/pom.xml index aa424ca759..96ac837a09 100644 --- a/spring-security-client/pom.xml +++ b/spring-security-client/pom.xml @@ -21,5 +21,5 @@ spring-security-thymeleaf-authentication spring-security-thymeleaf-authorize spring-security-thymeleaf-config - + diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 6a3c2399f8..39047fb756 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -32,5 +32,5 @@ test-containers testing testng - + From d753bd3bd39a4256362d8ce4fdca7fecb895fa19 Mon Sep 17 00:00:00 2001 From: Josephine Barboza Date: Thu, 28 Feb 2019 22:57:01 +0530 Subject: [PATCH 076/254] BAEL-2725 Lists in Groovy --- .../groovy/com/baeldung/lists/ListTest.groovy | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy b/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy new file mode 100644 index 0000000000..89a0194742 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy @@ -0,0 +1,170 @@ +package com.baeldung.groovy.lists + +import static groovy.test.GroovyAssert.* +import org.junit.Test + +class ListTest{ + + @Test + void testCreateList() { + + def list = [1, 2, 3] + assertNotNull(list) + + def listMix = ['A', "b", 1, true] + assertTrue(listMix == ['A', "b", 1, true]) + + def linkedList = [1, 2, 3] as LinkedList + assertTrue(linkedList instanceof LinkedList) + + ArrayList arrList = [1, 2, 3] + assertTrue(arrList.class == ArrayList) + + def list2 = new ArrayList(arrList) + assertTrue(list2 == arrList) + + def list3 = arrList.clone() + assertTrue(list3 == arrList) + } + + @Test + void testCreateEmptyList() { + + def emptyList = [] + assertTrue(emptyList.size() == 0) + } + + @Test + void testCompareTwoLists() { + + def list1 = [5, 6.0, 'p'] + def list2 = [5, 6.0, 'p'] + assertTrue(list1 == list2) + } + + @Test + void testGetItemsFromList(){ + + def list = ["Hello", "World"] + + assertTrue(list.get(1) == "World") + assertTrue(list[1] == "World") + assertTrue(list[-1] == "World") + assertTrue(list.getAt(1) == "World") + assertTrue(list.getAt(-2) == "Hello") + } + + @Test + void testAddItemsToList() { + + def list = [] + + list << 1 + list.add("Apple") + assertTrue(list == [1, "Apple"]) + + list[2] = "Box" + list[4] = true + assertTrue(list == [1, "Apple", "Box", null, true]) + + list.add(1, 6.0) + assertTrue(list == [1, 6.0, "Apple", "Box", null, true]) + + def list2 = [1, 2] + list += list2 + list += 12 + assertTrue(list == [1, 6.0, "Apple", "Box", null, true, 1, 2, 12]) + } + + @Test + void testUpdateItemsInList() { + + def list =[1, "Apple", 80, "App"] + list[1] = "Box" + list.set(2,90) + assertTrue(list == [1, "Box", 90, "App"]) + } + + @Test + void testRemoveItemsFromList(){ + + def list = [1, 2, 3, 4, 5, 5, 6, 6, 7] + + list.remove(3) + assertTrue(list == [1, 2, 3, 5, 5, 6, 6, 7]) + + list.removeElement(5) + assertTrue(list == [1, 2, 3, 5, 6, 6, 7]) + + assertTrue(list - 6 == [1, 2, 3, 5, 7]) + } + + @Test + void testIteratingOnAList(){ + + def list = [1, "App", 3, 4] + list.each{ println it * 2} + + list.eachWithIndex{ it, i -> println "$i : $it" } + } + + @Test + void testCollectingToAnotherList(){ + + def list = ["Kay", "Henry", "Justin", "Tom"] + assertTrue(list.collect{"Hi " + it} == ["Hi Kay", "Hi Henry", "Hi Justin", "Hi Tom"]) + } + + @Test + void testJoinItemsInAList(){ + assertTrue(["One", "Two", "Three"].join(",") == "One,Two,Three") + } + + @Test + void testFilteringOnLists(){ + def list = [2, 1, 3, 4, 5, 6, 76] + + assertTrue(list.find{it > 3} == 4) + + assertTrue(list.findAll{it > 3} == [4, 5, 6, 76]) + + assertTrue(list.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76]) + + assertFalse(list.every{ it < 6}) + + assertTrue(list.any{ it%2 == 0}) + + assertTrue(list.grep( Number )== [2, 1, 3, 4, 5, 6, 76]) + + assertTrue(list.grep{ it> 6 }== [76]) + } + + @Test + void testGetUniqueItemsInAList(){ + assertTrue([1, 3, 3, 4].toUnique() == [1, 3, 4]) + + def list = [1, 3, 3, 4] + list.unique() + assertTrue(list == [1, 3, 4]) + + assertTrue(["A", "B", "Ba", "Bat", "Cat"].toUnique{ it.size()} == ["A", "Ba", "Bat"]) + } + + @Test + void testSorting(){ + + assertTrue([1, 2, 1, 0].sort() == [0, 1, 1, 2]) + Comparator mc = {a,b -> a == b? 0: a < b? 1 : -1} + + def list = [1, 2, 1, 0] + list.sort(mc) + assertTrue(list == [2, 1, 1, 0]) + + def list1 = ["na", "ppp", "as"] + assertTrue(list1.max() == "ppp") + + Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1} + def list2 = [3, 2, 0, 7] + assertTrue(list2.min(minc) == 0) + } +} \ No newline at end of file From 23010dd32a5e88c095bcb2048dd113b7aced7a42 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 1 Mar 2019 18:40:44 +0800 Subject: [PATCH 077/254] Update README.md --- core-java-networking/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-networking/README.md b/core-java-networking/README.md index f6ce44d72f..faeeadab24 100644 --- a/core-java-networking/README.md +++ b/core-java-networking/README.md @@ -9,7 +9,7 @@ - [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java) - [Sending Emails with Java](http://www.baeldung.com/java-email) - [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java) -- [A Guide to the Java URL](http://www.baeldung.com/java-url) +- [A Simple Guide to the Java URL](http://www.baeldung.com/java-url) - [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding) From 6189d4645e8d0ee3799080c7d8e06c2c1a08b3f0 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 1 Mar 2019 18:43:45 +0800 Subject: [PATCH 078/254] Update README.md --- spring-remoting/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-remoting/README.md b/spring-remoting/README.md index 7d344a3f27..0898b9b002 100644 --- a/spring-remoting/README.md +++ b/spring-remoting/README.md @@ -4,7 +4,7 @@ - [Intro to Spring Remoting with HTTP Invokers](http://www.baeldung.com/spring-remoting-http-invoker) - [Spring Remoting with Hessian and Burlap](http://www.baeldung.com/spring-remoting-hessian-burlap) - [Spring Remoting with AMQP](http://www.baeldung.com/spring-remoting-amqp) -- [Spring Remoting with JMS](http://www.baeldung.com/spring-remoting-jms) +- [Spring Remoting with JMS and ActiveMQ](http://www.baeldung.com/spring-remoting-jms) - [Spring Remoting with RMI](http://www.baeldung.com/spring-remoting-rmi) ### Overview From bb4258a0daa94633795987d73d2cfac4c1135a44 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 1 Mar 2019 18:44:51 +0800 Subject: [PATCH 079/254] Update README.md --- jackson/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jackson/README.md b/jackson/README.md index 519673738f..25194c7255 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -25,7 +25,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations) - [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance) - [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat) -- [A Guide to Optional with Jackson](http://www.baeldung.com/jackson-optional) +- [Using Optional with Jackson](http://www.baeldung.com/jackson-optional) - [Map Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-map) - [Jackson Streaming API](http://www.baeldung.com/jackson-streaming-api) - [Jackson – JsonMappingException (No serializer found for class)](http://www.baeldung.com/jackson-jsonmappingexception) From 7b3da0202ec8574f741cb12699f65b4c31bd46ce Mon Sep 17 00:00:00 2001 From: Chandra Prakash Date: Sat, 2 Mar 2019 07:52:09 -0500 Subject: [PATCH 080/254] BAEL-2504 Combinations Initial Combinations code. --- algorithms-miscellaneous-1/pom.xml | 5 +++ .../ApacheCommonsCombinationGenerator.java | 17 +++++++ .../CombinatoricsLibCombinationGenerator.java | 13 ++++++ .../GuavaCombinationsGenerator.java | 17 +++++++ .../IterativeCombinationGenerator.java | 45 +++++++++++++++++++ ...electionRecursiveCombinationGenerator.java | 39 ++++++++++++++++ .../SetRecursiveCombinationGenerator.java | 38 ++++++++++++++++ .../combination/CombinationUnitTest.java | 35 +++++++++++++++ 8 files changed, 209 insertions(+) create mode 100644 algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java create mode 100644 algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java create mode 100644 algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java create mode 100644 algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java create mode 100644 algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java create mode 100644 algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java create mode 100644 algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml index fe670963c0..0d528023d6 100644 --- a/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-miscellaneous-1/pom.xml @@ -39,6 +39,11 @@ ${org.assertj.core.version} test + + com.github.dpaukov + combinatoricslib3 + 3.3.0 + diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java new file mode 100644 index 0000000000..4ec36927fa --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java @@ -0,0 +1,17 @@ +package com.baeldung.algorithms.combination; + +import java.util.Arrays; +import java.util.Iterator; + +import org.apache.commons.math3.util.CombinatoricsUtils; + +public class ApacheCommonsCombinationGenerator { + + public static void main(String[] args) { + Iterator iterator = CombinatoricsUtils.combinationsIterator(5, 3); + while (iterator.hasNext()) { + final int[] combination = iterator.next(); + System.out.println(Arrays.toString(combination)); + } + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java new file mode 100644 index 0000000000..0afdeefb8b --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java @@ -0,0 +1,13 @@ +package com.baeldung.algorithms.combination; + +import org.paukov.combinatorics3.Generator; + +public class CombinatoricsLibCombinationGenerator { + + public static void main(String[] args) { + Generator.combination(0, 1, 2, 3, 4, 5) + .simple(3) + .stream() + .forEach(System.out::println); + } +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java new file mode 100644 index 0000000000..d2783881ba --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java @@ -0,0 +1,17 @@ +package com.baeldung.algorithms.combination; + +import java.util.Arrays; +import java.util.Set; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; + +public class GuavaCombinationsGenerator { + + public static void main(String[] args) { + + Set> combinations = Sets.combinations(ImmutableSet.of(0, 1, 2, 3, 4, 5), 3); + System.out.println(combinations.size()); + System.out.println(Arrays.toString(combinations.toArray())); + } +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java new file mode 100644 index 0000000000..a0c7222717 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java @@ -0,0 +1,45 @@ +package com.baeldung.algorithms.combination; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class IterativeCombinationGenerator { + + private static final int N = 5; + private static final int R = 2; + + public List generate(int n, int r) { + List combinations = new ArrayList<>(); + int[] combination = new int[r]; + + for (int i = 0; i < r; i++) { + combination[i] = i; + } + + while (combination[r - 1] < n) { + combinations.add(combination.clone()); + + int t = r - 1; + while (t != 0 && combination[t] == n - r + t) { + t--; + } + combination[t]++; + for (int i = t + 1; i < r; i++) { + combination[i] = combination[i - 1] + 1; + } + } + + return combinations; + } + + public static void main(String[] args) { + IterativeCombinationGenerator generator = new IterativeCombinationGenerator(); + List combinations = generator.generate(N, R); + System.out.println(combinations.size()); + for (int[] combination : combinations) { + System.out.println(Arrays.toString(combination)); + } + } + +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java new file mode 100644 index 0000000000..400042b137 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java @@ -0,0 +1,39 @@ +package com.baeldung.algorithms.combination; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class SelectionRecursiveCombinationGenerator { + + private static final int N = 6; + private static final int R = 3; + + public List generate(int n, int r) { + List combinations = new ArrayList<>(); + helper(combinations, new int[r], 0, n - 1, 0); + return combinations; + } + + private void helper(List combinations, int data[], int start, int end, int index) { + if (index == data.length) { + int[] combination = data.clone(); + combinations.add(combination); + } else { + int max = Math.min(end, end + 1 - data.length + index); + for (int i = start; i <= max; i++) { + data[index] = i; + helper(combinations, data, i + 1, end, index + 1); + } + } + } + + public static void main(String[] args) { + SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator(); + List combinations = generator.generate(N, R); + System.out.println(combinations.size()); + for (int[] combination : combinations) { + System.out.println(Arrays.toString(combination)); + } + } +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java new file mode 100644 index 0000000000..60c1c229b9 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.combination; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class SetRecursiveCombinationGenerator { + + private static final int N = 6; + private static final int R = 3; + + public List generate(int n, int r) { + List combinations = new ArrayList<>(); + helper(combinations, new int[r], 0, n - 1, 0, r); + return combinations; + } + + private void helper(List combinations, int data[], int start, int end, int index, int r) { + if (index == data.length) { + int[] combination = data.clone(); + combinations.add(combination); + + } else if (start <= end) { + data[index] = start; + helper(combinations, data, start + 1, end, index + 1, r); + helper(combinations, data, start + 1, end, index, r); + } + } + + public static void main(String[] args) { + SetRecursiveCombinationGenerator generator = new SetRecursiveCombinationGenerator(); + List combinations = generator.generate(N, R); + System.out.println(combinations.size()); + for (int[] combination : combinations) { + System.out.println(Arrays.toString(combination)); + } + } +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java new file mode 100644 index 0000000000..987b6ddae6 --- /dev/null +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.algorithms.combination; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +import org.junit.Test; + +public class CombinationUnitTest { + + private static final int N = 5; + private static final int R = 3; + private static final int nCr = 10; + + @Test + public void givenSetAndSelectionSize_whenCalculatedUsingSetRecursiveAlgorithm_thenExpectedCount() { + SetRecursiveCombinationGenerator generator = new SetRecursiveCombinationGenerator(); + List selection = generator.generate(N, R); + assertEquals(nCr, selection.size()); + } + + @Test + public void givenSetAndSelectionSize_whenCalculatedUsingSelectionRecursiveAlgorithm_thenExpectedCount() { + SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator(); + List selection = generator.generate(N, R); + assertEquals(nCr, selection.size()); + } + + @Test + public void givenSetAndSelectionSize_whenCalculatedUsingIterativeAlgorithm_thenExpectedCount() { + IterativeCombinationGenerator generator = new IterativeCombinationGenerator(); + List selection = generator.generate(N, R); + assertEquals(nCr, selection.size()); + } +} From 3deeefe9107d1ff8936057b3dd35dc3a1a7d966b Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sat, 2 Mar 2019 19:58:07 +0100 Subject: [PATCH 081/254] BAEL-2755 - Introduction to the Null Object Pattern --- .../com/baeldung/nullobject/JmsRouter.java | 10 +++++++ .../java/com/baeldung/nullobject/Message.java | 24 +++++++++++++++ .../com/baeldung/nullobject/NullRouter.java | 10 +++++++ .../java/com/baeldung/nullobject/Router.java | 7 +++++ .../baeldung/nullobject/RouterFactory.java | 23 ++++++++++++++ .../baeldung/nullobject/RoutingHandler.java | 30 +++++++++++++++++++ .../com/baeldung/nullobject/SmsRouter.java | 10 +++++++ 7 files changed, 114 insertions(+) create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/nullobject/JmsRouter.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/nullobject/Message.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/nullobject/Router.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/nullobject/RouterFactory.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/nullobject/RoutingHandler.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/JmsRouter.java b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/JmsRouter.java new file mode 100644 index 0000000000..7d8215fead --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/JmsRouter.java @@ -0,0 +1,10 @@ +package com.baeldung.nullobject; + +public class JmsRouter implements Router { + + @Override + public void route(Message msg) { + System.out.println("Routing to a JMS queue. Msg: " + msg); + } + +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Message.java b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Message.java new file mode 100644 index 0000000000..9086b6d92d --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Message.java @@ -0,0 +1,24 @@ +package com.baeldung.nullobject; + +public class Message { + + private String body; + + private String priority; + + public Message(String body, String priority) { + this.body = body; + this.priority = priority; + } + + public String getPriority() { + return priority; + } + + @Override + public String toString() { + return "{body='" + body + '\'' + + ", priority='" + priority + '\'' + + '}'; + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java new file mode 100644 index 0000000000..7da3856c93 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java @@ -0,0 +1,10 @@ +package com.baeldung.nullobject; + +public class NullRouter implements Router { + + @Override + public void route(Message msg) { + // routing to /dev/null + } + +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Router.java b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Router.java new file mode 100644 index 0000000000..3e67de9558 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Router.java @@ -0,0 +1,7 @@ +package com.baeldung.nullobject; + +public interface Router { + + void route(Message msg); + +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RouterFactory.java b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RouterFactory.java new file mode 100644 index 0000000000..ba80834865 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RouterFactory.java @@ -0,0 +1,23 @@ +package com.baeldung.nullobject; + +public class RouterFactory { + + public static Router getRouterForMessage(Message msg) { + + if (msg.getPriority() == null) { + return new NullRouter(); + } + + switch (msg.getPriority()) { + case "high": + return new SmsRouter(); + + case "medium": + return new JmsRouter(); + + default: + return new NullRouter(); + } + + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RoutingHandler.java b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RoutingHandler.java new file mode 100644 index 0000000000..282b066085 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RoutingHandler.java @@ -0,0 +1,30 @@ +package com.baeldung.nullobject; + +import java.util.Arrays; +import java.util.List; + +public class RoutingHandler { + + public void handle(Iterable messages){ + for (Message msg : messages) { + Router router = RouterFactory.getRouterForMessage(msg); + router.route(msg); + } + } + + public static void main(String[] args) { + Message highPriorityMsg = new Message("Alert!", "high"); + Message mediumPriorityMsg = new Message("Warning!", "medium"); + Message lowPriorityMsg = new Message("Take a look!", "low"); + Message nullPriorityMsg = new Message("Take a look!", null); + + List messages = Arrays.asList(highPriorityMsg, + mediumPriorityMsg, + lowPriorityMsg, + nullPriorityMsg); + + RoutingHandler routingHandler = new RoutingHandler(); + routingHandler.handle(messages); + + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java new file mode 100644 index 0000000000..3d4a684f94 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java @@ -0,0 +1,10 @@ +package com.baeldung.nullobject; + +public class SmsRouter implements Router { + + @Override + public void route(Message msg) { + System.out.println("Routing to a SMS gate. Msg: " + msg); + } + +} From 4826f19d00ed78c7efcafae0f6bfea79a3b9679d Mon Sep 17 00:00:00 2001 From: Jon Cook Date: Sat, 2 Mar 2019 22:50:04 +0100 Subject: [PATCH 082/254] BAEL-2512 - Add a new section in Mockito Spy article --- .../org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java index e2de23aa14..e39b8c0023 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java @@ -17,6 +17,7 @@ public class MockitoMisusingUnitTest { public void givenNotASpy_whenDoReturn_thenThrowNotAMock() { try { List list = new ArrayList(); + Mockito.doReturn(100) .when(list) .size(); From 47eee45301d4bb7bfa4f8f5cb390a4ad7a3c1491 Mon Sep 17 00:00:00 2001 From: Denis Zhdanov Date: Sun, 3 Mar 2019 07:24:02 +0800 Subject: [PATCH 083/254] BAEL-2581 Delegation Pattern in Kotlin --- .../kotlin/delegates/InterfaceDelegation.kt | 64 +++++++++++++++++++ .../delegates/InterfaceDelegationTest.kt | 28 ++++++++ 2 files changed, 92 insertions(+) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt new file mode 100644 index 0000000000..8e261aacf2 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt @@ -0,0 +1,64 @@ +package com.baeldung.kotlin.delegates + +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock + +interface Producer { + + fun produce(): String +} + +class ProducerImpl : Producer { + + override fun produce() = "ProducerImpl" +} + +class EnhancedProducer(private val delegate: Producer) : Producer by delegate { + + override fun produce() = "${delegate.produce()} and EnhancedProducer" +} + +interface MessageService { + + fun processMessage(message: String): String +} + +class MessageServiceImpl : MessageService { + override fun processMessage(message: String): String { + return "MessageServiceImpl: $message" + } +} + +interface UserService { + + fun processUser(userId: String): String +} + +class UserServiceImpl : UserService { + + override fun processUser(userId: String): String { + return "UserServiceImpl: $userId" + } +} + +class CompositeService : UserService by UserServiceImpl(), MessageService by MessageServiceImpl() + +interface Service { + + val seed: Int + + fun serve(action: (Int) -> Unit) +} + +class ServiceImpl : Service { + + override val seed = 1 + + override fun serve(action: (Int) -> Unit) { + action(seed) + } +} + +class ServiceDecorator : Service by ServiceImpl() { + override val seed = 2 +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt new file mode 100644 index 0000000000..e65032acd4 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt @@ -0,0 +1,28 @@ +package com.baeldung.kotlin.delegates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.Test + +class InterfaceDelegationTest { + + @Test + fun `when delegated implementation is used then it works as expected`() { + val producer = EnhancedProducer(ProducerImpl()) + assertThat(producer.produce()).isEqualTo("ProducerImpl and EnhancedProducer") + } + + @Test + fun `when composite delegation is used then it works as expected`() { + val service = CompositeService() + assertThat(service.processMessage("message")).isEqualTo("MessageServiceImpl: message") + assertThat(service.processUser("user")).isEqualTo("UserServiceImpl: user") + } + + @Test + fun `when decoration is used then delegate knows nothing about it`() { + val service = ServiceDecorator() + service.serve { + assertThat(it).isEqualTo(1) + } + } +} \ No newline at end of file From 6ecbe4b20adbe69bfb762b8a3bb4b0db280c8a10 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 3 Mar 2019 08:27:57 +0200 Subject: [PATCH 084/254] Update MockitoMisusingUnitTest.java --- .../org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java index e2de23aa14..2935f7ea8a 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java @@ -26,5 +26,4 @@ public class MockitoMisusingUnitTest { assertThat(e.getMessage(), containsString("Argument passed to when() is not a mock!")); } } - } From 86b51e41571082a4cbd732bb386aac9c4a5ed881 Mon Sep 17 00:00:00 2001 From: Jon Cook Date: Sun, 3 Mar 2019 08:45:45 +0100 Subject: [PATCH 085/254] BAEL-2512 - Add a new section in Mockito Spy article --- .../misusing/MockitoMisusingUnitTest.java | 31 ------------------- 1 file changed, 31 deletions(-) delete mode 100644 testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java deleted file mode 100644 index e39b8c0023..0000000000 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.mockito.misusing; - -import static org.hamcrest.core.StringContains.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.exceptions.misusing.NotAMockException; - -public class MockitoMisusingUnitTest { - - @Test - public void givenNotASpy_whenDoReturn_thenThrowNotAMock() { - try { - List list = new ArrayList(); - - Mockito.doReturn(100) - .when(list) - .size(); - - fail("Should have thrown a NotAMockException because 'list' is not a mock!"); - } catch (NotAMockException e) { - assertThat(e.getMessage(), containsString("Argument passed to when() is not a mock!")); - } - } - -} From 23e3e6c7088077b030c6a6cdad40c9dc39699b31 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sun, 3 Mar 2019 10:33:31 +0100 Subject: [PATCH 086/254] BAEL-2755 - minor improvements --- .../src/main/java/com/baeldung/nullobject/NullRouter.java | 2 +- .../src/main/java/com/baeldung/nullobject/SmsRouter.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java index 7da3856c93..a0065a321d 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java @@ -4,7 +4,7 @@ public class NullRouter implements Router { @Override public void route(Message msg) { - // routing to /dev/null + // do nothing } } diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java index 3d4a684f94..3e8e2f15f3 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java @@ -4,7 +4,7 @@ public class SmsRouter implements Router { @Override public void route(Message msg) { - System.out.println("Routing to a SMS gate. Msg: " + msg); + System.out.println("Routing to a SMS gateway. Msg: " + msg); } } From 9838dca33acaf295e5d5c4f511deb6f8d78bb5b6 Mon Sep 17 00:00:00 2001 From: Jon Cook Date: Sun, 3 Mar 2019 15:18:14 +0100 Subject: [PATCH 087/254] BAEL-2512 - Add a new section in Mockito Spy article --- .../misusing/MockitoMisusingUnitTest.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java new file mode 100644 index 0000000000..306f53297a --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/misusing/MockitoMisusingUnitTest.java @@ -0,0 +1,38 @@ +package org.baeldung.mockito.misusing; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.exceptions.misusing.NotAMockException; +import org.mockito.internal.progress.ThreadSafeMockingProgress; + +public class MockitoMisusingUnitTest { + + @After + public void tearDown() { + ThreadSafeMockingProgress.mockingProgress().reset(); + } + + @Test + public void givenNotASpy_whenDoReturn_thenThrowNotAMock() { + try { + List list = new ArrayList(); + + Mockito.doReturn(100, Mockito.withSettings().lenient()) + .when(list) + .size(); + + fail("Should have thrown a NotAMockException because 'list' is not a mock!"); + } catch (NotAMockException e) { + assertThat(e.getMessage(), containsString("Argument passed to when() is not a mock!")); + } + } + +} From 19cf211ddfa2a0cca1a0eaa3b7230ab9302f9e8e Mon Sep 17 00:00:00 2001 From: eric-martin Date: Sun, 3 Mar 2019 10:36:36 -0600 Subject: [PATCH 088/254] BAEL-2496: Updated ArraySortBenchmark --- .../performance/ArraySortBenchmark.java | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/performance/ArraySortBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/ArraySortBenchmark.java index a1d40657d3..b93f8e9cc2 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/ArraySortBenchmark.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/ArraySortBenchmark.java @@ -1,17 +1,21 @@ package com.baeldung.performance; -import org.openjdk.jmh.annotations.*; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; - -@BenchmarkMode(Mode.SingleShotTime) +@BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Measurement(batchSize = 100000, iterations = 10) @Warmup(batchSize = 100000, iterations = 10) @@ -19,8 +23,8 @@ public class ArraySortBenchmark { @State(Scope.Thread) public static class Initialize { - Integer[] numbers = {5, 22, 10, 0}; - int[] primitives = {5, 22, 10, 0}; + Integer[] numbers = { -769214442, -1283881723, 1504158300, -1260321086, -1800976432, 1278262737, 1863224321, 1895424914, 2062768552, -1051922993, 751605209, -1500919212, 2094856518, -1014488489, -931226326, -1677121986, -2080561705, 562424208, -1233745158, 41308167 }; + int[] primitives = { -769214442, -1283881723, 1504158300, -1260321086, -1800976432, 1278262737, 1863224321, 1895424914, 2062768552, -1051922993, 751605209, -1500919212, 2094856518, -1014488489, -931226326, -1677121986, -2080561705, 562424208, -1233745158, 41308167 }; } @Benchmark From 2b8ebe7de23c8e632121c3380423e45750da2dde Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 3 Mar 2019 01:33:22 +0530 Subject: [PATCH 089/254] [BAEL-12185] - Updated JACKSON ANNOTATIONS article --- .../serialization/jsonrootname/Author.java | 2 +- .../jackson/annotation/AliasBean.java | 31 ++++++++++++++ .../test/JacksonAnnotationUnitTest.java | 41 +++++++++++++++++++ pom.xml | 2 +- 4 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 jackson/src/test/java/com/baeldung/jackson/annotation/AliasBean.java diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java index c6ebfd10fb..b6dd75da54 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java @@ -13,7 +13,7 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonRootName("writer") +@JsonRootName(value = "writer", namespace = "book") public class Author extends Person { List items = new ArrayList<>(); diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/AliasBean.java b/jackson/src/test/java/com/baeldung/jackson/annotation/AliasBean.java new file mode 100644 index 0000000000..1842b2b6f5 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/AliasBean.java @@ -0,0 +1,31 @@ +package com.baeldung.jackson.annotation; + +import com.fasterxml.jackson.annotation.JsonAlias; + +public class AliasBean { + + @JsonAlias({ "fName", "f_name" }) + private String firstName; + + private String lastName; + + public AliasBean() { + + } + + 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; + } +} diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java index 935777bad1..c8c4c592f0 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java @@ -14,6 +14,7 @@ import java.util.TimeZone; import org.junit.Test; +import com.baeldung.jackson.annotation.AliasBean; import com.baeldung.jackson.annotation.BeanWithCreator; import com.baeldung.jackson.annotation.BeanWithCustomAnnotation; import com.baeldung.jackson.annotation.BeanWithFilter; @@ -38,6 +39,7 @@ import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue; import com.baeldung.jackson.exception.UserWithRoot; import com.baeldung.jackson.jsonview.Item; import com.baeldung.jackson.jsonview.Views; +import com.baeldung.jackson.serialization.jsonrootname.Author; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.MapperFeature; @@ -46,6 +48,7 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class JacksonAnnotationUnitTest { @@ -372,5 +375,43 @@ public class JacksonAnnotationUnitTest { assertThat(result, containsString("1")); assertThat(result, containsString("name")); } + + @Test + public void whenDeserializingUsingJsonAlias_thenCorrect() throws IOException { + + // arrange + String json = "{\"fName\": \"Alex\", \"lastName\": \"Theedom\"}"; + + // act + AliasBean aliasBean = new ObjectMapper().readerFor(AliasBean.class).readValue(json); + + // assert + assertThat(aliasBean.getFirstName(), is("Alex")); + } + + @Test + public void whenSerializingUsingXMLRootNameWithNameSpace_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + + // act + ObjectMapper mapper = new XmlMapper(); + mapper = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).enable(SerializationFeature.INDENT_OUTPUT); + String result = mapper.writeValueAsString(author); + + // assert + assertThat(result, containsString("")); + + /* + + 3006b44a-cf62-4cfe-b3d8-30dc6c46ea96 + Alex + Theedom + + + */ + + } } diff --git a/pom.xml b/pom.xml index 0a401299ba..81f55e3cbf 100644 --- a/pom.xml +++ b/pom.xml @@ -1630,7 +1630,7 @@ 2.3.1 1.9.13 1.2 - 2.9.7 + 2.9.8 1.3 1.2.0 5.2.0 From b796bb014639a30245f336c1761d5e88438a5651 Mon Sep 17 00:00:00 2001 From: Chandra Prakash Date: Sun, 3 Mar 2019 18:14:03 -0500 Subject: [PATCH 090/254] guava library updated to 27.0.1 upgraded guava library to 27.0.1 added javadoc --- algorithms-miscellaneous-1/pom.xml | 2 +- .../ApacheCommonsCombinationGenerator.java | 16 +++++++++-- .../IterativeCombinationGenerator.java | 11 ++++++-- ...electionRecursiveCombinationGenerator.java | 16 ++++++++++- .../SetRecursiveCombinationGenerator.java | 28 +++++++++++++------ 5 files changed, 59 insertions(+), 14 deletions(-) diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml index 0d528023d6..30130208f8 100644 --- a/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-miscellaneous-1/pom.xml @@ -82,7 +82,7 @@ 3.6.1 3.9.0 1.11 - 25.1-jre + 27.0.1-jre \ No newline at end of file diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java index 4ec36927fa..40142ce940 100644 --- a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java @@ -7,11 +7,23 @@ import org.apache.commons.math3.util.CombinatoricsUtils; public class ApacheCommonsCombinationGenerator { - public static void main(String[] args) { - Iterator iterator = CombinatoricsUtils.combinationsIterator(5, 3); + private static final int N = 6; + private static final int R = 3; + + /** + * Print all combinations of r elements from a set + * @param n - number of elements in set + * @param r - number of elements in selection + */ + public static void generate(int n, int r) { + Iterator iterator = CombinatoricsUtils.combinationsIterator(n, r); while (iterator.hasNext()) { final int[] combination = iterator.next(); System.out.println(Arrays.toString(combination)); } } + + public static void main(String[] args) { + generate(N, R); + } } \ No newline at end of file diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java index a0c7222717..676d2f41e3 100644 --- a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java @@ -5,14 +5,21 @@ import java.util.Arrays; import java.util.List; public class IterativeCombinationGenerator { - + private static final int N = 5; private static final int R = 2; + /** + * Generate all combinations of r elements from a set + * @param n the number of elements in input set + * @param r the number of elements in a combination + * @return the list containing all combinations + */ public List generate(int n, int r) { List combinations = new ArrayList<>(); int[] combination = new int[r]; + // initialize with lowest lexicographic combination for (int i = 0; i < r; i++) { combination[i] = i; } @@ -20,6 +27,7 @@ public class IterativeCombinationGenerator { while (combination[r - 1] < n) { combinations.add(combination.clone()); + // generate next combination in lexicographic order int t = r - 1; while (t != 0 && combination[t] == n - r + t) { t--; @@ -41,5 +49,4 @@ public class IterativeCombinationGenerator { System.out.println(Arrays.toString(combination)); } } - } diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java index 400042b137..52305b8c2f 100644 --- a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java @@ -9,12 +9,26 @@ public class SelectionRecursiveCombinationGenerator { private static final int N = 6; private static final int R = 3; + /** + * Generate all combinations of r elements from a set + * @param n - number of elements in input set + * @param r - number of elements to be chosen + * @return the list containing all combinations + */ public List generate(int n, int r) { List combinations = new ArrayList<>(); helper(combinations, new int[r], 0, n - 1, 0); return combinations; } + /** + * Choose elements from set by recursing over elements selected + * @param combinations - List to store generated combinations + * @param data - current combination + * @param start - starting element of remaining set + * @param end - last element of remaining set + * @param index - number of elements chosen so far. + */ private void helper(List combinations, int data[], int start, int end, int index) { if (index == data.length) { int[] combination = data.clone(); @@ -31,9 +45,9 @@ public class SelectionRecursiveCombinationGenerator { public static void main(String[] args) { SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator(); List combinations = generator.generate(N, R); - System.out.println(combinations.size()); for (int[] combination : combinations) { System.out.println(Arrays.toString(combination)); } + System.out.printf("generated %d combinations of %d items from %d ", combinations.size(), R, N); } } diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java index 60c1c229b9..a73447b31d 100644 --- a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java @@ -6,33 +6,45 @@ import java.util.List; public class SetRecursiveCombinationGenerator { - private static final int N = 6; - private static final int R = 3; + private static final int N = 5; + private static final int R = 2; + /** + * Generate all combinations of r elements from a set + * @param n - number of elements in set + * @param r - number of elements in selection + * @return the list containing all combinations + */ public List generate(int n, int r) { List combinations = new ArrayList<>(); - helper(combinations, new int[r], 0, n - 1, 0, r); + helper(combinations, new int[r], 0, n-1, 0); return combinations; } - private void helper(List combinations, int data[], int start, int end, int index, int r) { + /** + * @param combinations - List to contain the generated combinations + * @param data - List of elements in the selection + * @param start - index of the starting element in the remaining set + * @param end - index of the last element in the set + * @param index - number of elements selected so far + */ + private void helper(List combinations, int data[], int start, int end, int index) { if (index == data.length) { int[] combination = data.clone(); combinations.add(combination); - } else if (start <= end) { data[index] = start; - helper(combinations, data, start + 1, end, index + 1, r); - helper(combinations, data, start + 1, end, index, r); + helper(combinations, data, start + 1, end, index + 1); + helper(combinations, data, start + 1, end, index); } } public static void main(String[] args) { SetRecursiveCombinationGenerator generator = new SetRecursiveCombinationGenerator(); List combinations = generator.generate(N, R); - System.out.println(combinations.size()); for (int[] combination : combinations) { System.out.println(Arrays.toString(combination)); } + System.out.printf("generated %d combinations of %d items from %d ", combinations.size(), R, N); } } From 7e2de11a5afaee971e4e54cf05540217263c1ff5 Mon Sep 17 00:00:00 2001 From: Rodolfo Felipe Date: Mon, 4 Mar 2019 00:36:23 -0400 Subject: [PATCH 091/254] BAEL-2448 Code examples for article. --- .../CollectionFilteringExamples.java | 51 +++++++++++++++++++ .../collection/filtering/Employee.java | 44 ++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 core-java-collections-list/src/main/java/com/baeldung/collection/filtering/CollectionFilteringExamples.java create mode 100644 core-java-collections-list/src/main/java/com/baeldung/collection/filtering/Employee.java diff --git a/core-java-collections-list/src/main/java/com/baeldung/collection/filtering/CollectionFilteringExamples.java b/core-java-collections-list/src/main/java/com/baeldung/collection/filtering/CollectionFilteringExamples.java new file mode 100644 index 0000000000..a7ab5840f7 --- /dev/null +++ b/core-java-collections-list/src/main/java/com/baeldung/collection/filtering/CollectionFilteringExamples.java @@ -0,0 +1,51 @@ +package com.baeldung.collection.filtering; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Various filtering examples. + * + * @author Rodolfo Felipe + */ +public class CollectionFilteringExamples { + + private List buildEmployeeList() { + return Arrays.asList(new Employee(1, "Mike", 1), new Employee(2, "John", 1), new Employee(3, "Mary", 1), new Employee(4, "Joe", 2), new Employee(5, "Nicole", 2), new Employee(6, "Alice", 2), new Employee(7, "Bob", 3), new Employee(8, "Scarlett", 3)); + } + + private List employeeNameFilter() { + return Arrays.asList("Alice", "Mike", "Bob"); + } + + private List getFilteredEmployeeList() { + List filteredList = new ArrayList<>(); + for (Employee employee : buildEmployeeList()) { + for (String name : employeeNameFilter()) { + if (employee.getName() + .equalsIgnoreCase(name)) { + filteredList.add(employee); + } + } + } + return filteredList; + } + + private List getFilteredEmployeeListLambdaExample() { + return buildEmployeeList().stream() + .filter(employee -> employeeNameFilter().contains(employee.getName())) + .collect(Collectors.toList()); + } + + private List getFilteredEmployeeListLambdaExampleWithHashSetContains() { + Set nameFilterSet = employeeNameFilter().stream() + .collect(Collectors.toSet()); + return buildEmployeeList().stream() + .filter(employee -> nameFilterSet.contains(employee.getName())) + .collect(Collectors.toList()); + } + +} diff --git a/core-java-collections-list/src/main/java/com/baeldung/collection/filtering/Employee.java b/core-java-collections-list/src/main/java/com/baeldung/collection/filtering/Employee.java new file mode 100644 index 0000000000..2aa267b4dc --- /dev/null +++ b/core-java-collections-list/src/main/java/com/baeldung/collection/filtering/Employee.java @@ -0,0 +1,44 @@ +package com.baeldung.collection.filtering; + +/** + * Java 8 Collection Filtering by List of Values base class. + * + * @author Rodolfo Felipe + */ +public class Employee { + + private Integer employeeNumber; + private String name; + private Integer departmentId; + + public Employee(Integer employeeNumber, String name, Integer departmentId) { + this.employeeNumber = employeeNumber; + this.name = name; + this.departmentId = departmentId; + } + + public Integer getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(Integer employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getDepartmentId() { + return departmentId; + } + + public void setDepartmentId(Integer departmentId) { + this.departmentId = departmentId; + } + +} From 834df022ec8b70993653978e9c7a17124e9e82c7 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 4 Mar 2019 18:16:42 +0800 Subject: [PATCH 092/254] Update README.md --- spring-5-reactive/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 119e57f256..ef2f7d07eb 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -7,7 +7,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) - [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) -- [Exploring the Spring 5 MVC URL Matching](http://www.baeldung.com/spring-5-mvc-url-matching) +- [Exploring the Spring 5 WebFlux URL Matching](http://www.baeldung.com/spring-5-mvc-url-matching) - [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) From 8cb3b8d8dcc9ee2f09152cc836af78212f25e388 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:28:17 +0530 Subject: [PATCH 093/254] Back-link added --- core-java-collections-list/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-collections-list/README.md b/core-java-collections-list/README.md index 3a4a7c69e8..b4e5a31f20 100644 --- a/core-java-collections-list/README.md +++ b/core-java-collections-list/README.md @@ -28,3 +28,4 @@ - [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) - [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist) - [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal) +- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int) From e7503db1e798cc876d0eb09263dcf0b61c1fcc51 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:31:22 +0530 Subject: [PATCH 094/254] Back-link added --- java-strings/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-strings/README.md b/java-strings/README.md index 1ab5e098f6..3c401b4102 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -53,3 +53,4 @@ - [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) - [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) - [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) +- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) From d3090e250855681cf68aa2a639137203a918b9d1 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:35:03 +0530 Subject: [PATCH 095/254] Back-link added --- core-java-lang/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-lang/README.md b/core-java-lang/README.md index c1c22caf6c..eaedc93eed 100644 --- a/core-java-lang/README.md +++ b/core-java-lang/README.md @@ -41,3 +41,4 @@ - [Java Interfaces](https://www.baeldung.com/java-interfaces) - [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values) - [Variable Scope in Java](https://www.baeldung.com/java-variable-scope) +- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects) From aa80b07e8071713d01eec0aa9cfd31d49e72bc9a Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:36:45 +0530 Subject: [PATCH 096/254] Back-link added --- core-java-8/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-8/README.md b/core-java-8/README.md index 892dc71f76..540a5f677f 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -38,3 +38,4 @@ - [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs) - [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated) - [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain) +- [Method References in Java](https://www.baeldung.com/java-method-references) From a8fb9250bf2e7e06ef0e39fb0cdb862d46cd0b1f Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:38:13 +0530 Subject: [PATCH 097/254] Back-link added --- spring-boot-mvc/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-mvc/README.md b/spring-boot-mvc/README.md index 0e1ac5a8ce..d5a39cdc9f 100644 --- a/spring-boot-mvc/README.md +++ b/spring-boot-mvc/README.md @@ -11,3 +11,4 @@ - [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache) - [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) +- [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) From ab33ec149ea2dc72c585be797291d5d47747cdc0 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:41:20 +0530 Subject: [PATCH 098/254] Back-link added --- guice/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/guice/README.md b/guice/README.md index d1bd1ff883..77c788c363 100644 --- a/guice/README.md +++ b/guice/README.md @@ -2,3 +2,4 @@ ### Relevant Articles - [Guide to Google Guice](http://www.baeldung.com/guice) +- [Guice vs Spring – Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection) From 17fad4c738237d86092779dc7cc4674b3344e44e Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:44:10 +0530 Subject: [PATCH 099/254] Back-link added --- core-java-lang-oop/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-lang-oop/README.md b/core-java-lang-oop/README.md index bbc3d26c99..200415fe21 100644 --- a/core-java-lang-oop/README.md +++ b/core-java-lang-oop/README.md @@ -22,3 +22,4 @@ - [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) - [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors) - [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts) +- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces) From 1df138e5099eb80a14b217508b922c1d612ea7d8 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:47:01 +0530 Subject: [PATCH 100/254] Back-link added --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 1143604eac..67538a3895 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -50,3 +50,4 @@ - [Using Curl in Java](https://www.baeldung.com/java-curl) - [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) +- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) From b5a73e7252845a3685986526feec8a4ab1f1b8a3 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:49:02 +0530 Subject: [PATCH 101/254] Back-link added --- core-groovy/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-groovy/README.md b/core-groovy/README.md index 71788acdb7..f1a1161875 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -4,3 +4,4 @@ - [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy) - [Working with JSON in Groovy](http://www.baeldung.com/groovy-json) +- [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read) From 5bc15c387d0989ddb9bb1adb8078faf86f511fc4 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:52:30 +0530 Subject: [PATCH 102/254] Back-link added --- spring-security-mvc-jsonview/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-security-mvc-jsonview/README.md diff --git a/spring-security-mvc-jsonview/README.md b/spring-security-mvc-jsonview/README.md new file mode 100644 index 0000000000..35c806e856 --- /dev/null +++ b/spring-security-mvc-jsonview/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Filtering Jackson JSON Output Based on Spring Security Role](https://www.baeldung.com/spring-security-role-filter-json) From 178e3aa0f26cee2c68e97cc63ec4ff6ec40cbd2d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:54:04 +0530 Subject: [PATCH 103/254] Back-link added --- core-java-collections/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-collections/README.md b/core-java-collections/README.md index 710be31a08..80d4385c45 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -32,3 +32,4 @@ - [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator) - [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences) - [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector) +- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack) From e299681c32a956ed5d4e4e67e9e788a3e78363e5 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 4 Mar 2019 19:24:11 +0800 Subject: [PATCH 104/254] Update README.md --- core-java-networking/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-networking/README.md b/core-java-networking/README.md index faeeadab24..f6ce44d72f 100644 --- a/core-java-networking/README.md +++ b/core-java-networking/README.md @@ -9,7 +9,7 @@ - [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java) - [Sending Emails with Java](http://www.baeldung.com/java-email) - [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java) -- [A Simple Guide to the Java URL](http://www.baeldung.com/java-url) +- [A Guide to the Java URL](http://www.baeldung.com/java-url) - [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding) From 1e2032b96cbdee9fcecb4a1856c7b2fe7d983c3f Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 16:55:58 +0530 Subject: [PATCH 105/254] Back-link added --- core-kotlin/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 6ee79b2a2e..1a7ecd34e1 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -52,3 +52,4 @@ - [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) - [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final) - [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) +- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl) From b9914774480135413159479385af48611b9b194f Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:00:18 +0530 Subject: [PATCH 106/254] Back-Link added --- spring-boot-libraries/README.MD | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-libraries/README.MD b/spring-boot-libraries/README.MD index cc32ce8355..f3706e0fa4 100644 --- a/spring-boot-libraries/README.MD +++ b/spring-boot-libraries/README.MD @@ -4,3 +4,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Guide to ShedLock with Spring](https://www.baeldung.com/shedlock-spring) +- [A Guide to the Problem Spring Web Library](https://www.baeldung.com/problem-spring-web) From f8ca54321733bc26e76d3bc649e7835afa29fe53 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:04:53 +0530 Subject: [PATCH 107/254] Back-link added --- spring-soap/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-soap/README.md diff --git a/spring-soap/README.md b/spring-soap/README.md new file mode 100644 index 0000000000..8d96350e1e --- /dev/null +++ b/spring-soap/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Creating a SOAP Web Service with Spring](https://www.baeldung.com/spring-boot-soap-web-service) From f956a00fdd5cb59fa7e126f031456a2e11b39fec Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:05:55 +0530 Subject: [PATCH 108/254] Back-link added --- persistence-modules/hibernate5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index a4e95a9062..8fc8a433e8 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -30,3 +30,4 @@ - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) - [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) - [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) +- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) From aa4a20b4a899843055c1876964d2d2300257b315 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:07:30 +0530 Subject: [PATCH 109/254] Back-link added --- persistence-modules/hibernate5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index 8fc8a433e8..026a5feb86 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -31,3 +31,4 @@ - [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) - [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) - [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) +- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) From 5e30bafb53e1ee1bf4318900ffe6ed1bbedc20f9 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:14:03 +0530 Subject: [PATCH 110/254] Back-link added --- core-java-9/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-9/README.md b/core-java-9/README.md index d9586ba684..d24106cc8f 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -27,3 +27,4 @@ - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) - [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) - [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) +- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar) From 70d2bb2c91c4168d0f6c91a6dc1f284cfc0b716e Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:15:06 +0530 Subject: [PATCH 111/254] Back-link added --- core-kotlin/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 1a7ecd34e1..64ecd73b1c 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -53,3 +53,4 @@ - [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final) - [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) - [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl) +- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) From 00b9b9e9b95adc11130c90f98f20f0b74b60b247 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:17:19 +0530 Subject: [PATCH 112/254] Back-link added --- persistence-modules/spring-data-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md index 739031ff5e..e629a464df 100644 --- a/persistence-modules/spring-data-jpa/README.md +++ b/persistence-modules/spring-data-jpa/README.md @@ -20,6 +20,7 @@ - [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert) - [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) - [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) +- [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test) ### Eclipse Config After importing the project into Eclipse, you may see the following error: From 140850225e44001cb096ec6bbbe2e1f3b22d6661 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:18:18 +0530 Subject: [PATCH 113/254] Back-link added --- core-groovy/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-groovy/README.md b/core-groovy/README.md index f1a1161875..fde7f33f86 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -5,3 +5,4 @@ - [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy) - [Working with JSON in Groovy](http://www.baeldung.com/groovy-json) - [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read) +- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) From 8fbe21c0eb1b37aed4aa33be90c8a30ef104b721 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:19:13 +0530 Subject: [PATCH 114/254] Back-link added --- core-java-9/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-9/README.md b/core-java-9/README.md index d24106cc8f..7e256d5c7e 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -28,3 +28,4 @@ - [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) - [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) - [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar) +- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation) From 55b93c5c52587a53795b5568b76c02b5cf36230f Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:20:11 +0530 Subject: [PATCH 115/254] Back-link added --- core-groovy/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-groovy/README.md b/core-groovy/README.md index fde7f33f86..6e385d528f 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -6,3 +6,4 @@ - [Working with JSON in Groovy](http://www.baeldung.com/groovy-json) - [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read) - [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) +- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) From b4a1434ad6eaefcf04a8942d8df4e55b75823b4a Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:21:01 +0530 Subject: [PATCH 116/254] Back-link added --- core-java-collections-list/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-collections-list/README.md b/core-java-collections-list/README.md index b4e5a31f20..598d8331d0 100644 --- a/core-java-collections-list/README.md +++ b/core-java-collections-list/README.md @@ -29,3 +29,4 @@ - [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist) - [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal) - [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int) +- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance) From bb2003ca8ef2226e62d7bc3b8de0c30cc3278c4c Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:21:57 +0530 Subject: [PATCH 117/254] Back-link added --- core-groovy/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-groovy/README.md b/core-groovy/README.md index 6e385d528f..ec2fcfa574 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -7,3 +7,4 @@ - [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read) - [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) - [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) +- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits) From 5f9665ab6ecb43da5ef64b58348f6b5021a23ed1 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:22:50 +0530 Subject: [PATCH 118/254] Back-link added --- spring-mvc-simple/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md index 755e0932fc..cd4ad5aba2 100644 --- a/spring-mvc-simple/README.md +++ b/spring-mvc-simple/README.md @@ -8,3 +8,4 @@ - [Guide to Spring Email](http://www.baeldung.com/spring-email) - [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405) - [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param) +- [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable) From f6d4d8c4602e0e84cc577f3ce750c256e4f49ad9 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:23:41 +0530 Subject: [PATCH 119/254] Back-link added --- json/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/json/README.md b/json/README.md index 2e253a4ae9..24b25a5b12 100644 --- a/json/README.md +++ b/json/README.md @@ -11,3 +11,4 @@ - [Overview of JSON Pointer](https://www.baeldung.com/json-pointer) - [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api) - [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key) +- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration) From 58389b2a86b5c87abeaa540290aafa4303b21a11 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:24:40 +0530 Subject: [PATCH 120/254] Back-link added --- json/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/json/README.md b/json/README.md index 24b25a5b12..c0ca4b00ef 100644 --- a/json/README.md +++ b/json/README.md @@ -12,3 +12,4 @@ - [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api) - [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key) - [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration) +- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) From 6afbc3086f2e7403e6a935842e2c3d52d01a134d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:27:04 +0530 Subject: [PATCH 121/254] Back-link added --- software-security/sql-injection-samples/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 software-security/sql-injection-samples/README.md diff --git a/software-security/sql-injection-samples/README.md b/software-security/sql-injection-samples/README.md new file mode 100644 index 0000000000..7a077074ac --- /dev/null +++ b/software-security/sql-injection-samples/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [SQL Injection and How to Prevent It?](https://www.baeldung.com/sql-injection) From 0f2e3da7d465fd457c7f94c849644cc3a4ebe114 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:27:39 +0530 Subject: [PATCH 122/254] Back-link added --- core-kotlin-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md index 6aabd71a6c..8d22c4f1a8 100644 --- a/core-kotlin-2/README.md +++ b/core-kotlin-2/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type) +- [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges) From 3ede9262f6fa6e1a8f49e3e24c24f9d34cd9979e Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:28:52 +0530 Subject: [PATCH 123/254] Back-link added --- jhipster/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jhipster/README.md b/jhipster/README.md index 91ba54bf60..289bfac754 100644 --- a/jhipster/README.md +++ b/jhipster/README.md @@ -3,3 +3,4 @@ - [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices) - [Intro to JHipster](http://www.baeldung.com/jhipster) - [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) +- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles) From 04638627a7c15f23edfea156a531f751e6a6e8e1 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:29:42 +0530 Subject: [PATCH 124/254] Back-link added --- persistence-modules/spring-data-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md index e629a464df..9512ad336d 100644 --- a/persistence-modules/spring-data-jpa/README.md +++ b/persistence-modules/spring-data-jpa/README.md @@ -21,6 +21,7 @@ - [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) - [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) - [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test) +- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation) ### Eclipse Config After importing the project into Eclipse, you may see the following error: From be2d3ce59a317cd4dfeeeed459c49383ba79357b Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:30:56 +0530 Subject: [PATCH 125/254] Back-link added --- ratpack/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ratpack/README.md b/ratpack/README.md index dded42fab6..14bc3f6c74 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -5,3 +5,4 @@ - [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) - [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix) - [Ratpack HTTP Client](https://www.baeldung.com/ratpack-http-client) +- [Ratpack with RxJava](https://www.baeldung.com/ratpack-rxjava) From 10a395f64e1cb6d9649fc17ae02d422ca374e89c Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:31:49 +0530 Subject: [PATCH 126/254] Back-link added --- maven/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/maven/README.md b/maven/README.md index 1c0e50f95a..1352a2a10f 100644 --- a/maven/README.md +++ b/maven/README.md @@ -14,3 +14,4 @@ - [Apache Maven Tutorial](https://www.baeldung.com/maven) - [Use the Latest Version of a Dependency in Maven](https://www.baeldung.com/maven-dependency-latest-version) - [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module) +- [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin) From 3f6b909ab8d6083fa1bdb35af05aa53505fa2c69 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 4 Mar 2019 17:33:17 +0530 Subject: [PATCH 127/254] Back-link added --- libraries/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/README.md b/libraries/README.md index 378317778e..57f22631f1 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -66,6 +66,7 @@ - [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) - [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) - [Intro to Derive4J](https://www.baeldung.com/derive4j) +- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library) 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. From c2cb4d4bc081d678f4a8fc3bdcd7a8e86c36f761 Mon Sep 17 00:00:00 2001 From: Ganesh Pagade Date: Tue, 5 Mar 2019 00:01:05 +0530 Subject: [PATCH 128/254] gson advanced list examples --- .../org/baeldung/gson/entities/Animal.java | 5 + .../java/org/baeldung/gson/entities/Cow.java | 19 ++ .../java/org/baeldung/gson/entities/Dog.java | 18 ++ .../org/baeldung/gson/entities/MyClass.java | 37 +++ .../serialization/AnimalDeserializer.java | 35 +++ .../gson/advance/GsonAdvanceUnitTest.java | 110 ++++++++ .../advance/RuntimeTypeAdapterFactory.java | 265 ++++++++++++++++++ 7 files changed, 489 insertions(+) create mode 100644 gson/src/main/java/org/baeldung/gson/entities/Animal.java create mode 100644 gson/src/main/java/org/baeldung/gson/entities/Cow.java create mode 100644 gson/src/main/java/org/baeldung/gson/entities/Dog.java create mode 100644 gson/src/main/java/org/baeldung/gson/entities/MyClass.java create mode 100644 gson/src/main/java/org/baeldung/gson/serialization/AnimalDeserializer.java create mode 100644 gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java create mode 100644 gson/src/test/java/org/baeldung/gson/advance/RuntimeTypeAdapterFactory.java diff --git a/gson/src/main/java/org/baeldung/gson/entities/Animal.java b/gson/src/main/java/org/baeldung/gson/entities/Animal.java new file mode 100644 index 0000000000..2eec5f8704 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Animal.java @@ -0,0 +1,5 @@ +package org.baeldung.gson.entities; + +public abstract class Animal { + public String type = "Animal"; +} diff --git a/gson/src/main/java/org/baeldung/gson/entities/Cow.java b/gson/src/main/java/org/baeldung/gson/entities/Cow.java new file mode 100644 index 0000000000..020bcd5860 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Cow.java @@ -0,0 +1,19 @@ +package org.baeldung.gson.entities; + +public class Cow extends Animal { + private String breed; + + public Cow() { + breed = "Jersey"; + type = "Cow"; + } + + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } +} + diff --git a/gson/src/main/java/org/baeldung/gson/entities/Dog.java b/gson/src/main/java/org/baeldung/gson/entities/Dog.java new file mode 100644 index 0000000000..042d73adcf --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Dog.java @@ -0,0 +1,18 @@ +package org.baeldung.gson.entities; + +public class Dog extends Animal { + private String petName; + + public Dog() { + petName = "Milo"; + type = "Dog"; + } + + public String getPetName() { + return petName; + } + + public void setPetName(String petName) { + this.petName = petName; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/entities/MyClass.java b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java new file mode 100644 index 0000000000..86e14985da --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java @@ -0,0 +1,37 @@ +package org.baeldung.gson.entities; + +public class MyClass { + private int id; + private String[] strings; + + public MyClass() { + id = 1; + strings = new String[] { "a", "b" }; + } + + + // @Override + // public String toString() { + // return "{" + + // "id=" + id + + // ", name='" + name + '\'' + + // ", strings=" + Arrays.toString(strings) + + // '}'; + // } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String[] getStrings() { + return strings; + } + + public void setStrings(String[] strings) { + this.strings = strings; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/serialization/AnimalDeserializer.java b/gson/src/main/java/org/baeldung/gson/serialization/AnimalDeserializer.java new file mode 100644 index 0000000000..9dcef0e10b --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serialization/AnimalDeserializer.java @@ -0,0 +1,35 @@ +package org.baeldung.gson.serialization; + +import com.google.gson.Gson; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; +import org.baeldung.gson.entities.Animal; + +public class AnimalDeserializer implements JsonDeserializer { + private String animalTypeElementName; + private Gson gson; + private Map> animalTypeRegistry; + + public AnimalDeserializer(String animalTypeElementName) { + this.animalTypeElementName = animalTypeElementName; + this.gson = new Gson(); + this.animalTypeRegistry = new HashMap<>(); + } + + public void registerBarnType(String animalTypeName, Class animalType) { + animalTypeRegistry.put(animalTypeName, animalType); + } + + public Animal deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { + JsonObject animalObject = json.getAsJsonObject(); + JsonElement animalTypeElement = animalObject.get(animalTypeElementName); + + Class animalType = animalTypeRegistry.get(animalTypeElement.getAsString()); + return gson.fromJson(animalObject, animalType); + } +} \ No newline at end of file diff --git a/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java new file mode 100644 index 0000000000..7032dde1ce --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java @@ -0,0 +1,110 @@ +package org.baeldung.gson.advance; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import org.baeldung.gson.entities.Animal; +import org.baeldung.gson.entities.Cow; +import org.baeldung.gson.entities.Dog; +import org.baeldung.gson.entities.MyClass; +import org.baeldung.gson.serialization.AnimalDeserializer; +import org.junit.Test; + +public class GsonAdvanceUnitTest { + + @Test public void givenListOfMyClass_whenSerializing_thenCorrect() { + List list = new ArrayList<>(); + list.add(new MyClass()); + list.add(new MyClass()); + + Gson gson = new Gson(); + String jsonString = gson.toJson(list); + String expectedString = "[{\"id\":1,\"strings\":[\"a\",\"b\"]},{\"id\":1,\"strings\":[\"a\",\"b\"]}]"; + + assertEquals(expectedString, jsonString); + } + + @Test(expected = ClassCastException.class) + public void givenJsonString_whenIncorrectDeserializing_thenThrowClassCastException() { + String inputString = "[{\"id\":1,\"strings\":[\"a\",\"b\"]},{\"id\":1,\"strings\":[\"a\",\"b\"]}]"; + + Gson gson = new Gson(); + List list = gson.fromJson(inputString, ArrayList.class); + + assertEquals(2, list.size()); + int id = list.get(0).getId(); + } + + @Test public void givenJsonString_whenDeserializing_thenReturnListOfMyClass() { + String inputString = "[{\"id\":1,\"strings\":[\"a\",\"b\"]},{\"id\":1,\"strings\":[\"a\",\"b\"]}]"; + Type listOfMyClassObject = new TypeToken>() {}.getType(); + + Gson gson = new Gson(); + List list = gson.fromJson(inputString, listOfMyClassObject); + + assertEquals(2, list.size()); + assertEquals(1, list.get(0).getId()); + } + + @Test public void givenPolymorphicList_whenSerializeWithTypeAdapter_thenCorrect() { + String expectedString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; + + List inList = new ArrayList<>(); + inList.add(new Dog()); + inList.add(new Cow()); + + String jsonString = new Gson().toJson(inList); + + assertEquals(expectedString, jsonString); + } + + @Test public void givenPolymorphicList_whenDeserializeWithTypeAdapter_thenCorrect() { + String inputString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; + + AnimalDeserializer deserializer = new AnimalDeserializer("type"); + deserializer.registerBarnType("Dog", Dog.class); + deserializer.registerBarnType("Cow", Cow.class); + Gson gson = new GsonBuilder() + .registerTypeAdapter(Animal.class, deserializer) + .create(); + + List outList = gson.fromJson(inputString, new TypeToken>(){}.getType()); + + assertEquals(2, outList.size()); + assertTrue(outList.get(0) instanceof Dog); + } + + @Test public void givenPolymorphicList_whenSerializeWithRuntimeTypeAdapter_thenCorrect() { + String expectedString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; + + List inList = new ArrayList<>(); + inList.add(new Dog()); + inList.add(new Cow()); + String jsonString = new Gson().toJson(inList); + + assertEquals(expectedString, jsonString); + } + + @Test public void givenPolymorphicList_whenDeserializeWithRuntimeTypeAdapter_thenCorrect() { + String inputString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; + + Type listOfAnimals = new TypeToken>() {}.getType(); + + RuntimeTypeAdapterFactory adapter = RuntimeTypeAdapterFactory.of(Animal.class) + .registerSubtype(Dog.class) + .registerSubtype(Cow.class); + + Gson gson = new GsonBuilder().registerTypeAdapterFactory(adapter).create(); + + List outList = gson.fromJson(inputString, listOfAnimals); + + assertEquals(2, outList.size()); + assertTrue(outList.get(0) instanceof Dog); + } +} \ No newline at end of file diff --git a/gson/src/test/java/org/baeldung/gson/advance/RuntimeTypeAdapterFactory.java b/gson/src/test/java/org/baeldung/gson/advance/RuntimeTypeAdapterFactory.java new file mode 100644 index 0000000000..739dd889c7 --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/advance/RuntimeTypeAdapterFactory.java @@ -0,0 +1,265 @@ +package org.baeldung.gson.advance; + +/* + * Copyright (C) 2011 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.internal.Streams; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Adapts values whose runtime type may differ from their declaration type. This + * is necessary when a field's type is not the same type that GSON should create + * when deserializing that field. For example, consider these types: + *
   {@code
+ *   abstract class Shape {
+ *     int x;
+ *     int y;
+ *   }
+ *   class Circle extends Shape {
+ *     int radius;
+ *   }
+ *   class Rectangle extends Shape {
+ *     int width;
+ *     int height;
+ *   }
+ *   class Diamond extends Shape {
+ *     int width;
+ *     int height;
+ *   }
+ *   class Drawing {
+ *     Shape bottomShape;
+ *     Shape topShape;
+ *   }
+ * }
+ *

Without additional type information, the serialized JSON is ambiguous. Is + * the bottom shape in this drawing a rectangle or a diamond?

   {@code
+ *   {
+ *     "bottomShape": {
+ *       "width": 10,
+ *       "height": 5,
+ *       "x": 0,
+ *       "y": 0
+ *     },
+ *     "topShape": {
+ *       "radius": 2,
+ *       "x": 4,
+ *       "y": 1
+ *     }
+ *   }}
+ * This class addresses this problem by adding type information to the + * serialized JSON and honoring that type information when the JSON is + * deserialized:
   {@code
+ *   {
+ *     "bottomShape": {
+ *       "type": "Diamond",
+ *       "width": 10,
+ *       "height": 5,
+ *       "x": 0,
+ *       "y": 0
+ *     },
+ *     "topShape": {
+ *       "type": "Circle",
+ *       "radius": 2,
+ *       "x": 4,
+ *       "y": 1
+ *     }
+ *   }}
+ * Both the type field name ({@code "type"}) and the type labels ({@code + * "Rectangle"}) are configurable. + * + *

Registering Types

+ * Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field + * name to the {@link #of} factory method. If you don't supply an explicit type + * field name, {@code "type"} will be used.
   {@code
+ *   RuntimeTypeAdapterFactory shapeAdapterFactory
+ *       = RuntimeTypeAdapterFactory.of(Shape.class, "type");
+ * }
+ * Next register all of your subtypes. Every subtype must be explicitly + * registered. This protects your application from injection attacks. If you + * don't supply an explicit type label, the type's simple name will be used. + *
   {@code
+ *   shapeAdapterFactory.registerSubtype(Rectangle.class, "Rectangle");
+ *   shapeAdapterFactory.registerSubtype(Circle.class, "Circle");
+ *   shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond");
+ * }
+ * Finally, register the type adapter factory in your application's GSON builder: + *
   {@code
+ *   Gson gson = new GsonBuilder()
+ *       .registerTypeAdapterFactory(shapeAdapterFactory)
+ *       .create();
+ * }
+ * Like {@code GsonBuilder}, this API supports chaining:
   {@code
+ *   RuntimeTypeAdapterFactory shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
+ *       .registerSubtype(Rectangle.class)
+ *       .registerSubtype(Circle.class)
+ *       .registerSubtype(Diamond.class);
+ * }
+ */ +public final class RuntimeTypeAdapterFactory implements TypeAdapterFactory { + private final Class baseType; + private final String typeFieldName; + private final Map> labelToSubtype = new LinkedHashMap>(); + private final Map, String> subtypeToLabel = new LinkedHashMap, String>(); + private final boolean maintainType; + + private RuntimeTypeAdapterFactory(Class baseType, String typeFieldName, boolean maintainType) { + if (typeFieldName == null || baseType == null) { + throw new NullPointerException(); + } + this.baseType = baseType; + this.typeFieldName = typeFieldName; + this.maintainType = maintainType; + } + + /** + * Creates a new runtime type adapter using for {@code baseType} using {@code + * typeFieldName} as the type field name. Type field names are case sensitive. + * {@code maintainType} flag decide if the type will be stored in pojo or not. + */ + public static RuntimeTypeAdapterFactory of(Class baseType, String typeFieldName, boolean maintainType) { + return new RuntimeTypeAdapterFactory(baseType, typeFieldName, maintainType); + } + + /** + * Creates a new runtime type adapter using for {@code baseType} using {@code + * typeFieldName} as the type field name. Type field names are case sensitive. + */ + public static RuntimeTypeAdapterFactory of(Class baseType, String typeFieldName) { + return new RuntimeTypeAdapterFactory(baseType, typeFieldName, false); + } + + /** + * Creates a new runtime type adapter for {@code baseType} using {@code "type"} as + * the type field name. + */ + public static RuntimeTypeAdapterFactory of(Class baseType) { + return new RuntimeTypeAdapterFactory(baseType, "type", false); + } + + /** + * Registers {@code type} identified by {@code label}. Labels are case + * sensitive. + * + * @throws IllegalArgumentException if either {@code type} or {@code label} + * have already been registered on this type adapter. + */ + public RuntimeTypeAdapterFactory registerSubtype(Class type, String label) { + if (type == null || label == null) { + throw new NullPointerException(); + } + if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) { + throw new IllegalArgumentException("types and labels must be unique"); + } + labelToSubtype.put(label, type); + subtypeToLabel.put(type, label); + return this; + } + + /** + * Registers {@code type} identified by its {@link Class#getSimpleName simple + * name}. Labels are case sensitive. + * + * @throws IllegalArgumentException if either {@code type} or its simple name + * have already been registered on this type adapter. + */ + public RuntimeTypeAdapterFactory registerSubtype(Class type) { + return registerSubtype(type, type.getSimpleName()); + } + + public TypeAdapter create(Gson gson, TypeToken type) { + if (type.getRawType() != baseType) { + return null; + } + + final Map> labelToDelegate + = new LinkedHashMap>(); + final Map, TypeAdapter> subtypeToDelegate + = new LinkedHashMap, TypeAdapter>(); + for (Map.Entry> entry : labelToSubtype.entrySet()) { + TypeAdapter delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); + labelToDelegate.put(entry.getKey(), delegate); + subtypeToDelegate.put(entry.getValue(), delegate); + } + + return new TypeAdapter() { + @Override public R read(JsonReader in) throws IOException { + JsonElement jsonElement = Streams.parse(in); + JsonElement labelJsonElement; + if (maintainType) { + labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); + } else { + labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); + } + + if (labelJsonElement == null) { + throw new JsonParseException("cannot deserialize " + baseType + + " because it does not define a field named " + typeFieldName); + } + String label = labelJsonElement.getAsString(); + @SuppressWarnings("unchecked") // registration requires that subtype extends T + TypeAdapter delegate = (TypeAdapter) labelToDelegate.get(label); + if (delegate == null) { + throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + + label + "; did you forget to register a subtype?"); + } + return delegate.fromJsonTree(jsonElement); + } + + @Override public void write(JsonWriter out, R value) throws IOException { + Class srcType = value.getClass(); + String label = subtypeToLabel.get(srcType); + @SuppressWarnings("unchecked") // registration requires that subtype extends T + TypeAdapter delegate = (TypeAdapter) subtypeToDelegate.get(srcType); + if (delegate == null) { + throw new JsonParseException("cannot serialize " + srcType.getName() + + "; did you forget to register a subtype?"); + } + JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); + + if (maintainType) { + Streams.write(jsonObject, out); + return; + } + + JsonObject clone = new JsonObject(); + + if (jsonObject.has(typeFieldName)) { + throw new JsonParseException("cannot serialize " + srcType.getName() + + " because it already defines a field named " + typeFieldName); + } + clone.add(typeFieldName, new JsonPrimitive(label)); + + for (Map.Entry e : jsonObject.entrySet()) { + clone.add(e.getKey(), e.getValue()); + } + Streams.write(clone, out); + } + }.nullSafe(); + } +} From 904046b0671898beb5504b66b68dc18dad3d2083 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 4 Mar 2019 21:39:47 +0200 Subject: [PATCH 129/254] Update README.md --- core-java-8/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-8/README.md b/core-java-8/README.md index 540a5f677f..eca07883e0 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -39,3 +39,4 @@ - [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated) - [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain) - [Method References in Java](https://www.baeldung.com/java-method-references) +- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) From 3186e484037e39ce9fa61874ce911f8a9dd90156 Mon Sep 17 00:00:00 2001 From: Rodolfo Felipe Date: Mon, 4 Mar 2019 20:43:14 -0400 Subject: [PATCH 130/254] BAEL-2448-Rev1 Changing examples to unit tests instead of plain methods after advice from editor. --- .../CollectionFilteringExamples.java | 51 ------------- .../filtering/CollectionFilteringTest.java | 73 +++++++++++++++++++ 2 files changed, 73 insertions(+), 51 deletions(-) delete mode 100644 core-java-collections-list/src/main/java/com/baeldung/collection/filtering/CollectionFilteringExamples.java create mode 100644 core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java diff --git a/core-java-collections-list/src/main/java/com/baeldung/collection/filtering/CollectionFilteringExamples.java b/core-java-collections-list/src/main/java/com/baeldung/collection/filtering/CollectionFilteringExamples.java deleted file mode 100644 index a7ab5840f7..0000000000 --- a/core-java-collections-list/src/main/java/com/baeldung/collection/filtering/CollectionFilteringExamples.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.collection.filtering; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Various filtering examples. - * - * @author Rodolfo Felipe - */ -public class CollectionFilteringExamples { - - private List buildEmployeeList() { - return Arrays.asList(new Employee(1, "Mike", 1), new Employee(2, "John", 1), new Employee(3, "Mary", 1), new Employee(4, "Joe", 2), new Employee(5, "Nicole", 2), new Employee(6, "Alice", 2), new Employee(7, "Bob", 3), new Employee(8, "Scarlett", 3)); - } - - private List employeeNameFilter() { - return Arrays.asList("Alice", "Mike", "Bob"); - } - - private List getFilteredEmployeeList() { - List filteredList = new ArrayList<>(); - for (Employee employee : buildEmployeeList()) { - for (String name : employeeNameFilter()) { - if (employee.getName() - .equalsIgnoreCase(name)) { - filteredList.add(employee); - } - } - } - return filteredList; - } - - private List getFilteredEmployeeListLambdaExample() { - return buildEmployeeList().stream() - .filter(employee -> employeeNameFilter().contains(employee.getName())) - .collect(Collectors.toList()); - } - - private List getFilteredEmployeeListLambdaExampleWithHashSetContains() { - Set nameFilterSet = employeeNameFilter().stream() - .collect(Collectors.toSet()); - return buildEmployeeList().stream() - .filter(employee -> nameFilterSet.contains(employee.getName())) - .collect(Collectors.toList()); - } - -} diff --git a/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java b/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java new file mode 100644 index 0000000000..bf3ec53abb --- /dev/null +++ b/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java @@ -0,0 +1,73 @@ +package com.baeldung.collection.filtering; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +/** + * Various filtering examples. + * + * @author Rodolfo Felipe + */ +public class CollectionFilteringTest { + + private List buildEmployeeList() { + return Arrays.asList(new Employee(1, "Mike", 1), new Employee(2, "John", 1), new Employee(3, "Mary", 1), new Employee(4, "Joe", 2), new Employee(5, "Nicole", 2), new Employee(6, "Alice", 2), new Employee(7, "Bob", 3), new Employee(8, "Scarlett", 3)); + } + + private List employeeNameFilter() { + return Arrays.asList("Alice", "Mike", "Bob"); + } + + @Test + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoop() { + List filteredList = new ArrayList<>(); + List originalList = buildEmployeeList(); + List nameFilter = employeeNameFilter(); + + for (Employee employee : originalList) { + for (String name : nameFilter) { + if (employee.getName() + .equalsIgnoreCase(name)) { + filteredList.add(employee); + } + } + } + + Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size())); + } + + @Test + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambda() { + List filteredList; + List originalList = buildEmployeeList(); + List nameFilter = employeeNameFilter(); + + filteredList = originalList.stream() + .filter(employee -> nameFilter.contains(employee.getName())) + .collect(Collectors.toList()); + + Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size())); + } + + @Test + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaAndHashSet() { + List filteredList; + List originalList = buildEmployeeList(); + Set nameFilterSet = employeeNameFilter().stream() + .collect(Collectors.toSet()); + + filteredList = originalList.stream() + .filter(employee -> nameFilterSet.contains(employee.getName())) + .collect(Collectors.toList()); + + Assert.assertThat(filteredList.size(), Matchers.is(nameFilterSet.size())); + } + +} From bf31484ee367db29fc23a190698da2207ce6d0de Mon Sep 17 00:00:00 2001 From: Rodolfo Felipe Date: Mon, 4 Mar 2019 20:49:30 -0400 Subject: [PATCH 131/254] BAEL-2448-Rev2 Changing method names to comply with Jenkins PMD method naming rules. --- .../collection/filtering/CollectionFilteringTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java b/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java index bf3ec53abb..3b4a087ecd 100644 --- a/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java +++ b/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java @@ -26,7 +26,7 @@ public class CollectionFilteringTest { } @Test - public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoop() { + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoopUnitTest() { List filteredList = new ArrayList<>(); List originalList = buildEmployeeList(); List nameFilter = employeeNameFilter(); @@ -44,7 +44,7 @@ public class CollectionFilteringTest { } @Test - public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambda() { + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaUnitTest() { List filteredList; List originalList = buildEmployeeList(); List nameFilter = employeeNameFilter(); @@ -57,7 +57,7 @@ public class CollectionFilteringTest { } @Test - public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaAndHashSet() { + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaAndHashSetUnitTest() { List filteredList; List originalList = buildEmployeeList(); Set nameFilterSet = employeeNameFilter().stream() From 245e0f32b33ed5c3465bead17bbf87a8cb49d8a2 Mon Sep 17 00:00:00 2001 From: Rodolfo Felipe Date: Mon, 4 Mar 2019 20:54:50 -0400 Subject: [PATCH 132/254] BAEL-2448-Rev3 Renaming test class so it passes PMD checks. Reverting method names to previous commit. --- ...ilteringTest.java => CollectionFilteringUnitTest.java} | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) rename core-java-collections-list/src/test/java/com/baeldung/collection/filtering/{CollectionFilteringTest.java => CollectionFilteringUnitTest.java} (92%) diff --git a/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java b/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringUnitTest.java similarity index 92% rename from core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java rename to core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringUnitTest.java index 3b4a087ecd..cbc7136192 100644 --- a/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringTest.java +++ b/core-java-collections-list/src/test/java/com/baeldung/collection/filtering/CollectionFilteringUnitTest.java @@ -15,7 +15,7 @@ import org.junit.Test; * * @author Rodolfo Felipe */ -public class CollectionFilteringTest { +public class CollectionFilteringUnitTest { private List buildEmployeeList() { return Arrays.asList(new Employee(1, "Mike", 1), new Employee(2, "John", 1), new Employee(3, "Mary", 1), new Employee(4, "Joe", 2), new Employee(5, "Nicole", 2), new Employee(6, "Alice", 2), new Employee(7, "Bob", 3), new Employee(8, "Scarlett", 3)); @@ -26,7 +26,7 @@ public class CollectionFilteringTest { } @Test - public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoopUnitTest() { + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoop() { List filteredList = new ArrayList<>(); List originalList = buildEmployeeList(); List nameFilter = employeeNameFilter(); @@ -44,7 +44,7 @@ public class CollectionFilteringTest { } @Test - public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaUnitTest() { + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambda() { List filteredList; List originalList = buildEmployeeList(); List nameFilter = employeeNameFilter(); @@ -57,7 +57,7 @@ public class CollectionFilteringTest { } @Test - public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaAndHashSetUnitTest() { + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaAndHashSet() { List filteredList; List originalList = buildEmployeeList(); Set nameFilterSet = employeeNameFilter().stream() From b095add969b84a4f72d6b4864ec938407ac8f07f Mon Sep 17 00:00:00 2001 From: Josephine Barboza Date: Tue, 5 Mar 2019 22:00:33 +0530 Subject: [PATCH 133/254] BAEL-2725 --- .../groovy/com/baeldung/lists/ListTest.groovy | 43 ++++++++++--------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy b/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy index 89a0194742..f682503ed4 100644 --- a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy @@ -20,11 +20,11 @@ class ListTest{ ArrayList arrList = [1, 2, 3] assertTrue(arrList.class == ArrayList) - def list2 = new ArrayList(arrList) - assertTrue(list2 == arrList) + def copyList = new ArrayList(arrList) + assertTrue(copyList == arrList) - def list3 = arrList.clone() - assertTrue(list3 == arrList) + def cloneList = arrList.clone() + assertTrue(cloneList == arrList) } @Test @@ -122,30 +122,33 @@ class ListTest{ @Test void testFilteringOnLists(){ - def list = [2, 1, 3, 4, 5, 6, 76] + def filterList = [2, 1, 3, 4, 5, 6, 76] - assertTrue(list.find{it > 3} == 4) + assertTrue(filterList.find{it > 3} == 4) - assertTrue(list.findAll{it > 3} == [4, 5, 6, 76]) + assertTrue(filterList.findAll{it > 3} == [4, 5, 6, 76]) - assertTrue(list.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76]) + assertTrue(filterList.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76]) + + assertTrue(filterList.grep( Number )== [2, 1, 3, 4, 5, 6, 76]) + + assertTrue(filterList.grep{ it> 6 }== [76]) - assertFalse(list.every{ it < 6}) + def conditionList = [2, 1, 3, 4, 5, 6, 76] + + assertFalse(conditionList.every{ it < 6}) - assertTrue(list.any{ it%2 == 0}) + assertTrue(conditionList.any{ it%2 == 0}) - assertTrue(list.grep( Number )== [2, 1, 3, 4, 5, 6, 76]) - - assertTrue(list.grep{ it> 6 }== [76]) } @Test void testGetUniqueItemsInAList(){ assertTrue([1, 3, 3, 4].toUnique() == [1, 3, 4]) - def list = [1, 3, 3, 4] - list.unique() - assertTrue(list == [1, 3, 4]) + def uniqueList = [1, 3, 3, 4] + uniqueList.unique() + assertTrue(uniqueList == [1, 3, 4]) assertTrue(["A", "B", "Ba", "Bat", "Cat"].toUnique{ it.size()} == ["A", "Ba", "Bat"]) } @@ -160,11 +163,11 @@ class ListTest{ list.sort(mc) assertTrue(list == [2, 1, 1, 0]) - def list1 = ["na", "ppp", "as"] - assertTrue(list1.max() == "ppp") + def strList = ["na", "ppp", "as"] + assertTrue(strList.max() == "ppp") Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1} - def list2 = [3, 2, 0, 7] - assertTrue(list2.min(minc) == 0) + def numberList = [3, 2, 0, 7] + assertTrue(numberList.min(minc) == 0) } } \ No newline at end of file From 9c62f1ea0c0be4a6a352a76496448ba9e422d149 Mon Sep 17 00:00:00 2001 From: Ganesh Pagade Date: Tue, 5 Mar 2019 22:27:46 +0530 Subject: [PATCH 134/254] minor change --- .../java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java index 7032dde1ce..020118aa2b 100644 --- a/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java +++ b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java @@ -37,8 +37,7 @@ public class GsonAdvanceUnitTest { Gson gson = new Gson(); List list = gson.fromJson(inputString, ArrayList.class); - assertEquals(2, list.size()); - int id = list.get(0).getId(); + assertEquals(1, list.get(0).getId()); } @Test public void givenJsonString_whenDeserializing_thenReturnListOfMyClass() { From b1834b6d96b566faed1f520552cbb14e650052d6 Mon Sep 17 00:00:00 2001 From: Ganesh Pagade Date: Tue, 5 Mar 2019 22:29:31 +0530 Subject: [PATCH 135/254] minor change --- .../main/java/org/baeldung/gson/entities/MyClass.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/gson/src/main/java/org/baeldung/gson/entities/MyClass.java b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java index 86e14985da..827ca10cb0 100644 --- a/gson/src/main/java/org/baeldung/gson/entities/MyClass.java +++ b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java @@ -9,16 +9,6 @@ public class MyClass { strings = new String[] { "a", "b" }; } - - // @Override - // public String toString() { - // return "{" + - // "id=" + id + - // ", name='" + name + '\'' + - // ", strings=" + Arrays.toString(strings) + - // '}'; - // } - public int getId() { return id; } From 0983aa916328e8097908b0fc6eb2f462bbef7e85 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Tue, 5 Mar 2019 21:14:51 +0100 Subject: [PATCH 136/254] CF UAA config && demo. --- cloud-foundry-uaa/cf-uaa-config/uaa.yml | 73 +++++++++++++++++ .../cf-uaa-oauth2-client/pom.xml | 43 ++++++++++ .../client/CFUAAOAuth2ClientApplication.java | 13 +++ .../client/CFUAAOAuth2ClientController.java | 80 +++++++++++++++++++ .../src/main/resources/application.properties | 23 ++++++ .../src/main/resources/templates/index.html | 1 + .../cf-uaa-oauth2-resource-server/pom.xml | 43 ++++++++++ .../CFUAAOAuth2ResourceServerApplication.java | 13 +++ ...UAAOAuth2ResourceServerRestController.java | 28 +++++++ ...h2ResourceServerSecurityConfiguration.java | 21 +++++ .../src/main/resources/application.properties | 16 ++++ 11 files changed, 354 insertions(+) create mode 100644 cloud-foundry-uaa/cf-uaa-config/uaa.yml create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java create mode 100644 cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties diff --git a/cloud-foundry-uaa/cf-uaa-config/uaa.yml b/cloud-foundry-uaa/cf-uaa-config/uaa.yml new file mode 100644 index 0000000000..b782c2b681 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-config/uaa.yml @@ -0,0 +1,73 @@ +issuer: + uri: http://localhost:8080/uaa + +spring_profiles: postgresql,default + +database.driverClassName: org.postgresql.Driver +database.url: jdbc:postgresql:uaadb2 +database.username: postgres +database.password: postgres + +encryption: + active_key_label: CHANGE-THIS-KEY + encryption_keys: + - label: CHANGE-THIS-KEY + passphrase: CHANGEME + +login: + serviceProviderKey: | + -----BEGIN RSA PRIVATE KEY----- + MIICXQIBAAKBgQDHtC5gUXxBKpEqZTLkNvFwNGnNIkggNOwOQVNbpO0WVHIivig5 + L39WqS9u0hnA+O7MCA/KlrAR4bXaeVVhwfUPYBKIpaaTWFQR5cTR1UFZJL/OF9vA + fpOwznoD66DDCnQVpbCjtDYWX+x6imxn8HCYxhMol6ZnTbSsFW6VZjFMjQIDAQAB + AoGAVOj2Yvuigi6wJD99AO2fgF64sYCm/BKkX3dFEw0vxTPIh58kiRP554Xt5ges + 7ZCqL9QpqrChUikO4kJ+nB8Uq2AvaZHbpCEUmbip06IlgdA440o0r0CPo1mgNxGu + lhiWRN43Lruzfh9qKPhleg2dvyFGQxy5Gk6KW/t8IS4x4r0CQQD/dceBA+Ndj3Xp + ubHfxqNz4GTOxndc/AXAowPGpge2zpgIc7f50t8OHhG6XhsfJ0wyQEEvodDhZPYX + kKBnXNHzAkEAyCA76vAwuxqAd3MObhiebniAU3SnPf2u4fdL1EOm92dyFs1JxyyL + gu/DsjPjx6tRtn4YAalxCzmAMXFSb1qHfwJBAM3qx3z0gGKbUEWtPHcP7BNsrnWK + vw6By7VC8bk/ffpaP2yYspS66Le9fzbFwoDzMVVUO/dELVZyBnhqSRHoXQcCQQCe + A2WL8S5o7Vn19rC0GVgu3ZJlUrwiZEVLQdlrticFPXaFrn3Md82ICww3jmURaKHS + N+l4lnMda79eSp3OMmq9AkA0p79BvYsLshUJJnvbk76pCjR28PK4dV1gSDUEqQMB + qy45ptdwJLqLJCeNoR0JUcDNIRhOCuOPND7pcMtX6hI/ + -----END RSA PRIVATE KEY----- + serviceProviderKeyPassword: password + serviceProviderCertificate: | + -----BEGIN CERTIFICATE----- + MIIDSTCCArKgAwIBAgIBADANBgkqhkiG9w0BAQQFADB8MQswCQYDVQQGEwJhdzEO + MAwGA1UECBMFYXJ1YmExDjAMBgNVBAoTBWFydWJhMQ4wDAYDVQQHEwVhcnViYTEO + MAwGA1UECxMFYXJ1YmExDjAMBgNVBAMTBWFydWJhMR0wGwYJKoZIhvcNAQkBFg5h + cnViYUBhcnViYS5hcjAeFw0xNTExMjAyMjI2MjdaFw0xNjExMTkyMjI2MjdaMHwx + CzAJBgNVBAYTAmF3MQ4wDAYDVQQIEwVhcnViYTEOMAwGA1UEChMFYXJ1YmExDjAM + BgNVBAcTBWFydWJhMQ4wDAYDVQQLEwVhcnViYTEOMAwGA1UEAxMFYXJ1YmExHTAb + BgkqhkiG9w0BCQEWDmFydWJhQGFydWJhLmFyMIGfMA0GCSqGSIb3DQEBAQUAA4GN + ADCBiQKBgQDHtC5gUXxBKpEqZTLkNvFwNGnNIkggNOwOQVNbpO0WVHIivig5L39W + qS9u0hnA+O7MCA/KlrAR4bXaeVVhwfUPYBKIpaaTWFQR5cTR1UFZJL/OF9vAfpOw + znoD66DDCnQVpbCjtDYWX+x6imxn8HCYxhMol6ZnTbSsFW6VZjFMjQIDAQABo4Ha + MIHXMB0GA1UdDgQWBBTx0lDzjH/iOBnOSQaSEWQLx1syGDCBpwYDVR0jBIGfMIGc + gBTx0lDzjH/iOBnOSQaSEWQLx1syGKGBgKR+MHwxCzAJBgNVBAYTAmF3MQ4wDAYD + VQQIEwVhcnViYTEOMAwGA1UEChMFYXJ1YmExDjAMBgNVBAcTBWFydWJhMQ4wDAYD + VQQLEwVhcnViYTEOMAwGA1UEAxMFYXJ1YmExHTAbBgkqhkiG9w0BCQEWDmFydWJh + QGFydWJhLmFyggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAYvBJ + 0HOZbbHClXmGUjGs+GS+xC1FO/am2suCSYqNB9dyMXfOWiJ1+TLJk+o/YZt8vuxC + KdcZYgl4l/L6PxJ982SRhc83ZW2dkAZI4M0/Ud3oePe84k8jm3A7EvH5wi5hvCkK + RpuRBwn3Ei+jCRouxTbzKPsuCVB+1sNyxMTXzf0= + -----END CERTIFICATE----- + +#The secret that an external login server will use to authenticate to the uaa using the id `login` +LOGIN_SECRET: loginsecret + +jwt: + token: + signing-key: | + -----BEGIN RSA PRIVATE KEY----- + MIIEpAIBAAKCAQEAqUeygEfDGxI6c1VDQ6xIyUSLrP6iz1y97iHFbtXSxXaArL4a + ... + v6Mtt5LcRAAVP7pemunTdju4h8Q/noKYlVDVL30uLYUfKBL4UKfOBw== + -----END RSA PRIVATE KEY----- + verification-key: | + -----BEGIN PUBLIC KEY----- + MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqUeygEfDGxI6c1VDQ6xI + ... + AwIDAQAB + -----END PUBLIC KEY----- diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml new file mode 100644 index 0000000000..8e31cc41fb --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.3.RELEASE + + + com.example + cf-uaa-oauth2-client + 0.0.1-SNAPSHOT + uaa-client-webapp + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java new file mode 100644 index 0000000000..c9e81fcd5d --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.cfuaa.oauth2.client; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CFUAAOAuth2ClientApplication { + + public static void main(String[] args) { + SpringApplication.run(CFUAAOAuth2ClientApplication.class, args); + } + +} diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java new file mode 100644 index 0000000000..b1631ed327 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java @@ -0,0 +1,80 @@ +package com.baeldung.cfuaa.oauth2.client; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; +import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; + +@RestController +public class CFUAAOAuth2ClientController { + + @Value("${resource.server.url}") + private String remoteResourceServer; + + private RestTemplate restTemplate; + + private OAuth2AuthorizedClientService authorizedClientService; + + public CFUAAOAuth2ClientController(OAuth2AuthorizedClientService authorizedClientService) { + this.authorizedClientService = authorizedClientService; + this.restTemplate = new RestTemplate(); + } + + @RequestMapping("/") + public String index(OAuth2AuthenticationToken authenticationToken) { + OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName()); + OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken(); + + String response = "Hello, " + authenticationToken.getPrincipal().getName(); + response += "

"; + response += "Here is your accees token :
" + oAuth2AccessToken.getTokenValue(); + response += "
"; + response += "
You can use it to call these Resource Server APIs:"; + response += "

"; + response += "Call Resource Server Read API"; + response += "
"; + response += "Call Resource Server Write API"; + return response; + } + + @RequestMapping("/read") + public String read(OAuth2AuthenticationToken authenticationToken) { + String url = remoteResourceServer + "/read"; + return callResourceServer(authenticationToken, url); + } + + @RequestMapping("/write") + public String write(OAuth2AuthenticationToken authenticationToken) { + String url = remoteResourceServer + "/write"; + return callResourceServer(authenticationToken, url); + } + + private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) { + OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName()); + OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken(); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue()); + + HttpEntity entity = new HttpEntity<>("parameters", headers); + ResponseEntity responseEntity = null; + + String response = null; + try { + responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); + response = responseEntity.getBody(); + } catch (HttpClientErrorException e) { + response = e.getMessage(); + } + return response; + } +} \ No newline at end of file diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties new file mode 100644 index 0000000000..de8e1a7b9f --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties @@ -0,0 +1,23 @@ +# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties) +#spring.security.oauth2.client.provider.*= # OAuth provider details. +#spring.security.oauth2.client.registration.*= # OAuth client registrations. + +server.port=8081 +#server.servlet.context-path=/uaa-client-webapp + +uaa.url=http://localhost:8080/uaa +resource.server.url=http://localhost:8082 + +spring.security.oauth2.client.registration.uaa.client-name=UAA OAuth2 Client +spring.security.oauth2.client.registration.uaa.client-id=client1 +spring.security.oauth2.client.registration.uaa.client-secret=client1 +spring.security.oauth2.client.registration.uaa.authorization-grant-type=authorization_code +spring.security.oauth2.client.registration.uaa.scope=resource.read,resource.write,openid,profile +spring.security.oauth2.client.registration.uaa.redirect-uri=http://localhost:8081/login/oauth2/code/uaa +#spring.security.oauth2.client.registration.uaa.redirect-uri=http://localhost:8081/** + +spring.security.oauth2.client.provider.uaa.token-uri=${uaa.url}/oauth/token +spring.security.oauth2.client.provider.uaa.authorization-uri=${uaa.url}/oauth/authorize +spring.security.oauth2.client.provider.uaa.jwk-set-uri=${uaa.url}/token_keys +spring.security.oauth2.client.provider.uaa.user-info-uri=${uaa.url}/userinfo +spring.security.oauth2.client.provider.uaa.user-name-attribute=user_name diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html new file mode 100644 index 0000000000..eb6e267b94 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html @@ -0,0 +1 @@ +tintin \ No newline at end of file diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml new file mode 100644 index 0000000000..9cf8993cd2 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.3.RELEASE + + + com.baeldung.cfuaa + cf-uaa-oauth2-resource-server + 0.0.1-SNAPSHOT + cf-uaa-oauth2-resource-server + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java new file mode 100644 index 0000000000..51ad6e938d --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.cfuaa.oauth2.resourceserver; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CFUAAOAuth2ResourceServerApplication { + + public static void main(String[] args) { + SpringApplication.run(CFUAAOAuth2ResourceServerApplication.class, args); + } + +} diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java new file mode 100644 index 0000000000..c08f17d8d8 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java @@ -0,0 +1,28 @@ +package com.baeldung.cfuaa.oauth2.resourceserver; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.security.Principal; + +@RestController +public class CFUAAOAuth2ResourceServerRestController { + + @GetMapping("/") + public String index(@AuthenticationPrincipal Jwt jwt) { + return String.format("Hello, %s!", jwt.getSubject()); + } + + @GetMapping("/read") + public String read(JwtAuthenticationToken jwtAuthenticationToken) { + return "Hello write: " + jwtAuthenticationToken.getTokenAttributes(); + } + + @GetMapping("/write") + public String write(Principal principal) { + return "Hello write: " + principal.getName(); + } +} diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java new file mode 100644 index 0000000000..d04d51cda3 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java @@ -0,0 +1,21 @@ +package com.baeldung.cfuaa.oauth2.resourceserver; + +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@EnableWebSecurity +public class CFUAAOAuth2ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/read/**").hasAuthority("SCOPE_resource.read") + .antMatchers("/write/**").hasAuthority("SCOPE_resource.write") + .anyRequest().authenticated() + .and() + .oauth2ResourceServer() + .jwt(); + } +} \ No newline at end of file diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties new file mode 100644 index 0000000000..ba9b95e0d4 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties @@ -0,0 +1,16 @@ +server.port=8082 + +uaa.url=http://localhost:8080/uaa + +#approch1 +spring.security.oauth2.resourceserver.jwt.issuer-uri=${uaa.url}/oauth/token + +#approch2 +#spring.security.oauth2.resourceserver.jwt.jwk-set-uri=${uaa.url}/token_key + +# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties) +#security.oauth2.client.client-id=client1 +#security.oauth2.client.client-secret=client1 + +#security.oauth2.resource.jwt.key-uri=${uaa.url}/token_key +#security.oauth2.resource.token-info-uri=${uaa.url}/oauth/check_token From 9f22567d4f0935ac1c4da08c8f745847a3f477a4 Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Sat, 2 Mar 2019 11:06:35 -0500 Subject: [PATCH 137/254] BAEL-2727 Example Code --- .../main/groovy/com/baeldung/io/Task.groovy | 8 ++ .../src/main/resources/binaryExample.jpg | Bin 0 -> 1139 bytes core-groovy/src/main/resources/ioData.txt | Bin 0 -> 34 bytes core-groovy/src/main/resources/ioInput.txt | 4 + core-groovy/src/main/resources/ioOutput.txt | 3 + .../src/main/resources/ioSerializedObject.txt | Bin 0 -> 199 bytes .../baeldung/io/DataAndObjectsUnitTest.groovy | 51 +++++++ .../baeldung/io/ReadExampleUnitTest.groovy | 134 ++++++++++++++++++ .../io/TraverseFileTreeUnitTest.groovy | 61 ++++++++ .../baeldung/io/WriteExampleUnitTest.groovy | 96 +++++++++++++ 10 files changed, 357 insertions(+) create mode 100644 core-groovy/src/main/groovy/com/baeldung/io/Task.groovy create mode 100644 core-groovy/src/main/resources/binaryExample.jpg create mode 100644 core-groovy/src/main/resources/ioData.txt create mode 100644 core-groovy/src/main/resources/ioInput.txt create mode 100644 core-groovy/src/main/resources/ioOutput.txt create mode 100644 core-groovy/src/main/resources/ioSerializedObject.txt create mode 100644 core-groovy/src/test/groovy/com/baeldung/io/DataAndObjectsUnitTest.groovy create mode 100644 core-groovy/src/test/groovy/com/baeldung/io/ReadExampleUnitTest.groovy create mode 100644 core-groovy/src/test/groovy/com/baeldung/io/TraverseFileTreeUnitTest.groovy create mode 100644 core-groovy/src/test/groovy/com/baeldung/io/WriteExampleUnitTest.groovy diff --git a/core-groovy/src/main/groovy/com/baeldung/io/Task.groovy b/core-groovy/src/main/groovy/com/baeldung/io/Task.groovy new file mode 100644 index 0000000000..8a3bedc048 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/io/Task.groovy @@ -0,0 +1,8 @@ +package com.baeldung.io + +class Task implements Serializable { + String description + Date startDate + Date dueDate + int status +} diff --git a/core-groovy/src/main/resources/binaryExample.jpg b/core-groovy/src/main/resources/binaryExample.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4b32645ac9b8030b3ed570263cd4f5c477a13d0f GIT binary patch literal 1139 zcmex=``2_j6xdp@o1cgOJMMZh|#U;coyG6VInuyV4pa*FVB^NNrR z{vTivwh= zDOELf4NWZ*Q!{f5ODks=S2uSLPp{yR(6I1`$f)F$)U@=B%&g*)(z5c3%Btp;*0%PJ z&aO$5r%atTea6gLixw|gx@`H1m8&*w-m-Pu_8mKS9XfpE=&|D`PM*4S`O4L6*Kgds z_3+W-Cr_U}fAR9w$4{TXeEs(Q$Io9Ne=#yJL%ap|8JfQYf&OA*VPR%r2lxYE z#}NLy#lXYN2#h>tK?Zwsdx80d=DeqoLp33BN>@lV5)W0p*xBF6khQ3U6 zd|u@KEmAIb41aHDTx{>#nkC<~Jx*3U>Uf9g?-TCdWVB0j6ID+27Ax=^&QO1*obaGL zF@Af(VsHJEk9BnJsHWWR@(aq%*y``S^~J;|=RU8_)Ly*5{gHTgeOkOMcddR{_HHJz zvQ1OwD?L;4=b8C4y2+f+eZ9r{3-#^)Y%cv%t}yrfs5Vpmm)v58sevc%N~g5DeGlVV zen;w0{g3vKPVbM$DeSnqzRcwulRHm+nTf1O)!$mr^-KOSRoFk$+xua*)BcNgS4?)c zJmZ~x;J`eG!p2v;m3tgpmiHXGxVCFba%`lR*R7Y=?$$r(Ynh{RrL^;1{5J77O?5WM z**o@_7PHNN%&k!~X*$aq^NUPgiw)$pd*-g~k$LbSVf`^V{tx~~);Hxo;?{AXX;%T4=@?p*vK{+sQO z^N*QpZr%B@-hbzZ^0v^!G2S)%V(+Z7S`#pThVb9#419YYi~gGYu%0(_AMb~Ea~Hn& swmNlL<_F!qdpIu&y0KsRHShT>jde1|Wuqm7uEupQ40*6 + out.writeUTF(message) + out.writeInt(length) + out.writeBoolean(valid) + } + + String loadedMessage = "" + int loadedLength + boolean loadedValid + + new File('src/main/resources/ioData.txt').withDataInputStream { is -> + loadedMessage = is.readUTF() + loadedLength = is.readInt() + loadedValid = is.readBoolean() + } + + assertEquals(message, loadedMessage) + assertEquals(length, loadedLength) + assertEquals(valid, loadedValid) + } + + @Test + void whenUsingWithObjectOutputStream_thenObjectIsSerializedToFile() { + Task task = new Task(description:'Take out the trash', startDate:new Date(), status:0) + new File('src/main/resources/ioSerializedObject.txt').withObjectOutputStream { out -> + out.writeObject(task) + } + + Task taskRead + + new File('src/main/resources/ioSerializedObject.txt').withObjectInputStream { is -> + taskRead = is.readObject() + } + + assertEquals(task.description, taskRead.description) + assertEquals(task.startDate, taskRead.startDate) + assertEquals(task.status, taskRead.status) + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/io/ReadExampleUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/io/ReadExampleUnitTest.groovy new file mode 100644 index 0000000000..bed77b4d81 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/io/ReadExampleUnitTest.groovy @@ -0,0 +1,134 @@ +package com.baeldung.io + +import static org.junit.Assert.* +import org.junit.Test + +class ReadExampleUnitTest { + + @Test + void whenUsingEachLine_thenCorrectLinesReturned() { + def expectedList = [ + 'First line of text', + 'Second line of text', + 'Third line of text', + 'Fourth line of text'] + + def lines = [] + + new File('src/main/resources/ioInput.txt').eachLine { line -> + lines.add(line) + } + assertEquals(expectedList, lines) + } + + @Test + void whenUsingReadEachLineWithLineNumber_thenCorrectLinesReturned() { + def expectedList = [ + 'Second line of text', + 'Third line of text', + 'Fourth line of text'] + + def lineNoRange = 2..4 + def lines = [] + + new File('src/main/resources/ioInput.txt').eachLine { line, lineNo -> + if (lineNoRange.contains(lineNo)) { + lines.add(line) + } + } + assertEquals(expectedList, lines) + } + + @Test + void whenUsingReadEachLineWithLineNumberStartAtZero_thenCorrectLinesReturned() { + def expectedList = [ + 'Second line of text', + 'Third line of text', + 'Fourth line of text'] + + def lineNoRange = 1..3 + def lines = [] + + new File('src/main/resources/ioInput.txt').eachLine(0, { line, lineNo -> + if (lineNoRange.contains(lineNo)) { + lines.add(line) + } + }) + assertEquals(expectedList, lines) + } + + @Test + void whenUsingWithReader_thenLineCountReturned() { + def expectedCount = 4 + def actualCount = 0 + new File('src/main/resources/ioInput.txt').withReader { reader -> + while(reader.readLine()) { + actualCount++ + } + } + assertEquals(expectedCount, actualCount) + } + + @Test + void whenUsingNewReader_thenOutputFileCreated() { + def outputPath = 'src/main/resources/ioOut.txt' + def reader = new File('src/main/resources/ioInput.txt').newReader() + new File(outputPath).append(reader) + reader.close() + def ioOut = new File(outputPath) + assertTrue(ioOut.exists()) + ioOut.delete() + } + + @Test + void whenUsingWithInputStream_thenCorrectBytesAreReturned() { + def expectedLength = 1139 + byte[] data = [] + new File("src/main/resources/binaryExample.jpg").withInputStream { stream -> + data = stream.getBytes() + } + assertEquals(expectedLength, data.length) + } + + @Test + void whenUsingNewInputStream_thenOutputFileCreated() { + def outputPath = 'src/main/resources/binaryOut.jpg' + def is = new File('src/main/resources/binaryExample.jpg').newInputStream() + new File(outputPath).append(is) + is.close() + def ioOut = new File(outputPath) + assertTrue(ioOut.exists()) + ioOut.delete() + } + + @Test + void whenUsingCollect_thenCorrectListIsReturned() { + def expectedList = ['First line of text', 'Second line of text', 'Third line of text', 'Fourth line of text'] + + def actualList = new File('src/main/resources/ioInput.txt').collect {it} + assertEquals(expectedList, actualList) + } + + @Test + void whenUsingAsStringArray_thenCorrectArrayIsReturned() { + String[] expectedArray = ['First line of text', 'Second line of text', 'Third line of text', 'Fourth line of text'] + + def actualArray = new File('src/main/resources/ioInput.txt') as String[] + assertArrayEquals(expectedArray, actualArray) + } + + @Test + void whenUsingText_thenCorrectStringIsReturned() { + def ln = System.getProperty('line.separator') + def expectedString = "First line of text${ln}Second line of text${ln}Third line of text${ln}Fourth line of text" + def actualString = new File('src/main/resources/ioInput.txt').text + assertEquals(expectedString.toString(), actualString) + } + + @Test + void whenUsingBytes_thenByteArrayIsReturned() { + def expectedLength = 1139 + def contents = new File('src/main/resources/binaryExample.jpg').bytes + assertEquals(expectedLength, contents.length) + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/io/TraverseFileTreeUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/io/TraverseFileTreeUnitTest.groovy new file mode 100644 index 0000000000..dac0189fb9 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/io/TraverseFileTreeUnitTest.groovy @@ -0,0 +1,61 @@ +package com.baeldung.io + +import org.junit.Test + +import groovy.io.FileType +import groovy.io.FileVisitResult + +class TraverseFileTreeUnitTest { + @Test + void whenUsingEachFile_filesAreListed() { + new File('src/main/resources').eachFile { file -> + println file.name + } + } + + @Test(expected = IllegalArgumentException) + void whenUsingEachFileOnAFile_anErrorOccurs() { + new File('src/main/resources/ioInput.txt').eachFile { file -> + println file.name + } + } + + @Test + void whenUsingEachFileMatch_filesAreListed() { + new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file -> + println file.name + } + } + + @Test + void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() { + new File('src/main').eachFileRecurse(FileType.FILES) { file -> + println "$file.parent $file.name" + } + } + + @Test + void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() { + new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file -> + println "$file.parent $file.name" + } + } + + @Test + void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() { + new File('src/main').eachDirRecurse { dir -> + println "$dir.parent $dir.name" + } + } + + @Test + void whenUsingTraverse_thenDirectoryIsTraversed() { + new File('src/main').traverse { file -> + if (file.directory && file.name == 'groovy') { + FileVisitResult.SKIP_SUBTREE + } else { + println "$file.parent - $file.name" + } + } + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/io/WriteExampleUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/io/WriteExampleUnitTest.groovy new file mode 100644 index 0000000000..81758b430a --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/io/WriteExampleUnitTest.groovy @@ -0,0 +1,96 @@ +package com.baeldung.io + +import static org.junit.Assert.* + +import org.junit.Before +import org.junit.Test + +class WriteExampleUnitTest { + @Before + void clearOutputFile() { + new File('src/main/resources/ioOutput.txt').text = '' + new File('src/main/resources/ioBinaryOutput.bin').delete() + } + + @Test + void whenUsingWithWriter_thenFileCreated() { + def outputLines = [ + 'Line one of output example', + 'Line two of output example', + 'Line three of output example' + ] + + def outputFileName = 'src/main/resources/ioOutput.txt' + new File(outputFileName).withWriter { writer -> + outputLines.each { line -> + writer.writeLine line + } + } + def writtenLines = new File(outputFileName).collect {it} + assertEquals(outputLines, writtenLines) + } + + @Test + void whenUsingNewWriter_thenFileCreated() { + def outputLines = [ + 'Line one of output example', + 'Line two of output example', + 'Line three of output example' + ] + + def outputFileName = 'src/main/resources/ioOutput.txt' + def writer = new File(outputFileName).newWriter() + outputLines.forEach {line -> + writer.writeLine line + } + writer.flush() + writer.close() + + def writtenLines = new File(outputFileName).collect {it} + assertEquals(outputLines, writtenLines) + } + + @Test + void whenUsingDoubleLessThanOperator_thenFileCreated() { + def outputLines = [ + 'Line one of output example', + 'Line two of output example', + 'Line three of output example' + ] + + def ln = System.getProperty('line.separator') + def outputFileName = 'src/main/resources/ioOutput.txt' + new File(outputFileName) << "Line one of output example${ln}Line two of output example${ln}Line three of output example" + def writtenLines = new File(outputFileName).collect {it} + assertEquals(outputLines.size(), writtenLines.size()) + } + + @Test + void whenUsingBytes_thenBinaryFileCreated() { + def outputFileName = 'src/main/resources/ioBinaryOutput.bin' + def outputFile = new File(outputFileName) + byte[] outBytes = [44, 88, 22] + outputFile.bytes = outBytes + assertEquals(3, new File(outputFileName).size()) + } + + @Test + void whenUsingWithOutputStream_thenBinaryFileCreated() { + def outputFileName = 'src/main/resources/ioBinaryOutput.bin' + byte[] outBytes = [44, 88, 22] + new File(outputFileName).withOutputStream { stream -> + stream.write(outBytes) + } + assertEquals(3, new File(outputFileName).size()) + } + + @Test + void whenUsingNewOutputStream_thenBinaryFileCreated() { + def outputFileName = 'src/main/resources/ioBinaryOutput.bin' + byte[] outBytes = [44, 88, 22] + def os = new File(outputFileName).newOutputStream() + os.write(outBytes) + os.close() + assertEquals(3, new File(outputFileName).size()) + } +} From 4376424e512d9296cc2914049f3dcf8d00d55231 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Wed, 6 Mar 2019 07:14:23 +0000 Subject: [PATCH 138/254] Adding XMLGregorianCalendar to LocalDate converters --- .../XmlGregorianCalendarConverter.java | 29 ++++++++++++ .../XmlGregorianCalendarConverterTest.java | 44 +++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 java-dates/src/main/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverter.java create mode 100644 java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java diff --git a/java-dates/src/main/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverter.java b/java-dates/src/main/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverter.java new file mode 100644 index 0000000000..7f7515ec4b --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverter.java @@ -0,0 +1,29 @@ +package com.baeldung.xmlgregoriancalendar; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.time.LocalDate; + +public class XmlGregorianCalendarConverter { + + public static void main(String[] args) throws DatatypeConfigurationException { + LocalDate localDate = LocalDate.now(); + System.out.println("localdate: " + localDate); + XMLGregorianCalendar xmlGregorianCalendar = fromLocalDate(localDate); + System.out.println("xmlGregorianCalendar: " + xmlGregorianCalendar); + + xmlGregorianCalendar.setTime(1, 1, 30); + System.out.println("xmlGregorianCalendar with time information: " + xmlGregorianCalendar); + LocalDate newLocalDate = fromXMLGregorianCalendar(xmlGregorianCalendar); + System.out.println("newLocalDate: " + newLocalDate); + } + + static XMLGregorianCalendar fromLocalDate(LocalDate localDate) throws DatatypeConfigurationException { + return DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString()); + } + + static LocalDate fromXMLGregorianCalendar(XMLGregorianCalendar xmlGregorianCalendar) { + return LocalDate.of(xmlGregorianCalendar.getYear(), xmlGregorianCalendar.getMonth(), xmlGregorianCalendar.getDay()); + } +} diff --git a/java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java b/java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java new file mode 100644 index 0000000000..f27c91be7e --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java @@ -0,0 +1,44 @@ +package com.baeldung.xmlgregoriancalendar; + +import org.junit.Test; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.time.LocalDate; + +import static com.baeldung.xmlgregoriancalendar.XmlGregorianCalendarConverter.fromLocalDate; +import static com.baeldung.xmlgregoriancalendar.XmlGregorianCalendarConverter.fromXMLGregorianCalendar; +import static org.assertj.core.api.Assertions.assertThat; + +public class XmlGregorianCalendarConverterTest { + + @Test + public void fromLocalDateToXMLGregorianCalendar() throws DatatypeConfigurationException { + LocalDate localDate = LocalDate.of(2017, 4, 25); + XMLGregorianCalendar xmlGregorianCalendar = fromLocalDate(localDate); + + assertThat(xmlGregorianCalendar.getYear()).isEqualTo(localDate.getYear()); + assertThat(xmlGregorianCalendar.getMonth()).isEqualTo(localDate.getMonthValue()); + assertThat(xmlGregorianCalendar.getDay()).isEqualTo(localDate.getDayOfMonth()); + } + + @Test + public void fromXMLGregorianCalendarToLocalDate() throws DatatypeConfigurationException { + XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-04-25"); + LocalDate localDate = fromXMLGregorianCalendar(xmlGregorianCalendar); + + assertThat(localDate.getYear()).isEqualTo(xmlGregorianCalendar.getYear()); + assertThat(localDate.getMonthValue()).isEqualTo(xmlGregorianCalendar.getMonth()); + assertThat(localDate.getDayOfMonth()).isEqualTo(xmlGregorianCalendar.getDay()); + } + + @Test + public void compositionOfFunctionsIsIdentity() throws DatatypeConfigurationException { // Only if we don't consider time + LocalDate localDate = LocalDate.of(2017, 4, 25); + XMLGregorianCalendar xmlGregorianCalendar = fromLocalDate(localDate); + LocalDate resultDate = fromXMLGregorianCalendar(xmlGregorianCalendar); + + assertThat(resultDate).isEqualTo(localDate); + } +} From e98cc8a407b33e59c5277b50f98f4ae7684e3e2c Mon Sep 17 00:00:00 2001 From: saukedia1 Date: Wed, 6 Mar 2019 15:11:21 +0530 Subject: [PATCH 139/254] BAEL-2011 Eclipse error: web.xml is missing and is set to true --- maven/maven-war-plugin-property/pom.xml | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 maven/maven-war-plugin-property/pom.xml diff --git a/maven/maven-war-plugin-property/pom.xml b/maven/maven-war-plugin-property/pom.xml new file mode 100644 index 0000000000..7063a4e247 --- /dev/null +++ b/maven/maven-war-plugin-property/pom.xml @@ -0,0 +1,29 @@ + + 4.0.0 + com.baeldung + maven-war-plugin-property + 0.0.1-SNAPSHOT + war + maven-war-plugin-property + + + + false + + + + + + maven-war-plugin + + 3.1.0 + + + false + + + + + \ No newline at end of file From 7a029078e6860742f08fb13e6f5da75fcb81788a Mon Sep 17 00:00:00 2001 From: Urvy Agrawal Date: Thu, 7 Mar 2019 22:49:44 +0530 Subject: [PATCH 140/254] Adding files for BAEL-2196 (#6477) * Adding files for BAEL-2196 * modified Package structure --- maven/compiler-plugin-java-9/pom.xml | 22 +++++++++++++++++++ .../maven/java9/MavenCompilerPlugin.java | 9 ++++++++ .../src/main/java/module-info.java | 3 +++ 3 files changed, 34 insertions(+) create mode 100644 maven/compiler-plugin-java-9/pom.xml create mode 100644 maven/compiler-plugin-java-9/src/main/java/com/baeldung/maven/java9/MavenCompilerPlugin.java create mode 100644 maven/compiler-plugin-java-9/src/main/java/module-info.java diff --git a/maven/compiler-plugin-java-9/pom.xml b/maven/compiler-plugin-java-9/pom.xml new file mode 100644 index 0000000000..5303cee82e --- /dev/null +++ b/maven/compiler-plugin-java-9/pom.xml @@ -0,0 +1,22 @@ + + 4.0.0 + com.baeldung + compiler-plugin-java-9 + 0.0.1-SNAPSHOT + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + 9 + 9 + + + + + \ No newline at end of file diff --git a/maven/compiler-plugin-java-9/src/main/java/com/baeldung/maven/java9/MavenCompilerPlugin.java b/maven/compiler-plugin-java-9/src/main/java/com/baeldung/maven/java9/MavenCompilerPlugin.java new file mode 100644 index 0000000000..b460d6e38c --- /dev/null +++ b/maven/compiler-plugin-java-9/src/main/java/com/baeldung/maven/java9/MavenCompilerPlugin.java @@ -0,0 +1,9 @@ +package com.baeldung.maven.java9; + +import static javax.xml.XMLConstants.XML_NS_PREFIX; + +public class MavenCompilerPlugin { + public static void main(String[] args) { + System.out.println("The XML namespace prefix is: " + XML_NS_PREFIX); + } +} diff --git a/maven/compiler-plugin-java-9/src/main/java/module-info.java b/maven/compiler-plugin-java-9/src/main/java/module-info.java new file mode 100644 index 0000000000..afc1d45e71 --- /dev/null +++ b/maven/compiler-plugin-java-9/src/main/java/module-info.java @@ -0,0 +1,3 @@ +module com.baeldung.maven.java9 { + requires java.xml; +} \ No newline at end of file From 67ed044498250f2b62a55866d63efd45dd5c4119 Mon Sep 17 00:00:00 2001 From: eric-martin Date: Thu, 7 Mar 2019 21:52:47 -0600 Subject: [PATCH 141/254] BAEL-2755: Added design-patterns-2 module --- patterns/design-patterns-2/pom.xml | 25 +++++++++++++++++++ .../com/baeldung/nullobject/JmsRouter.java | 0 .../java/com/baeldung/nullobject/Message.java | 0 .../com/baeldung/nullobject/NullRouter.java | 0 .../java/com/baeldung/nullobject/Router.java | 0 .../baeldung/nullobject/RouterFactory.java | 0 .../baeldung/nullobject/RoutingHandler.java | 0 .../com/baeldung/nullobject/SmsRouter.java | 0 patterns/pom.xml | 1 + 9 files changed, 26 insertions(+) create mode 100644 patterns/design-patterns-2/pom.xml rename patterns/{design-patterns => design-patterns-2}/src/main/java/com/baeldung/nullobject/JmsRouter.java (100%) rename patterns/{design-patterns => design-patterns-2}/src/main/java/com/baeldung/nullobject/Message.java (100%) rename patterns/{design-patterns => design-patterns-2}/src/main/java/com/baeldung/nullobject/NullRouter.java (100%) rename patterns/{design-patterns => design-patterns-2}/src/main/java/com/baeldung/nullobject/Router.java (100%) rename patterns/{design-patterns => design-patterns-2}/src/main/java/com/baeldung/nullobject/RouterFactory.java (100%) rename patterns/{design-patterns => design-patterns-2}/src/main/java/com/baeldung/nullobject/RoutingHandler.java (100%) rename patterns/{design-patterns => design-patterns-2}/src/main/java/com/baeldung/nullobject/SmsRouter.java (100%) diff --git a/patterns/design-patterns-2/pom.xml b/patterns/design-patterns-2/pom.xml new file mode 100644 index 0000000000..2a0213065b --- /dev/null +++ b/patterns/design-patterns-2/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + design-patterns-2 + 1.0 + design-patterns-2 + jar + + + com.baeldung + patterns + 1.0.0-SNAPSHOT + .. + + + + + + + UTF-8 + 1.8 + 1.8 + + diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/JmsRouter.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/JmsRouter.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/JmsRouter.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/JmsRouter.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Message.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/Message.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/Message.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/Message.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/NullRouter.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/NullRouter.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Router.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/Router.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/Router.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/Router.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RouterFactory.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/RouterFactory.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/RouterFactory.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/RouterFactory.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RoutingHandler.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/RoutingHandler.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/RoutingHandler.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/RoutingHandler.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/SmsRouter.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/SmsRouter.java diff --git a/patterns/pom.xml b/patterns/pom.xml index 3c3bb6d5ea..111e72b9ca 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -17,6 +17,7 @@ front-controller intercepting-filter design-patterns + design-patterns-2 solid From b9c7d82e15f564fe2c5e45b41fa2ed8bc388c107 Mon Sep 17 00:00:00 2001 From: saukedia1 Date: Fri, 8 Mar 2019 15:57:20 +0530 Subject: [PATCH 142/254] BAEL-2011 Eclipse error: web.xml is missing and is set to true --- maven/{maven-war-plugin-property => maven-war-plugin}/pom.xml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename maven/{maven-war-plugin-property => maven-war-plugin}/pom.xml (100%) diff --git a/maven/maven-war-plugin-property/pom.xml b/maven/maven-war-plugin/pom.xml similarity index 100% rename from maven/maven-war-plugin-property/pom.xml rename to maven/maven-war-plugin/pom.xml From 558e316623b1a28e7ef81d54853d72c3f34b1d61 Mon Sep 17 00:00:00 2001 From: saukedia1 Date: Fri, 8 Mar 2019 16:02:36 +0530 Subject: [PATCH 143/254] BAEL-2011 Eclipse error: web.xml is missing and is set to true --- maven/maven-war-plugin/pom.xml | 52 +++++++++++++++++----------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/maven/maven-war-plugin/pom.xml b/maven/maven-war-plugin/pom.xml index 7063a4e247..5169a21e78 100644 --- a/maven/maven-war-plugin/pom.xml +++ b/maven/maven-war-plugin/pom.xml @@ -1,29 +1,29 @@ - 4.0.0 - com.baeldung - maven-war-plugin-property - 0.0.1-SNAPSHOT - war - maven-war-plugin-property + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + maven-war-plugin-property + 0.0.1-SNAPSHOT + war + maven-war-plugin-property + + + + false + - - - false - - - - - - maven-war-plugin - - 3.1.0 - - - false - - - - + + + + maven-war-plugin + + 3.1.0 + + + false + + + + \ No newline at end of file From 786888f7c33d5bd147654565a5a810dfba8ad0b6 Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Fri, 8 Mar 2019 08:39:44 -0300 Subject: [PATCH 144/254] BAEL-12777 Upgrade parent-spring-5 version: * Migrated parent-spring-5 version (spring-core and spring-security) * Cleaned spring-security version being used in some modules. Now using the parent version --- parent-spring-5/pom.xml | 4 ++-- spring-mvc-simple/pom.xml | 3 +-- spring-security-mvc-custom/pom.xml | 11 ++++------- spring-security-mvc-jsonview/pom.xml | 11 ++++------- spring-security-mvc-login/pom.xml | 9 ++++----- spring-security-rest/pom.xml | 7 +++---- spring-static-resources/pom.xml | 9 +++------ 7 files changed, 21 insertions(+), 33 deletions(-) diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 5d7a3b66b3..3178682d34 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -29,10 +29,10 @@ - 5.1.2.RELEASE + 5.1.4.RELEASE 5.0.2 2.9.6 - 5.1.2.RELEASE + 5.1.4.RELEASE \ No newline at end of file diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 8c2661cc27..b9ed3a3e81 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -17,7 +17,7 @@ org.springframework spring-oxm - ${spring-oxm.version} + ${spring.version} com.sun.mail @@ -181,7 +181,6 @@ 1.4.9 5.1.0 20180130 - 5.0.2.RELEASE 3.0.8 diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index b4239fb2b8..7c60a8e18a 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -21,17 +21,17 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} + ${spring-security.version} @@ -144,7 +144,7 @@ org.springframework.security spring-security-test - ${org.springframework.security.version} + ${spring-security.version} test @@ -192,9 +192,6 @@
- - 5.0.6.RELEASE - 3.1.0 1.2 diff --git a/spring-security-mvc-jsonview/pom.xml b/spring-security-mvc-jsonview/pom.xml index 7f1129128f..b6d3e7e399 100644 --- a/spring-security-mvc-jsonview/pom.xml +++ b/spring-security-mvc-jsonview/pom.xml @@ -38,17 +38,17 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} + ${spring-security.version} @@ -133,7 +133,7 @@ org.springframework.security spring-security-test - ${org.springframework.security.version} + ${spring-security.version} test @@ -206,9 +206,6 @@ - - 5.0.5.RELEASE - 3.1.0 1.2 diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index bbdff6fc2f..048297bbd4 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -21,17 +21,17 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} + ${spring-security.version} @@ -116,7 +116,7 @@ org.springframework.security spring-security-test - ${org.springframework.security.version} + ${spring-security.version} test @@ -175,7 +175,6 @@ - 5.0.5.RELEASE 3.1.0 diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 37c743e896..24f1c5807a 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -21,12 +21,12 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} @@ -144,7 +144,7 @@ org.springframework.security spring-security-test - ${org.springframework.security.version} + ${spring-security.version} test @@ -274,7 +274,6 @@ - 5.1.0.RELEASE 0.25.0.RELEASE diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index aedf88e384..fc2b3336bc 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -20,17 +20,17 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} + ${spring-security.version} @@ -196,9 +196,6 @@ - - 5.0.6.RELEASE - 1.8.9 2.3.2-b02 From ae6c29dd19fcb5edf0182096f3f3b7b0f8a5c6e8 Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Fri, 8 Mar 2019 11:20:52 -0300 Subject: [PATCH 145/254] Guide to Stream.reduce() (#6480) * Initial Commit * Update Application.java * Update Application.java --- java-streams-2/pom.xml | 39 +++++++++ .../reduce/application/Application.java | 39 +++++++++ .../benchmarks/JMHStreamReduceBenchMark.java | 52 ++++++++++++ .../com/baeldung/reduce/entities/User.java | 25 ++++++ .../reduce/utilities/NumberUtils.java | 52 ++++++++++++ .../reduce/tests/StreamReduceUnitTest.java | 79 +++++++++++++++++++ 6 files changed, 286 insertions(+) create mode 100644 java-streams-2/pom.xml create mode 100644 java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java create mode 100644 java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java create mode 100644 java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java create mode 100644 java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java create mode 100644 java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java diff --git a/java-streams-2/pom.xml b/java-streams-2/pom.xml new file mode 100644 index 0000000000..cd89a1a80f --- /dev/null +++ b/java-streams-2/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + com.baeldung.javastreams2 + javastreams2 + 1.0 + jar + + + org.openjdk.jmh + jmh-core + 1.21 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.21 + + + junit + junit + 4.12 + test + jar + + + org.assertj + assertj-core + 3.11.1 + test + + + Stream Reduce + + UTF-8 + 1.8 + 1.8 + + \ No newline at end of file diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java b/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java new file mode 100644 index 0000000000..79c557524d --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java @@ -0,0 +1,39 @@ +package com.baeldung.reduce.application; + +import com.baeldung.reduce.entities.User; +import com.baeldung.reduce.utilities.NumberUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Application { + + public static void main(String[] args) { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); + System.out.println(result1); + + int result2 = numbers.stream().reduce(0, Integer::sum); + System.out.println(result2); + + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); + System.out.println(result3); + + String result4 = letters.stream().reduce("", String::concat); + System.out.println(result4); + + String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); + System.out.println(result5); + + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result6); + + String result7 = letters.parallelStream().reduce("", String::concat); + System.out.println(result7); + + int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result8); + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java b/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java new file mode 100644 index 0000000000..af4a9276a9 --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java @@ -0,0 +1,52 @@ +package com.baeldung.reduce.benchmarks; + +import com.baeldung.reduce.entities.User; +import java.util.ArrayList; +import java.util.List; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +public class JMHStreamReduceBenchMark { + + private final List userList = createUsers(); + + public static void main(String[] args) throws RunnerException { + + Options options = new OptionsBuilder() + .include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true).shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } + + private List createUsers() { + List users = new ArrayList<>(); + for (int i = 0; i <= 1000000; i++) { + users.add(new User("John" + i, i)); + } + return users; + } + + @Benchmark + public Integer executeReduceOnParallelizedStream() { + return this.userList + .parallelStream() + .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } + + @Benchmark + public Integer executeReduceOnSequentialStream() { + return this.userList + .stream() + .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java b/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java new file mode 100644 index 0000000000..a17c6a02b6 --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java @@ -0,0 +1,25 @@ +package com.baeldung.reduce.entities; + +public class User { + + private final String name; + private final int age; + + public User(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "User{" + "name=" + name + ", age=" + age + '}'; + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java b/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java new file mode 100644 index 0000000000..a7a4b8df29 --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java @@ -0,0 +1,52 @@ +package com.baeldung.reduce.utilities; + +import java.util.List; +import java.util.function.BiFunction; +import java.util.logging.Level; +import java.util.logging.Logger; + +public abstract class NumberUtils { + + private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); + + public static int divideListElements(List values, Integer divider) { + return values.stream() + .reduce(0, (a, b) -> { + try { + return a / divider + b / divider; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return 0; + }); + } + + public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { + return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); + } + + public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { + BiFunction division = (a, b) -> a / b; + return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); + } + + private static int divide(int value, int factor) { + int result = 0; + try { + result = value / factor; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return result; + } + + private static int applyFunction(BiFunction function, int a, int b) { + try { + return function.apply(a, b); + } + catch(Exception e) { + LOGGER.log(Level.INFO, "Exception thrown!"); + } + return 0; + } +} diff --git a/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java b/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java new file mode 100644 index 0000000000..564d614017 --- /dev/null +++ b/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java @@ -0,0 +1,79 @@ +package com.baeldung.reduce.tests; + +import com.baeldung.reduce.entities.User; +import com.baeldung.reduce.utilities.NumberUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class StreamReduceUnitTest { + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, Integer::sum); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (partialString, element) -> partialString + element); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); + assertThat(result).isEqualTo("ABCDE"); + } + + @Test + public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + assertThat(result).isEqualTo(65); + } + + @Test + public void givenStringList_whenReduceWithParallelStream_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.parallelStream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); + } +} From 3fd4fb1cdaa7336358a259134ed5547a6fb57b2c Mon Sep 17 00:00:00 2001 From: Johan Janssen Date: Fri, 8 Mar 2019 15:30:10 +0100 Subject: [PATCH 146/254] Kotlin split list in pairs examples. (#6368) * Kotlin split list in pairs examples. * Renamed some items. --- .../com/baeldung/splitting/SplittingTest.kt | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt new file mode 100644 index 0000000000..a9ddc99992 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt @@ -0,0 +1,99 @@ +package com.baeldung.lambda + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class SplittingTest { + private val evenList = listOf(0, "a", 1, "b", 2, "c"); + + private val unevenList = listOf(0, "a", 1, "b", 2, "c", 3); + + private fun verifyList(resultList: List>) { + assertEquals("[[0, a], [1, b], [2, c]]", resultList.toString()) + } + + private fun verifyPartialList(resultList: List>) { + assertEquals("[[0, a], [1, b], [2, c], [3]]", resultList.toString()) + } + + @Test + fun whenChunked_thenListIsSplit() { + val resultList = evenList.chunked(2) + verifyList(resultList) + } + + @Test + fun whenUnevenChunked_thenListIsSplit() { + val resultList = unevenList.chunked(2) + verifyPartialList(resultList) + } + + @Test + fun whenWindowed_thenListIsSplit() { + val resultList = evenList.windowed(2, 2) + verifyList(resultList) + } + + @Test + fun whenUnevenPartialWindowed_thenListIsSplit() { + val resultList = unevenList.windowed(2, 2, partialWindows = true) + verifyPartialList(resultList) + } + + @Test + fun whenUnevenWindowed_thenListIsSplit() { + val resultList = unevenList.windowed(2, 2, partialWindows = false) + verifyList(resultList) + } + + @Test + fun whenGroupByWithAscendingNumbers_thenListIsSplit() { + val numberList = listOf(1, 2, 3, 4, 5, 6); + val resultList = numberList.groupBy { (it + 1) / 2 } + assertEquals("[[1, 2], [3, 4], [5, 6]]", resultList.values.toString()) + assertEquals("[1, 2, 3]", resultList.keys.toString()) + } + + @Test + fun whenGroupByWithAscendingNumbersUneven_thenListIsSplit() { + val numberList = listOf(1, 2, 3, 4, 5, 6, 7); + val resultList = numberList.groupBy { (it + 1) / 2 }.values + assertEquals("[[1, 2], [3, 4], [5, 6], [7]]", resultList.toString()) + } + + @Test + fun whenGroupByWithRandomNumbers_thenListIsSplitInWrongWay() { + val numberList = listOf(1, 3, 8, 20, 23, 30); + val resultList = numberList.groupBy { (it + 1) / 2 } + assertEquals("[[1], [3], [8], [20], [23], [30]]", resultList.values.toString()) + assertEquals("[1, 2, 4, 10, 12, 15]", resultList.keys.toString()) + } + + @Test + fun whenWithIndexGroupBy_thenListIsSplit() { + val resultList = evenList.withIndex() + .groupBy { it.index / 2 } + .map { it.value.map { it.value } } + verifyList(resultList) + } + + @Test + fun whenWithIndexGroupByUneven_thenListIsSplit() { + val resultList = unevenList.withIndex() + .groupBy { it.index / 2 } + .map { it.value.map { it.value } } + verifyPartialList(resultList) + } + + @Test + fun whenFoldIndexed_thenListIsSplit() { + val resultList = evenList.foldIndexed(ArrayList>(evenList.size / 2)) { index, acc, item -> + if (index % 2 == 0) { + acc.add(ArrayList(2)) + } + acc.last().add(item) + acc + } + verifyList(resultList) + } +} \ No newline at end of file From 4ec4fdb72bfc402fe1c3c1ea9dde8c59eced9f92 Mon Sep 17 00:00:00 2001 From: Wosin Date: Fri, 8 Mar 2019 23:20:37 +0100 Subject: [PATCH 147/254] Bael 43 (#6423) * BAEL-43: Apache Spark with Spring Cloud Data Flow * Replaced functions with lambdas + removed unnecessary type casting. --- .../apache-spark-job/pom.xml | 36 +++++++++++++++++ .../spring/cloud/PiApproximation.java | 39 +++++++++++++++++++ spring-cloud-data-flow/pom.xml | 1 + 3 files changed, 76 insertions(+) create mode 100644 spring-cloud-data-flow/apache-spark-job/pom.xml create mode 100644 spring-cloud-data-flow/apache-spark-job/src/main/java/com/baeldung/spring/cloud/PiApproximation.java diff --git a/spring-cloud-data-flow/apache-spark-job/pom.xml b/spring-cloud-data-flow/apache-spark-job/pom.xml new file mode 100644 index 0000000000..390b7ebdc6 --- /dev/null +++ b/spring-cloud-data-flow/apache-spark-job/pom.xml @@ -0,0 +1,36 @@ + + + + spring-cloud-data-flow + com.baeldung + 0.0.1-SNAPSHOT + + 4.0.0 + + apache-spark-job + + + org.springframework.cloud + spring-cloud-task-core + 2.0.0.RELEASE + + + org.apache.spark + spark-core_2.10 + 1.6.2 + + + log4j + log4j + + + org.slf4j + slf4j-log4j12 + + + + + + \ No newline at end of file diff --git a/spring-cloud-data-flow/apache-spark-job/src/main/java/com/baeldung/spring/cloud/PiApproximation.java b/spring-cloud-data-flow/apache-spark-job/src/main/java/com/baeldung/spring/cloud/PiApproximation.java new file mode 100644 index 0000000000..dfead21728 --- /dev/null +++ b/spring-cloud-data-flow/apache-spark-job/src/main/java/com/baeldung/spring/cloud/PiApproximation.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.cloud; + +import org.apache.spark.SparkConf; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.api.java.function.Function; +import org.apache.spark.api.java.function.Function2; +import org.apache.spark.rdd.RDD; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PiApproximation { + public static void main(String[] args) { + SparkConf conf = new SparkConf().setAppName("BaeldungPIApproximation"); + JavaSparkContext context = new JavaSparkContext(conf); + int slices = args.length >= 1 ? Integer.valueOf(args[0]) : 2; + int n = (100000L * slices) > Integer.MAX_VALUE ? Integer.MAX_VALUE : 100000 * slices; + + List xs = IntStream.rangeClosed(0, n) + .mapToObj(element -> Integer.valueOf(element)) + .collect(Collectors.toList()); + + JavaRDD dataSet = context.parallelize(xs, slices); + + JavaRDD pointsInsideTheCircle = dataSet.map(integer -> { + double x = Math.random() * 2 - 1; + double y = Math.random() * 2 - 1; + return (x*x + y*y ) < 1 ? 1: 0; + }); + + int count = pointsInsideTheCircle.reduce((integer, integer2) -> integer + integer2); + + System.out.println("The pi was estimated as:" + count / n); + + context.stop(); + } +} diff --git a/spring-cloud-data-flow/pom.xml b/spring-cloud-data-flow/pom.xml index daf8ebd2c8..36a780c28d 100644 --- a/spring-cloud-data-flow/pom.xml +++ b/spring-cloud-data-flow/pom.xml @@ -20,6 +20,7 @@ log-sink batch-job etl + apache-spark-job From 2c4d334dc3f11781393d354773fbb681d7c98794 Mon Sep 17 00:00:00 2001 From: soufiane-cheouati <46105138+soufiane-cheouati@users.noreply.github.com> Date: Fri, 8 Mar 2019 22:30:42 +0000 Subject: [PATCH 148/254] Reversing binary tree classes (#6467) * Add files via upload * Add files via upload * Add files via upload --- .../algorithms/reversingtree/TreeNode.java | 42 ++++++++++++ .../reversingtree/TreeReverser.java | 68 +++++++++++++++++++ .../reversingtree/TreeReverserUnitTest.java | 33 +++++++++ 3 files changed, 143 insertions(+) create mode 100644 algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java create mode 100644 algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java create mode 100644 algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java new file mode 100644 index 0000000000..7905b752a9 --- /dev/null +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java @@ -0,0 +1,42 @@ +package com.baeldung.algorithms.reversingtree; + +public class TreeNode { + + private int value; + private TreeNode rightChild; + private TreeNode leftChild; + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public TreeNode getRightChild() { + return rightChild; + } + + public void setRightChild(TreeNode rightChild) { + this.rightChild = rightChild; + } + + public TreeNode getLeftChild() { + return leftChild; + } + + public void setLeftChild(TreeNode leftChild) { + this.leftChild = leftChild; + } + + public TreeNode(int value, TreeNode rightChild, TreeNode leftChild) { + this.value = value; + this.rightChild = rightChild; + this.leftChild = leftChild; + } + + public TreeNode(int value) { + this.value = value; + } +} diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java new file mode 100644 index 0000000000..6d3a9ddd31 --- /dev/null +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java @@ -0,0 +1,68 @@ +package com.baeldung.algorithms.reversingtree; + +import java.util.LinkedList; + +public class TreeReverser { + + public TreeNode createBinaryTree() { + + TreeNode leaf1 = new TreeNode(3); + TreeNode leaf2 = new TreeNode(1); + TreeNode leaf3 = new TreeNode(9); + TreeNode leaf4 = new TreeNode(6); + + TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2); + TreeNode nodeRight = new TreeNode(7, leaf3, leaf4); + + TreeNode root = new TreeNode(4, nodeRight, nodeLeft); + + return root; + } + + public void reverseRecursive(TreeNode treeNode) { + if (treeNode == null) { + return; + } + + TreeNode temp = treeNode.getLeftChild(); + treeNode.setLeftChild(treeNode.getRightChild()); + treeNode.setRightChild(temp); + + reverseRecursive(treeNode.getLeftChild()); + reverseRecursive(treeNode.getRightChild()); + } + + public void reverseIterative(TreeNode treeNode) { + LinkedList queue = new LinkedList(); + + if (treeNode != null) { + queue.add(treeNode); + } + + while (!queue.isEmpty()) { + + TreeNode node = queue.poll(); + if (node.getLeftChild() != null) + queue.add(node.getLeftChild()); + if (node.getRightChild() != null) + queue.add(node.getRightChild()); + + TreeNode temp = node.getLeftChild(); + node.setLeftChild(node.getRightChild()); + node.setRightChild(temp); + } + } + + public String toString(TreeNode root) { + if (root == null) { + return ""; + } + + StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" "); + + buffer.append(toString(root.getLeftChild())); + buffer.append(toString(root.getRightChild())); + + return buffer.toString(); + } +} diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java new file mode 100644 index 0000000000..cbc265fae1 --- /dev/null +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.algorithms.reversingtree; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class TreeReverserUnitTest { + + @Test + public void givenTreeWhenReversingRecursivelyThenReversed() { + TreeReverser reverser = new TreeReverser(); + + TreeNode treeNode = reverser.createBinaryTree(); + + reverser.reverseRecursive(treeNode); + + assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode) + .trim()); + } + + @Test + public void givenTreeWhenReversingIterativelyThenReversed() { + TreeReverser reverser = new TreeReverser(); + + TreeNode treeNode = reverser.createBinaryTree(); + + reverser.reverseIterative(treeNode); + + assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode) + .trim()); + } + +} From 8f54420e95d5012319dae1a27193234722e126b2 Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Sat, 9 Mar 2019 00:50:03 -0300 Subject: [PATCH 149/254] Added sample code for BAEL-1122 (#6468) --- spring-all/pom.xml | 18 +++++++------ .../spring/PropertiesWithJavaConfig.java | 1 + .../main/resources/configForProperties.xml | 2 +- ...lePropertiesJavaConfigIntegrationTest.java | 25 +++++++++++++++++++ ...plePropertiesXmlConfigIntegrationTest.java | 21 ++++++++++++++++ 5 files changed, 59 insertions(+), 8 deletions(-) create mode 100644 spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java create mode 100644 spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 5872fbdac5..8c88efb970 100644 --- a/spring-all/pom.xml +++ b/spring-all/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 spring-all 0.1-SNAPSHOT @@ -47,12 +47,16 @@ org.springframework spring-websocket - - + + org.springframework spring-messaging - - + + + javax.annotation + javax.annotation-api + ${annotation-api.version} + org.springframework @@ -227,13 +231,13 @@ - + org.baeldung.sample.App 5.0.6.RELEASE 1.2.0.RELEASE - + 1.3.2 5.2.5.Final diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java index 08626bb4d2..6589143a94 100644 --- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java +++ b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java @@ -7,6 +7,7 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration @PropertySource("classpath:foo.properties") +@PropertySource("classpath:bar.properties") public class PropertiesWithJavaConfig { public PropertiesWithJavaConfig() { diff --git a/spring-all/src/main/resources/configForProperties.xml b/spring-all/src/main/resources/configForProperties.xml index 0f766665eb..459aea3ec6 100644 --- a/spring-all/src/main/resources/configForProperties.xml +++ b/spring-all/src/main/resources/configForProperties.xml @@ -7,7 +7,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - + diff --git a/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java new file mode 100644 index 0000000000..9cb41c20f7 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java @@ -0,0 +1,25 @@ +package org.baeldung.properties.multiple; + +import org.baeldung.properties.spring.PropertiesWithJavaConfig; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringJUnitConfig(PropertiesWithJavaConfig.class) +public class MultiplePropertiesJavaConfigIntegrationTest { + + @Value("${key.something}") + private String something; + + @Value("${key.something2}") + private String something2; + + + @Test + public void whenReadInjectedValues_thenGetCorrectValues() { + assertThat(something).isEqualTo("val"); + assertThat(something2).isEqualTo("val2"); + } +} diff --git a/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java new file mode 100644 index 0000000000..b4f81f3541 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java @@ -0,0 +1,21 @@ +package org.baeldung.properties.multiple; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringJUnitConfig(locations = "classpath:configForProperties.xml") +public class MultiplePropertiesXmlConfigIntegrationTest { + + @Value("${key.something}") private String something; + + @Value("${key.something2}") private String something2; + + @Test + public void whenReadInjectedValues_thenGetCorrectValues() { + assertThat(something).isEqualTo("val"); + assertThat(something2).isEqualTo("val2"); + } +} From 02fd91ad35810cfe06d8b2e28a740957a8437ad5 Mon Sep 17 00:00:00 2001 From: Ganesh Pagade Date: Sat, 9 Mar 2019 14:59:08 +0530 Subject: [PATCH 150/254] review comments --- .../org/baeldung/gson/entities/MyClass.java | 36 +++++++++++++---- .../gson/advance/GsonAdvanceUnitTest.java | 40 +++++++++++-------- 2 files changed, 51 insertions(+), 25 deletions(-) diff --git a/gson/src/main/java/org/baeldung/gson/entities/MyClass.java b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java index 827ca10cb0..997f4c3f26 100644 --- a/gson/src/main/java/org/baeldung/gson/entities/MyClass.java +++ b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java @@ -1,14 +1,18 @@ package org.baeldung.gson.entities; +import java.util.Objects; + public class MyClass { private int id; - private String[] strings; + private String name; - public MyClass() { - id = 1; - strings = new String[] { "a", "b" }; + public MyClass(int id, String name) { + this.id = id; + this.name = name; } + public MyClass() { } + public int getId() { return id; } @@ -17,11 +21,27 @@ public class MyClass { this.id = id; } - public String[] getStrings() { - return strings; + public String getName() { + return name; } - public void setStrings(String[] strings) { - this.strings = strings; + public void setName(String name) { + this.name = name; + } + + @Override public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MyClass myClass = (MyClass) o; + return id == myClass.id && Objects.equals(name, myClass.name); + } + + @Override public int hashCode() { + + return Objects.hash(id, name); } } diff --git a/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java index 020118aa2b..3bf2afbe4a 100644 --- a/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java +++ b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java @@ -8,6 +8,7 @@ import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.baeldung.gson.entities.Animal; import org.baeldung.gson.entities.Cow; @@ -18,40 +19,42 @@ import org.junit.Test; public class GsonAdvanceUnitTest { - @Test public void givenListOfMyClass_whenSerializing_thenCorrect() { - List list = new ArrayList<>(); - list.add(new MyClass()); - list.add(new MyClass()); + @Test + public void givenListOfMyClass_whenSerializing_thenCorrect() { + List list = Arrays.asList(new MyClass(1, "name1"), new MyClass(2, "name2")); Gson gson = new Gson(); String jsonString = gson.toJson(list); - String expectedString = "[{\"id\":1,\"strings\":[\"a\",\"b\"]},{\"id\":1,\"strings\":[\"a\",\"b\"]}]"; + String expectedString = "[{\"id\":1,\"name\":\"name1\"},{\"id\":2,\"name\":\"name2\"}]"; assertEquals(expectedString, jsonString); } @Test(expected = ClassCastException.class) public void givenJsonString_whenIncorrectDeserializing_thenThrowClassCastException() { - String inputString = "[{\"id\":1,\"strings\":[\"a\",\"b\"]},{\"id\":1,\"strings\":[\"a\",\"b\"]}]"; + String inputString = "[{\"id\":1,\"name\":\"name1\"},{\"id\":2,\"name\":\"name2\"}]"; Gson gson = new Gson(); - List list = gson.fromJson(inputString, ArrayList.class); + List outputList = gson.fromJson(inputString, ArrayList.class); - assertEquals(1, list.get(0).getId()); + assertEquals(1, outputList.get(0).getId()); } - @Test public void givenJsonString_whenDeserializing_thenReturnListOfMyClass() { - String inputString = "[{\"id\":1,\"strings\":[\"a\",\"b\"]},{\"id\":1,\"strings\":[\"a\",\"b\"]}]"; + @Test + public void givenJsonString_whenDeserializing_thenReturnListOfMyClass() { + String inputString = "[{\"id\":1,\"name\":\"name1\"},{\"id\":2,\"name\":\"name2\"}]"; + List inputList = Arrays.asList(new MyClass(1, "name1"), new MyClass(2, "name2")); + Type listOfMyClassObject = new TypeToken>() {}.getType(); Gson gson = new Gson(); - List list = gson.fromJson(inputString, listOfMyClassObject); + List outputList = gson.fromJson(inputString, listOfMyClassObject); - assertEquals(2, list.size()); - assertEquals(1, list.get(0).getId()); + assertEquals(inputList, outputList); } - @Test public void givenPolymorphicList_whenSerializeWithTypeAdapter_thenCorrect() { + @Test + public void givenPolymorphicList_whenSerializeWithTypeAdapter_thenCorrect() { String expectedString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; List inList = new ArrayList<>(); @@ -63,7 +66,8 @@ public class GsonAdvanceUnitTest { assertEquals(expectedString, jsonString); } - @Test public void givenPolymorphicList_whenDeserializeWithTypeAdapter_thenCorrect() { + @Test + public void givenPolymorphicList_whenDeserializeWithTypeAdapter_thenCorrect() { String inputString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; AnimalDeserializer deserializer = new AnimalDeserializer("type"); @@ -79,7 +83,8 @@ public class GsonAdvanceUnitTest { assertTrue(outList.get(0) instanceof Dog); } - @Test public void givenPolymorphicList_whenSerializeWithRuntimeTypeAdapter_thenCorrect() { + @Test + public void givenPolymorphicList_whenSerializeWithRuntimeTypeAdapter_thenCorrect() { String expectedString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; List inList = new ArrayList<>(); @@ -90,7 +95,8 @@ public class GsonAdvanceUnitTest { assertEquals(expectedString, jsonString); } - @Test public void givenPolymorphicList_whenDeserializeWithRuntimeTypeAdapter_thenCorrect() { + @Test + public void givenPolymorphicList_whenDeserializeWithRuntimeTypeAdapter_thenCorrect() { String inputString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; Type listOfAnimals = new TypeToken>() {}.getType(); From 213349420b947a8d749eb4d2a51337bc5b80a870 Mon Sep 17 00:00:00 2001 From: Ganesh Pagade Date: Sat, 9 Mar 2019 15:06:07 +0530 Subject: [PATCH 151/254] review comments --- gson/src/main/java/org/baeldung/gson/entities/MyClass.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/gson/src/main/java/org/baeldung/gson/entities/MyClass.java b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java index 997f4c3f26..4e717e72c3 100644 --- a/gson/src/main/java/org/baeldung/gson/entities/MyClass.java +++ b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java @@ -29,7 +29,8 @@ public class MyClass { this.name = name; } - @Override public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if (this == o) { return true; } @@ -40,7 +41,8 @@ public class MyClass { return id == myClass.id && Objects.equals(name, myClass.name); } - @Override public int hashCode() { + @Override + public int hashCode() { return Objects.hash(id, name); } From c8ee65b1d2a01ba6a45922c42f26b13daa042709 Mon Sep 17 00:00:00 2001 From: TINO Date: Sat, 9 Mar 2019 15:36:20 +0300 Subject: [PATCH 152/254] BAEL - 1060 --- .../baeldung/rxjava/RxJavaHooksUnitTest.java | 329 ++++++++++++++++++ 1 file changed, 329 insertions(+) create mode 100644 rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java new file mode 100644 index 0000000000..e31838448b --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java @@ -0,0 +1,329 @@ +package com.baeldung.rxjava; + +import org.junit.Test; + +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Maybe; +import io.reactivex.Observable; +import io.reactivex.Single; +import io.reactivex.flowables.ConnectableFlowable; +import io.reactivex.observables.ConnectableObservable; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; + +public class RxJavaHooksUnitTest { + + @Test + public void givenCompletable_whenAssembled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnCompletableAssembly(completable -> { + System.out.println("Assembling Completable"); + return completable; + }); + Completable.fromSingle(Single.just(1)); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenCompletable_whenSubscribed_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnCompletableSubscribe((completable, observer) -> { + System.out.println("Subscribing to Completable"); + return observer; + }); + + Completable.fromSingle(Single.just(1)) + .test(true); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenObservable_whenAssembled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnObservableAssembly(observable -> { + System.out.println("Assembling Observable"); + return observable; + }); + + Observable.range(1, 10); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenObservable_whenSubscribed_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnObservableSubscribe((observable, observer) -> { + System.out.println("Suscribing to Observable"); + return observer; + }); + + Observable.range(1, 10) + .test(true); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenConnectableObservable_whenAssembled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnConnectableObservableAssembly(connectableObservable -> { + System.out.println("Assembling ConnectableObservable"); + return connectableObservable; + }); + + ConnectableObservable.range(1, 10) + .publish() + .connect(); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenFlowable_whenAssembled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnFlowableAssembly(flowable -> { + System.out.println("Assembling Flowable"); + return flowable; + }); + + Flowable.range(1, 10); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenFlowable_whenSubscribed_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnFlowableSubscribe((flowable, observer) -> { + System.out.println("Suscribing to Flowable"); + return observer; + }); + + Flowable.range(1, 10) + .test(); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenConnectableFlowable_whenAssembled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnConnectableFlowableAssembly(connectableFlowable -> { + System.out.println("Assembling ConnectableFlowable"); + return connectableFlowable; + }); + + ConnectableFlowable.range(1, 10) + .publish() + .connect(); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenParallel_whenAssembled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnParallelAssembly(parallelFlowable -> { + System.out.println("Assembling ParallelFlowable"); + return parallelFlowable; + }); + + Flowable.range(1, 10) + .parallel(); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenMaybe_whenAssembled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnMaybeAssembly(maybe -> { + System.out.println("Assembling Maybe"); + return maybe; + }); + + Maybe.just(1); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenMaybe_whenSubscribed_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnMaybeSubscribe((maybe, observer) -> { + System.out.println("Suscribing to Maybe"); + return observer; + }); + + Maybe.just(1) + .test(); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenSingle_whenAssembled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setOnSingleAssembly(single -> { + System.out.println("Assembling Single"); + return single; + }); + + Single.just(1); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenSingle_whenSubscribed_shouldExecuteTheHook() { + + try { + RxJavaPlugins.setOnSingleSubscribe((single, observer) -> { + System.out.println("Suscribing to Single"); + return observer; + }); + + Single.just(1) + .test(); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenAnyScheduler_whenCalled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setScheduleHandler((runnable) -> { + System.out.println("Executing Scheduler"); + return runnable; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenComputationScheduler_whenCalled_shouldExecuteTheHooks() { + try { + RxJavaPlugins.setInitComputationSchedulerHandler((scheduler) -> { + System.out.println("Initializing Computation Scheduler"); + return scheduler.call(); + }); + RxJavaPlugins.setComputationSchedulerHandler((scheduler) -> { + System.out.println("Executing Computation Scheduler"); + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() { + try { + RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { + System.out.println("Initializing IO Scheduler"); + return scheduler.call(); + }); + + RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { + System.out.println("Executing IO Scheduler"); + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.io()) + .test(); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() { + try { + RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { + System.out.println("Initializing newThread Scheduler"); + return scheduler.call(); + }); + + RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { + System.out.println("Executing newThread Scheduler"); + return scheduler; + }); + + Observable.range(1, 15) + .map(v -> v * 2) + .subscribeOn(Schedulers.newThread()) + .test(); + + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenSingleScheduler_whenCalled_shouldExecuteTheHooks() { + try { + RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { + System.out.println("Initializing Single Scheduler"); + return scheduler.call(); + }); + + RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { + System.out.println("Executing Single Scheduler"); + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void givenObservable_whenError_shouldExecuteTheHook() { + RxJavaPlugins.setErrorHandler(throwable -> { + System.out.println("Handling error" + throwable.getCause()); + }); + + Observable.error(new IllegalStateException()) + .subscribe(); + } +} From 1f933b8f8fd0d172aa4f0df099d86446955c01a4 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 9 Mar 2019 18:26:45 +0530 Subject: [PATCH 153/254] BAEL-10957 Fix Jhipster Module Tests and Module Renaming -Added hibernate-java8 dependency to fix mapping of Java8 Date, Time types to database types --- jhipster/jhipster-monolithic/pom.xml | 66 ++++++++++++---------------- 1 file changed, 29 insertions(+), 37 deletions(-) diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index 12dead99df..3e98298f56 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -3,7 +3,7 @@ 4.0.0 jhipster-monolithic war - jhipster-monolithic + jhipster-monolithic JHipster Monolithic Application @@ -87,7 +87,7 @@ io.dropwizard.metrics metrics-annotation - + io.dropwizard.metrics metrics-core @@ -95,15 +95,15 @@ io.dropwizard.metrics metrics-json - + io.dropwizard.metrics metrics-jvm - + io.dropwizard.metrics metrics-servlet - + io.dropwizard.metrics metrics-servlets @@ -201,6 +201,10 @@ org.hibernate hibernate-validator + + org.hibernate + hibernate-java8 + org.liquibase liquibase-core @@ -297,8 +301,8 @@ spring-boot:run - + org.eclipse.m2e lifecycle-mapping @@ -340,27 +344,11 @@ - + com.spotify docker-maven-plugin @@ -387,7 +375,8 @@ target/gatling/results src/test/gatling/bodies src/test/gatling/simulations - + true @@ -751,8 +740,9 @@ - cc @@ -868,7 +858,8 @@ - + IDE @@ -930,15 +921,16 @@ S3437,UndocumentedApi,BoldAndItalicTagsCheck - + src/main/webapp/app/**/*.* Web:BoldAndItalicTagsCheck - + src/main/java/**/* squid:S3437 - + src/main/java/**/* squid:UndocumentedApi From 3d5e52cde0a9c876eb38bdd9b5d19dff978f3f43 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 9 Mar 2019 20:08:17 +0530 Subject: [PATCH 154/254] [BAEL-12185] - Removed copied classes from other repositor --- .../deserialization/jacksoninject/Author.java | 26 ------- .../jsonanysetter/Inventory.java | 14 +--- .../deserialization/jsoncreator/Author.java | 27 ------- .../jsondeserialize/Author.java | 24 ------ .../deserialization/jsondeserialize/Book.java | 39 ++++++++-- .../deserialization/jsondeserialize/Item.java | 62 --------------- .../deserialization/jsonsetter/Author.java | 37 --------- .../com/baeldung/jackson/domain/Author.java | 27 ------- .../com/baeldung/jackson/domain/Book.java | 48 ------------ .../com/baeldung/jackson/domain/Course.java | 73 ----------------- .../com/baeldung/jackson/domain/Customer.java | 24 ------ .../baeldung/jackson/domain/Inventory.java | 29 ------- .../com/baeldung/jackson/domain/Item.java | 60 -------------- .../com/baeldung/jackson/domain/Order.java | 50 ------------ .../com/baeldung/jackson/domain/Person.java | 21 +---- .../jackson/inclusion/jsonignore/Author.java | 29 ------- .../jackson/inclusion/jsonignore/Person.java | 48 ------------ .../jsonignoreproperties/Course.java | 78 ------------------- .../jackson/inclusion/jsoninclude/Author.java | 34 -------- .../jackson/miscellaneous/custom/Course.java | 76 ------------------ .../custom/CustomCourseAnnotation.java | 20 ----- .../jackson/miscellaneous/custom/Item.java | 63 --------------- .../jackson/miscellaneous/disable/Author.java | 36 --------- .../jackson/miscellaneous/mixin/Author.java | 30 ------- .../miscellaneous/mixin/IgnoreListMixIn.java | 13 ---- .../jsonanygetter/Inventory.java | 43 ---------- .../serialization/jsongetter/Author.java | 32 -------- .../jsonpropertyorder/Author.java | 31 -------- .../jsonpropertyorder/Person.java | 42 ---------- .../serialization/jsonrawvalue/Customer.java | 28 ------- .../serialization/jsonrootname/Author.java | 32 -------- .../serialization/jsonserialize/Author.java | 29 ------- .../serialization/jsonserialize/Book.java | 52 ------------- .../jsonserialize/CustomDateSerializer.java | 34 -------- .../serialization/jsonserialize/Item.java | 62 --------------- .../serialization/jsonvalue/Course.java | 78 ------------------- .../jacksoninject/JacksonInjectUnitTest.java | 46 ----------- .../jsoncreator/JsonCreatorUnitTest.java | 41 ---------- .../JsonDeserializeUnitTest.java | 2 +- .../jsonsetter/JsonSetterUnitTest.java | 35 --------- .../jackson/general/jsonfilter/Author.java | 32 -------- .../jsonfilter/JsonFilterUnitTest.java | 42 ---------- .../jackson/general/jsonformat/Book.java | 54 ------------- .../jsonformat/JsonFormatUnitTest.java | 63 --------------- .../jackson/general/jsonproperty/Author.java | 29 ------- .../jackson/general/jsonproperty/Book.java | 61 --------------- .../jackson/general/jsonproperty/Item.java | 62 --------------- .../jsonproperty/JsonPropertyUnitTest.java | 70 ----------------- .../jsonignore/JsonIgnoreUnitTest.java | 41 ---------- .../JsonIgnorePropertiesUnitTest.java | 52 ------------- .../jsoninclude/JsonIncludeUnitTest.java | 40 ---------- .../miscellaneous/custom/CustomUnitTest.java | 51 ------------ .../disable/DisableUnitTest.java | 58 -------------- .../miscellaneous/mixin/MixInUnitTest.java | 58 -------------- .../jsonanygetter/JsonAnyGetterUnitTest.java | 49 ------------ .../jsongetter/JsonGetterUnitTest.java | 40 ---------- .../JsonPropertyOrderUnitTest.java | 42 ---------- .../jsonrawvalue/JsonRawValueUnitTest.java | 40 ---------- .../jsonrootname/JsonRootNameUnitTest.java | 46 ----------- .../jsonserialize/JsonSerializeUnitTest.java | 58 -------------- .../jsonvalue/JsonValueUnitTest.java | 27 ------- .../test/JacksonAnnotationUnitTest.java | 27 ------- 62 files changed, 40 insertions(+), 2577 deletions(-) delete mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/domain/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/domain/Book.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/domain/Course.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/domain/Customer.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/domain/Inventory.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/domain/Item.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/domain/Order.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/inclusion/jsoninclude/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/IgnoreListMixIn.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonanygetter/Inventory.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Person.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonrawvalue/Customer.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Author.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/Author.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Author.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Book.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignore/JsonIgnoreUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoreproperties/JsonIgnorePropertiesUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/miscellaneous/custom/CustomUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/miscellaneous/disable/DisableUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/miscellaneous/mixin/MixInUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/serialization/jsonanygetter/JsonAnyGetterUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/serialization/jsongetter/JsonGetterUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/serialization/jsonpropertyorder/JsonPropertyOrderUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/serialization/jsonrootname/JsonRootNameUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/serialization/jsonserialize/JsonSerializeUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/serialization/jsonvalue/JsonValueUnitTest.java diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java deleted file mode 100644 index db8b594509..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.jackson.deserialization.jacksoninject; - -import com.baeldung.jackson.domain.Item; - -import java.util.ArrayList; -import java.util.List; - -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author() { - } - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java index c4daf68bd6..d9748e2997 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java @@ -1,24 +1,14 @@ package com.baeldung.jackson.deserialization.jsonanysetter; -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; - import java.util.HashMap; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnySetter; + public class Inventory { - private Map stock = new HashMap<>(); - private Map countryDeliveryCost = new HashMap<>(); - @JsonIgnore - public Map getStock() { - return stock; - } - public Map getCountryDeliveryCost() { return countryDeliveryCost; } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java deleted file mode 100644 index d48c95b255..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.jackson.deserialization.jsoncreator; - -import com.baeldung.jackson.domain.Person; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.ArrayList; -import java.util.List; - -public class Author extends Person { - - List items = new ArrayList<>(); - - @JsonCreator - public Author(@JsonProperty("christianName") String firstName, @JsonProperty("surname") String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Author.java deleted file mode 100644 index 62e108facb..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Author.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.jackson.deserialization.jsondeserialize; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; - -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java index dc0d0ee623..1e411da64e 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java @@ -1,12 +1,16 @@ package com.baeldung.jackson.deserialization.jsondeserialize; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - import java.math.BigDecimal; import java.util.Date; +import java.util.UUID; -public class Book extends Item { +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +public class Book { + + private UUID id; + private String title; + private float price; private String ISBN; @JsonDeserialize(using = CustomDateDeserializer.class) @@ -16,8 +20,9 @@ public class Book extends Item { public Book() { } - public Book(String title, Author author) { - super(title, author); + public Book(String title) { + this.id = UUID.randomUUID(); + this.title = title; } public String getISBN() { @@ -43,4 +48,28 @@ public class Book extends Item { public void setPages(BigDecimal pages) { this.pages = pages; } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java deleted file mode 100644 index fc27a586ac..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.jackson.deserialization.jsondeserialize; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java deleted file mode 100644 index 3f9ae70a88..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.jackson.deserialization.jsonsetter; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonSetter; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author() { - } - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - @JsonIgnore - public List getItems() { - return items; - } - - @JsonSetter("publications") - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Author.java b/jackson/src/main/java/com/baeldung/jackson/domain/Author.java deleted file mode 100644 index 9000c00f21..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Author.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java b/jackson/src/main/java/com/baeldung/jackson/domain/Book.java deleted file mode 100644 index a5963e33ba..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Book extends Item { - - private String ISBN; - private Date published; - private BigDecimal pages; - - public Book() { - } - - public Book(String title, Author author) { - super(title, author); - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public Date getPublished() { - return published; - } - - public void setPublished(Date published) { - this.published = published; - } - - public BigDecimal getPages() { - return pages; - } - - public void setPages(BigDecimal pages) { - this.pages = pages; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java b/jackson/src/main/java/com/baeldung/jackson/domain/Course.java deleted file mode 100644 index 672b0bc250..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Customer.java b/jackson/src/main/java/com/baeldung/jackson/domain/Customer.java deleted file mode 100644 index 1e03ff9a13..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Customer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.jackson.domain; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Customer extends Person { - - private String configuration; - - public Customer(String firstName, String lastName) { - super(firstName, lastName); - } - - public String getConfiguration() { - return configuration; - } - - public void setConfiguration(String configuration) { - this.configuration = configuration; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Inventory.java b/jackson/src/main/java/com/baeldung/jackson/domain/Inventory.java deleted file mode 100644 index 41b7dc51da..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Inventory.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.HashMap; -import java.util.Map; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Inventory { - - private Map stock; - - private Map countryDeliveryCost = new HashMap<>(); - - public Map getStock() { - return stock; - } - - public void setStock(Map stock) { - this.stock = stock; - } - - public Map getCountryDeliveryCost() { - return countryDeliveryCost; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java b/jackson/src/main/java/com/baeldung/jackson/domain/Item.java deleted file mode 100644 index d9d1350a8e..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Order.java b/jackson/src/main/java/com/baeldung/jackson/domain/Order.java deleted file mode 100644 index 91f87f74df..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Order.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - private UUID id; - private Type type; - private int internalAudit; - - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java b/jackson/src/main/java/com/baeldung/jackson/domain/Person.java index 785efff755..f11ba41113 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Person.java @@ -1,24 +1,12 @@ package com.baeldung.jackson.domain; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ public class Person { - private UUID id; private String firstName; private String lastName; - - public Person() { - } - + public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); + super(); this.firstName = firstName; this.lastName = lastName; } @@ -38,8 +26,5 @@ public class Person { public void setLastName(String lastName) { this.lastName = lastName; } - - public UUID getId() { - return id; - } } + diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Author.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Author.java deleted file mode 100644 index a7801493bf..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Author.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignore; - -import com.baeldung.jackson.domain.Item; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java deleted file mode 100644 index 0037d83148..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignore; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Person { - - @JsonIgnore - private UUID id; - private String firstName; - private String lastName; - - public Person() { - } - - public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); - this.firstName = firstName; - this.lastName = lastName; - } - - 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 UUID getId() { - return id; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java deleted file mode 100644 index 70b4dd9842..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignoreproperties; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonIgnoreProperties({ "medium" }) -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsoninclude/Author.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsoninclude/Author.java deleted file mode 100644 index 30cb2735c2..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsoninclude/Author.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.jackson.inclusion.jsoninclude; - -import com.baeldung.jackson.domain.Person; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonInclude; - -import java.util.ArrayList; -import java.util.List; - -import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonInclude(NON_NULL) -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java deleted file mode 100644 index a44492b9f7..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.jackson.miscellaneous.custom; - -import com.baeldung.jackson.domain.Author; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@CustomCourseAnnotation -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java deleted file mode 100644 index d7f72ca6ec..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.jackson.miscellaneous.custom; - -import com.fasterxml.jackson.annotation.*; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@Retention(RetentionPolicy.RUNTIME) -@JacksonAnnotationsInside -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ "title", "price", "id", "duration", "authors", "level" }) -@JsonIgnoreProperties({ "prerequisite" }) -public @interface CustomCourseAnnotation { -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java deleted file mode 100644 index 6625283dec..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.jackson.miscellaneous.custom; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java deleted file mode 100644 index 0638e32925..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.jackson.miscellaneous.disable; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ "lastName", "items", "firstName", "id" }) -public class Author extends Person { - - @JsonIgnore - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/Author.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/Author.java deleted file mode 100644 index 26e3e4b647..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/Author.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.jackson.miscellaneous.mixin; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/IgnoreListMixIn.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/IgnoreListMixIn.java deleted file mode 100644 index 418c09c251..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/IgnoreListMixIn.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.jackson.miscellaneous.mixin; - -import com.fasterxml.jackson.annotation.JsonIgnoreType; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonIgnoreType -public class IgnoreListMixIn { -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonanygetter/Inventory.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonanygetter/Inventory.java deleted file mode 100644 index 52f586d93b..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonanygetter/Inventory.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.jackson.serialization.jsonanygetter; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.HashMap; -import java.util.Map; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Inventory { - - private String location; - - private Map stock = new HashMap<>(); - - private Map countryDeliveryCost = new HashMap<>(); - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - @JsonIgnore - public Map getStock() { - return stock; - } - - @JsonAnyGetter - public Map getCountryDeliveryCost() { - return countryDeliveryCost; - } - -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java deleted file mode 100644 index 8d89fefce7..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.jackson.serialization.jsongetter; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonGetter; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - @JsonGetter("publications") - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java deleted file mode 100644 index dadf893cf9..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.jackson.serialization.jsonpropertyorder; - -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonPropertyOrder({ "items", "firstName", "lastName", "id" }) -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Person.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Person.java deleted file mode 100644 index 519e48aada..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Person.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.jackson.serialization.jsonpropertyorder; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Person { - - private UUID id; - private String firstName; - private String lastName; - - public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); - this.firstName = firstName; - this.lastName = lastName; - } - - 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 UUID getId() { - return id; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrawvalue/Customer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrawvalue/Customer.java deleted file mode 100644 index f19c5314d2..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrawvalue/Customer.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.jackson.serialization.jsonrawvalue; - -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonRawValue; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Customer extends Person { - - @JsonRawValue - private String configuration; - - public Customer(String firstName, String lastName) { - super(firstName, lastName); - } - - public String getConfiguration() { - return configuration; - } - - public void setConfiguration(String configuration) { - this.configuration = configuration; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java deleted file mode 100644 index b6dd75da54..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.jackson.serialization.jsonrootname; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonRootName; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonRootName(value = "writer", namespace = "book") -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Author.java deleted file mode 100644 index 5a6e90d712..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Author.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java deleted file mode 100644 index 0ecc4e72ce..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Book extends Item { - - private String ISBN; - - @JsonSerialize(using = CustomDateSerializer.class) - private Date published; - private BigDecimal pages; - - public Book() { - } - - public Book(String title, Author author) { - super(title, author); - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public Date getPublished() { - return published; - } - - public void setPublished(Date published) { - this.published = published; - } - - public BigDecimal getPages() { - return pages; - } - - public void setPages(BigDecimal pages) { - this.pages = pages; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java deleted file mode 100644 index 131f4f3695..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class CustomDateSerializer extends StdSerializer { - - private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - - public CustomDateSerializer() { - this(null); - } - - public CustomDateSerializer(Class t) { - super(t); - } - - @Override - public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException { - gen.writeString(formatter.format(value)); - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java deleted file mode 100644 index 56cfa85793..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java deleted file mode 100644 index a3fdc2d8eb..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baeldung.jackson.serialization.jsonvalue; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonValue; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - @JsonValue - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java deleted file mode 100644 index 96dbff6f3c..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.jackson.deserialization.jacksoninject; - -import com.fasterxml.jackson.databind.InjectableValues; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; -import java.util.UUID; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JacksonInjectUnitTest { - - @Test - public void whenDeserializingUsingJacksonInject_thenCorrect() throws IOException { - - UUID id = UUID.fromString("9616dc8c-bad3-11e6-a4a6-cec0c932ce01"); - - // arrange - String authorJson = "{\"firstName\": \"Alex\", \"lastName\": \"Theedom\"}"; - - // act - InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id); - Author author = new ObjectMapper().reader(inject) - .forType(Author.class) - .readValue(authorJson); - - // assert - assertThat(author.getId()).isEqualTo(id); - - /* - { - "firstName": "Alex", - "lastName": "Theedom", - "publications": [] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java deleted file mode 100644 index cc245dab66..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.jackson.deserialization.jsoncreator; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonCreatorUnitTest { - - @Test - public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { - - // arrange - String authorJson = "{" + " \"christianName\": \"Alex\"," + " \"surname\": \"Theedom\"" + "}"; - - // act - final Author author = new ObjectMapper().readerFor(Author.class) - .readValue(authorJson); - - // assert - assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName()); - assertThat(from(authorJson).getString("surname")).isEqualTo(author.getLastName()); - - /* - { - "christianName": "Alex", - "surname": "Theedom" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java index 1bcde998d6..a7934d96cf 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java @@ -21,7 +21,7 @@ public class JsonDeserializeUnitTest { public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException { // arrange - String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"authors\":[{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"firstName\":\"Joshua\",\"lastName\":\"Bloch\"}],\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}"; + String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}"; // act Book book = new ObjectMapper().readerFor(Book.class) diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java deleted file mode 100644 index 4379fe376c..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.jackson.deserialization.jsonsetter; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonSetterUnitTest { - - @Test - public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException { - - // arrange - String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}"; - - // act - Author author = new ObjectMapper().readerFor(Author.class) - .readValue(json); - - // assert - assertThat(from(json).getList("publications") - .size()).isEqualTo(author.getItems() - .size()); - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/Author.java deleted file mode 100644 index 3d5a9c907c..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/Author.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.jackson.general.jsonfilter; - -import com.baeldung.jackson.domain.Person; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonFilter; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonFilter("authorFilter") -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java deleted file mode 100644 index 6fcc57faa7..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.jackson.general.jsonfilter; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ser.FilterProvider; -import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; -import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonFilterUnitTest { - - @Test - public void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - FilterProvider filters = new SimpleFilterProvider().addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); - - // act - String result = new ObjectMapper().writer(filters) - .writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNull(); - - /* - { - "lastName": "Theedom" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java deleted file mode 100644 index e2eb4aa48a..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.jackson.general.jsonformat; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonFormat; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Book extends Item { - - private String ISBN; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss") - private Date published; - private BigDecimal pages; - - public Book() { - } - - public Book(String title, Author author) { - super(title, author); - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public Date getPublished() { - return published; - } - - public void setPublished(Date published) { - this.published = published; - } - - public BigDecimal getPages() { - return pages; - } - - public void setPages(BigDecimal pages) { - this.pages = pages; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java deleted file mode 100644 index 1fe217cef6..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.jackson.general.jsonformat; - -import com.baeldung.jackson.domain.Author; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonFormatUnitTest { - - @Test - public void whenSerializingUsingJsonFormat_thenCorrect() throws JsonProcessingException, ParseException { - - // arrange - SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - - String toParse = "20-12-2014 14:30:00"; - Date date = df.parse(toParse); - - Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); - book.setPublished(date); - - // act - String result = new ObjectMapper().writeValueAsString(book); - - // assert - assertThat(from(result).getString("published")).isEqualTo(toParse); - - /* - { - "id": "762b39be-fd5b-489e-8688-aeb3b9bbf019", - "title": "Design Patterns: Elements of Reusable Object-oriented Software", - "authors": [ - { - "id": "6941b780-0f54-4259-adcb-85523c8f25f4", - "firstName": "The", - "lastName": "GoF", - "items": [] - } - ], - "price": 0, - "published": "20-12-2014 02:30:00", - "pages": null, - "isbn": null - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Author.java deleted file mode 100644 index 01552df729..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Author.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jackson.general.jsonproperty; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Book.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Book.java deleted file mode 100644 index 100d9634f5..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Book.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.jackson.general.jsonproperty; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Book extends Item { - - private String ISBN; - private Date published; - private BigDecimal pages; - private String binding; - - public Book() { - } - - public Book(String title, Author author) { - super(title, author); - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public Date getPublished() { - return published; - } - - public void setPublished(Date published) { - this.published = published; - } - - public BigDecimal getPages() { - return pages; - } - - public void setPages(BigDecimal pages) { - this.pages = pages; - } - - @JsonProperty("binding") - public String coverBinding() { - return binding; - } - - @JsonProperty("binding") - public void configureBinding(String binding) { - this.binding = binding; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java deleted file mode 100644 index d7ee430d51..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.jackson.general.jsonproperty; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java deleted file mode 100644 index 0b88e7fc47..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.jackson.general.jsonproperty; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonPropertyUnitTest { - - @Test - public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException { - - // arrange - Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); - book.configureBinding("Hardback"); - - // act - String result = new ObjectMapper().writeValueAsString(book); - - // assert - assertThat(from(result).getString("binding")).isEqualTo("Hardback"); - - /* - { - "id": "cd941587-d1ae-4c2a-9a36-29533bf50411", - "title": "Design Patterns: Elements of Reusable Object-oriented Software", - "authors": [ - { - "id": "c8e26318-2f5b-4fa2-9fdc-6e99be021fca", - "firstName": "The", - "lastName": "GoF", - "items": [] - } - ], - "price": 0, - "published": null, - "pages": null, - "isbn": null, - "binding": "Hardback" - } - */ - - } - - @Test - public void whenDeserializingUsingJsonProperty_thenCorrect() throws IOException { - - // arrange - String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}"; - - // act - Book book = new ObjectMapper().readerFor(Book.class) - .readValue(result); - - // assert - assertThat(book.coverBinding()).isEqualTo("Hardback"); - - } - -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignore/JsonIgnoreUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignore/JsonIgnoreUnitTest.java deleted file mode 100644 index 89e3c15f04..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignore/JsonIgnoreUnitTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignore; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIgnoreUnitTest { - - @Test - public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getString("firstName")).isEqualTo("Alex"); - assertThat(from(result).getString("lastName")).isEqualTo("Theedom"); - assertThat(from(result).getString("id")).isNull(); - - /* - { - "firstName": "Alex", - "lastName": "Theedom", - "items": [] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoreproperties/JsonIgnorePropertiesUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoreproperties/JsonIgnorePropertiesUnitTest.java deleted file mode 100644 index be20d242c9..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoreproperties/JsonIgnorePropertiesUnitTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignoreproperties; - -import com.baeldung.jackson.domain.Author; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIgnorePropertiesUnitTest { - - @Test - public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonProcessingException { - - // arrange - Course course = new Course("Spring Security", new Author("Eugen", "Paraschiv")); - course.setMedium(Course.Medium.ONLINE); - - // act - String result = new ObjectMapper().writeValueAsString(course); - - // assert - assertThat(from(result).getString("medium")).isNull(); - - /* - { - "id": "ef0c8d2b-b088-409e-905c-95ac88dc0ed0", - "title": "Spring Security", - "authors": [ - { - "id": "47a4f498-b0f3-4daf-909f-d2c35a0fe3c2", - "firstName": "Eugen", - "lastName": "Paraschiv", - "items": [] - } - ], - "price": 0, - "duration": 0, - "level": null, - "prerequisite": null - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java deleted file mode 100644 index ca4c4b751a..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.jackson.inclusion.jsoninclude; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIncludeUnitTest { - - @Test - public void whenSerializingUsingJsonInclude_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", null); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getString("firstName")).isEqualTo("Alex"); - assertThat(result).doesNotContain("lastName"); - - /* - { - "id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd", - "firstName": "Alex", - "items": [] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/custom/CustomUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/miscellaneous/custom/CustomUnitTest.java deleted file mode 100644 index 8f90c02875..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/custom/CustomUnitTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.jackson.miscellaneous.custom; - -import com.baeldung.jackson.domain.Author; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class CustomUnitTest { - - @Test - public void whenSerializingUsingCustom_thenCorrect() throws JsonProcessingException { - - // arrange - Course course = new Course("Spring Security", new Author("Eugen", "Paraschiv")); - course.setMedium(Course.Medium.ONLINE); - - // act - String result = new ObjectMapper().writeValueAsString(course); - - // assert - assertThat(from(result).getString("title")).isEqualTo("Spring Security"); - - /* - { - "title": "Spring Security", - "price": 0, - "id": "7dfd4db9-1175-432f-a53b-687423f7bb9b", - "duration": 0, - "authors": [ - { - "id": "da0738f6-033c-4974-8d87-92820e5ccf27", - "firstName": "Eugen", - "lastName": "Paraschiv", - "items": [] - } - ], - "medium": "ONLINE" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/disable/DisableUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/miscellaneous/disable/DisableUnitTest.java deleted file mode 100644 index f9bc14291e..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/disable/DisableUnitTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.jackson.miscellaneous.disable; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class DisableUnitTest { - - @Test - public void whenSerializingUsingDisable_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNull(); - - /* - { - "lastName": "Theedom", - "firstName": "Alex", - "id": "de4afbb4-b24d-45c8-bb00-fd6b9acb42f1" - } - */ - - // act - mapper = new ObjectMapper(); - mapper.disable(MapperFeature.USE_ANNOTATIONS); - result = mapper.writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNotNull(); - - /* - { - "id": "81e6ed72-6b27-4fe9-a36f-e3171c5b55ef", - "firstName": "Alex", - "lastName": "Theedom", - "items": [] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/mixin/MixInUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/miscellaneous/mixin/MixInUnitTest.java deleted file mode 100644 index 732cda58d0..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/mixin/MixInUnitTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.jackson.miscellaneous.mixin; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.List; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class MixInUnitTest { - - @Test - public void whenSerializingUsingMixIn_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNotNull(); - - /* - { - "id": "f848b076-00a4-444a-a50b-328595dd9bf5", - "firstName": "Alex", - "lastName": "Theedom", - "items": [] - } - */ - - ObjectMapper mapper = new ObjectMapper(); - mapper.addMixIn(List.class, IgnoreListMixIn.class); - - result = mapper.writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNull(); - - /* - { - "id": "9ffefb7d-e56f-447c-9009-e92e142f8347", - "firstName": "Alex", - "lastName": "Theedom" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonanygetter/JsonAnyGetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonanygetter/JsonAnyGetterUnitTest.java deleted file mode 100644 index 7a786e0bd6..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonanygetter/JsonAnyGetterUnitTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.jackson.serialization.jsonanygetter; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.Map; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonAnyGetterUnitTest { - - @Test - public void whenSerializingUsingJsonAnyGetter_thenCorrect() throws JsonProcessingException { - - // arrange - Inventory inventory = new Inventory(); - Map countryDeliveryCost = inventory.getCountryDeliveryCost(); - inventory.setLocation("France"); - - countryDeliveryCost.put("USA", 10.00f); - countryDeliveryCost.put("UK", 15.00f); - - // act - String result = new ObjectMapper().writeValueAsString(inventory); - - // assert - assertThat(from(result).getString("location")).isEqualTo("France"); - assertThat(from(result).getFloat("USA")).isEqualTo(10.00f); - assertThat(from(result).getFloat("UK")).isEqualTo(15.00f); - - /* - { - "location": "France", - "USA": 10, - "UK": 15 - } - */ - - } - -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsongetter/JsonGetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsongetter/JsonGetterUnitTest.java deleted file mode 100644 index 4bc9c51e83..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsongetter/JsonGetterUnitTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.jackson.serialization.jsongetter; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonGetterUnitTest { - - @Test - public void whenSerializingUsingJsonGetter_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getList("publications")).isNotNull(); - assertThat(from(result).getList("items")).isNull(); - - /* - { - "firstName": "Alex", - "lastName": "Theedom", - "publications": [] - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonpropertyorder/JsonPropertyOrderUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonpropertyorder/JsonPropertyOrderUnitTest.java deleted file mode 100644 index 77ef85ed73..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonpropertyorder/JsonPropertyOrderUnitTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.jackson.serialization.jsonpropertyorder; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; -import static org.hamcrest.MatcherAssert.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonPropertyOrderUnitTest { - - @Test - public void whenSerializingUsingJsonPropertyOrder_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(result, matchesJsonSchemaInClasspath("author-jsonpropertyorder-schema.json")); - - // NOTE: property order is not enforced by the JSON specification. - - /* - { - "items": [], - "firstName": "Alex", - "lastName": "Theedom", - "id": "fd277638-9b6e-49f7-81c1-bc52f165245b" - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java deleted file mode 100644 index f0f0913aee..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.jackson.serialization.jsonrawvalue; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonRawValueUnitTest { - - @Test - public void whenSerializingUsingJsonRawValue_thenCorrect() throws JsonProcessingException { - - // arrange - String customerConfig = "{\"colour\":\"red\",\"device\":\"mobile\",\"orientation\":\"landscape\"}"; - Customer customer = new Customer("Alex", "Theedom"); - customer.setConfiguration("{\"colour\":\"red\",\"device\":\"mobile\",\"orientation\":\"landscape\"}"); - - // act - String result = new ObjectMapper().writeValueAsString(customer); - - // assert - assertThat(result.contains(customerConfig)); - - /* - { - "firstName": "Alex", - "lastName": "Theedom", - "publications": [] - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrootname/JsonRootNameUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrootname/JsonRootNameUnitTest.java deleted file mode 100644 index cb54e63079..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrootname/JsonRootNameUnitTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.jackson.serialization.jsonrootname; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonRootNameUnitTest { - - @Test - public void whenSerializingUsingJsonRootName_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - ObjectMapper mapper = new ObjectMapper(); - mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); - String result = mapper.writeValueAsString(author); - - // assert - assertThat(from(result).getString("writer.firstName")).isEqualTo("Alex"); - assertThat(from(result).getString("author.firstName")).isNull(); - - /* - { - "writer": { - "id": "0f50dca6-3dd7-4801-a334-fd1614276389", - "firstName": "Alex", - "lastName": "Theedom", - "items": [] - } - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonserialize/JsonSerializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonserialize/JsonSerializeUnitTest.java deleted file mode 100644 index cca018e78d..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonserialize/JsonSerializeUnitTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.text.ParseException; -import java.text.SimpleDateFormat; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonSerializeUnitTest { - - @Test - public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException { - - // arrange - Author joshuaBloch = new Author("Joshua", "Bloch"); - Book book = new Book("Effective Java", joshuaBloch); - - SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - String toParse = "25-12-2017 13:30:25"; - book.setPublished(df.parse(toParse)); - - // act - String result = new ObjectMapper().writeValueAsString(book); - - // assert - assertThat(from(result).getString("published")).isEqualTo(toParse); - - /* - { - "id": "957c43f2-fa2e-42f9-bf75-6e3d5bb6960a", - "title": "Effective Java", - "authors": [ - { - "id": "9bcd817d-0141-42e6-8f04-e5aaab0980b6", - "firstName": "Joshua", - "lastName": "Bloch", - "items": [] - } - ], - "price": 0, - "published": "25-12-2017 13:30:25", - "pages": null, - "isbn": null - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonvalue/JsonValueUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonvalue/JsonValueUnitTest.java deleted file mode 100644 index 465daf13f5..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonvalue/JsonValueUnitTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.jackson.serialization.jsonvalue; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonValueUnitTest { - - @Test - public void whenSerializingUsingJsonValue_thenCorrect() throws JsonProcessingException { - - // act - String result = new ObjectMapper().writeValueAsString(Course.Level.ADVANCED); - - // assert - assertThat(result).isEqualTo("\"Advanced\""); - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java index c8c4c592f0..52d367f739 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java @@ -39,7 +39,6 @@ import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue; import com.baeldung.jackson.exception.UserWithRoot; import com.baeldung.jackson.jsonview.Item; import com.baeldung.jackson.jsonview.Views; -import com.baeldung.jackson.serialization.jsonrootname.Author; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.MapperFeature; @@ -48,7 +47,6 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class JacksonAnnotationUnitTest { @@ -388,30 +386,5 @@ public class JacksonAnnotationUnitTest { // assert assertThat(aliasBean.getFirstName(), is("Alex")); } - - @Test - public void whenSerializingUsingXMLRootNameWithNameSpace_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - ObjectMapper mapper = new XmlMapper(); - mapper = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).enable(SerializationFeature.INDENT_OUTPUT); - String result = mapper.writeValueAsString(author); - - // assert - assertThat(result, containsString("")); - - /* - - 3006b44a-cf62-4cfe-b3d8-30dc6c46ea96 - Alex - Theedom - - - */ - - } } From 8cf72e2e7ee4e53dcd3a3b240231a5258945ec55 Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 9 Mar 2019 17:18:23 +0100 Subject: [PATCH 155/254] BAEL-2217 forEach inside forEach in Kotlin: add flatMap example --- .../kotlin/com/baeldung/forEach/forEach.kt | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt b/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt index ef56009c71..20eda4e64f 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt +++ b/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt @@ -5,6 +5,15 @@ class Country(val name : String, val cities : List) class City(val name : String, val streets : List) +fun City.getStreetsWithCityName() : List { + return streets.map { "$name, $it" }.toList() +} + +fun Country.getCitiesWithCountryName() : List { + return cities.flatMap { it.getStreetsWithCityName() } + .map { "$name, $it" } +} + class World { private val streetsOfAmsterdam = listOf("Herengracht", "Prinsengracht") @@ -45,6 +54,19 @@ class World { } } } + + fun allStreetsFlatMap() { + + countries.flatMap { it.cities} + .flatMap { it.streets} + .forEach { println(it) } + } + + fun allFlatMapTable() { + + countries.flatMap { it.getCitiesWithCountryName() } + .forEach { println(it) } + } } fun main(args : Array) { @@ -56,6 +78,10 @@ fun main(args : Array) { world.allNested() world.allTable() + + world.allStreetsFlatMap() + + world.allFlatMapTable() } From cf5c99745fee64e00658b7fa034590b9386533ce Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 9 Mar 2019 22:54:08 +0530 Subject: [PATCH 156/254] BAEL-10957 Fix Jhipster Module Tests and Module Renaming -Added hibernate-java8 dependency in jhipster parent project to fix mapping of Java8 Date, Time types to database types and thereby fix all the tests that were failing due to this --- jhipster/jhipster-monolithic/pom.xml | 66 ++++++++++++++++------------ jhipster/pom.xml | 13 ++++-- 2 files changed, 47 insertions(+), 32 deletions(-) diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index 3e98298f56..12dead99df 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -3,7 +3,7 @@ 4.0.0 jhipster-monolithic war - jhipster-monolithic + jhipster-monolithic JHipster Monolithic Application @@ -87,7 +87,7 @@ io.dropwizard.metrics metrics-annotation - + io.dropwizard.metrics metrics-core @@ -95,15 +95,15 @@ io.dropwizard.metrics metrics-json - + io.dropwizard.metrics metrics-jvm - + io.dropwizard.metrics metrics-servlet - + io.dropwizard.metrics metrics-servlets @@ -201,10 +201,6 @@ org.hibernate hibernate-validator - - org.hibernate - hibernate-java8 - org.liquibase liquibase-core @@ -301,8 +297,8 @@ spring-boot:run - + org.eclipse.m2e lifecycle-mapping @@ -344,11 +340,27 @@ - + com.spotify docker-maven-plugin @@ -375,8 +387,7 @@ target/gatling/results src/test/gatling/bodies src/test/gatling/simulations - + true @@ -740,9 +751,8 @@ - cc @@ -858,8 +868,7 @@ - + IDE @@ -921,16 +930,15 @@ S3437,UndocumentedApi,BoldAndItalicTagsCheck - + src/main/webapp/app/**/*.* Web:BoldAndItalicTagsCheck - + src/main/java/**/* squid:S3437 - + src/main/java/**/* squid:UndocumentedApi diff --git a/jhipster/pom.xml b/jhipster/pom.xml index 3fcc53b354..e2a19ab21f 100644 --- a/jhipster/pom.xml +++ b/jhipster/pom.xml @@ -15,10 +15,17 @@ ../parent-boot-1 + + + org.hibernate + hibernate-java8 + + + jhipster-monolithic jhipster-microservice - jhipster-uaa - - + jhipster-uaa + + From 398770b64f76b0572399b49b0cbed75ecccce861 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 9 Mar 2019 22:58:23 +0530 Subject: [PATCH 157/254] BAEL-10957 Fixed formatting --- jhipster/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jhipster/pom.xml b/jhipster/pom.xml index e2a19ab21f..c50aac0c7a 100644 --- a/jhipster/pom.xml +++ b/jhipster/pom.xml @@ -25,7 +25,7 @@ jhipster-monolithic jhipster-microservice - jhipster-uaa - - + jhipster-uaa + + From 92e54a9231c45696a7d0f7fdd950bb0865133b52 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 9 Mar 2019 23:57:02 +0530 Subject: [PATCH 158/254] [BAEL-12185] - Removed copied classes from other repository - part 2 --- .../inclusion/jsonautodetect/Order.java | 54 -------------- .../inclusion/jsonignoretype/Order.java | 44 ----------- .../baeldung/jackson/polymorphism/Order.java | 62 ---------------- .../jsonanysetter/JsonAnySetterUnitTest.java | 50 ------------- .../JsonDeserializeUnitTest.java | 35 --------- .../general/jsonidentityinfo/Author.java | 31 -------- .../general/jsonidentityinfo/Course.java | 73 ------------------- .../general/jsonidentityinfo/Item.java | 64 ---------------- .../JsonIdentityInfoUnitTest.java | 60 --------------- .../general/jsonidentityinfo/Person.java | 45 ------------ .../jsonunwrapped/JsonUnwrappedUnitTest.java | 43 ----------- .../jackson/general/jsonunwrapped/Order.java | 54 -------------- .../general/jsonview/JsonViewUnitTest.java | 73 ------------------- .../jackson/general/jsonview/Order.java | 57 --------------- .../jackson/general/jsonview/Views.java | 15 ---- .../jackson/general/reference/Author.java | 30 -------- .../jackson/general/reference/Course.java | 73 ------------------- .../jackson/general/reference/Item.java | 64 ---------------- .../jackson/general/reference/Person.java | 45 ------------ .../general/reference/ReferenceUnitTest.java | 59 --------------- .../JsonAutoDetectUnitTest.java | 52 ------------- .../JsonIgnoreTypeUnitTest.java | 40 ---------- .../polymorphism/PolymorphismUnitTest.java | 66 ----------------- 23 files changed, 1189 deletions(-) delete mode 100644 jackson/src/main/java/com/baeldung/jackson/inclusion/jsonautodetect/Order.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoretype/Order.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/JsonIdentityInfoUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/Order.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonview/Order.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/jsonview/Views.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/reference/Author.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoretype/JsonIgnoreTypeUnitTest.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonautodetect/Order.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonautodetect/Order.java deleted file mode 100644 index f2ff5eeb08..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonautodetect/Order.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonautodetect; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonAutoDetect(fieldVisibility = Visibility.ANY) -public class Order { - - private UUID id; - private Type type; - private int internalAudit; - - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoretype/Order.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoretype/Order.java deleted file mode 100644 index 0d8867933f..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoretype/Order.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignoretype; - -import com.fasterxml.jackson.annotation.JsonIgnoreType; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - private UUID id; - private Type type; - - @JsonIgnoreType - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java b/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java deleted file mode 100644 index 1813148b2b..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.jackson.polymorphism; - -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - private UUID id; - private Type type; - private int internalAudit; - - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ordertype") - @JsonSubTypes({ @JsonSubTypes.Type(value = InternalType.class, name = "internal") }) - public static class Type { - public long id; - public String name; - } - - @JsonTypeName("internal") - public static class InternalType extends Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java deleted file mode 100644 index 2e1f94bc3c..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.jackson.deserialization.jsonanysetter; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonAnySetterUnitTest { - - @Test - public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException { - - // arrange - String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}"; - - // act - Inventory inventory = new ObjectMapper().readerFor(Inventory.class) - .readValue(json); - - // assert - assertThat(from(json).getMap(".") - .get("USA")).isEqualTo(inventory.getCountryDeliveryCost() - .get("USA")); - assertThat(from(json).getMap(".") - .get("UK")).isEqualTo(inventory.getCountryDeliveryCost() - .get("UK")); - assertThat(from(json).getMap(".") - .get("China")).isEqualTo(inventory.getCountryDeliveryCost() - .get("China")); - assertThat(from(json).getMap(".") - .get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost() - .get("Brazil")); - assertThat(from(json).getMap(".") - .get("France")).isEqualTo(inventory.getCountryDeliveryCost() - .get("France")); - assertThat(from(json).getMap(".") - .get("Russia")).isEqualTo(inventory.getCountryDeliveryCost() - .get("Russia")); - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java deleted file mode 100644 index a7934d96cf..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.jackson.deserialization.jsondeserialize; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; -import java.text.SimpleDateFormat; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonDeserializeUnitTest { - - @Test - public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException { - - // arrange - String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}"; - - // act - Book book = new ObjectMapper().readerFor(Book.class) - .readValue(bookJson); - - // assert - SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - assertThat(from(bookJson).getString("published")).isEqualTo(df.format(book.getPublished())); - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java deleted file mode 100644 index 1f36b95b2a..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java deleted file mode 100644 index 80dd9c275e..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java deleted file mode 100644 index bad6562122..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/JsonIdentityInfoUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/JsonIdentityInfoUnitTest.java deleted file mode 100644 index 014f1a8f69..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/JsonIdentityInfoUnitTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.Collections; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIdentityInfoUnitTest { - - @Test - public void whenSerializingUsingJsonIdentityInfo_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - Course course = new Course("Java EE Introduction", author); - author.setItems(Collections.singletonList(course)); - course.setAuthors(Collections.singletonList(author)); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getString("items[0].authors")).isNotNull(); - - /* - Authors are included. - { - "id": "1b408bf9-5946-4a14-a112-fde2953a7fe7", - "firstName": "Alex", - "lastName": "Theedom", - "items": [ - { - "id": "5ed30530-f0a5-42eb-b786-be2c655da968", - "title": "Java EE Introduction", - "authors": [ - "1b408bf9-5946-4a14-a112-fde2953a7fe7" - ], - "price": 0, - "duration": 0, - "medium": null, - "level": null, - "prerequisite": null - } - ] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java deleted file mode 100644 index ea80814124..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Person { - - private UUID id; - private String firstName; - private String lastName; - - public Person() { - } - - public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); - this.firstName = firstName; - this.lastName = lastName; - } - - 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 UUID getId() { - return id; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java deleted file mode 100644 index 5130e037d5..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.jackson.general.jsonunwrapped; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonUnwrappedUnitTest { - - @Test - public void whenSerializingUsingJsonUnwrapped_thenCorrect() throws JsonProcessingException { - - // arrange - Order.Type preorderType = new Order.Type(); - preorderType.id = 10; - preorderType.name = "pre-order"; - - Order order = new Order(preorderType); - - // act - String result = new ObjectMapper().writeValueAsString(order); - - // assert - assertThat(from(result).getInt("id")).isEqualTo(10); - assertThat(from(result).getString("name")).isEqualTo("pre-order"); - - /* - { - "id": 10, - "name": "pre-order" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/Order.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/Order.java deleted file mode 100644 index b1c5b832c3..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/Order.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.jackson.general.jsonunwrapped; - -import com.fasterxml.jackson.annotation.JsonUnwrapped; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - private UUID id; - - @JsonUnwrapped - private Type type; - private int internalAudit; - - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java deleted file mode 100644 index ab609008ce..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.jackson.general.jsonview; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonViewUnitTest { - - @Test - public void whenSerializingUsingJsonView_andInternalView_thenCorrect() throws JsonProcessingException { - - // arrange - Order order = new Order(120); - - // act - String result = new ObjectMapper().writerWithView(Views.Internal.class) - .writeValueAsString(order); - - // assert - assertThat(from(result).getUUID("id")).isNotNull(); - assertThat(from(result).getObject("type", Order.Type.class)).isNotNull(); - assertThat(from(result).getInt("internalAudit")).isEqualTo(120); - - /* - { - "id": "33806388-795b-4812-b90a-60292111bc5c", - "type": { - "id": 20, - "name": "Order" - }, - "internalAudit": 120 - } - */ - - } - - @Test - public void whenSerializingUsingJsonView_andPublicView_thenCorrect() throws JsonProcessingException { - - // arrange - Order order = new Order(120); - - // act - String result = new ObjectMapper().writerWithView(Views.Public.class) - .writeValueAsString(order); - - // assert - assertThat(from(result).getUUID("id")).isNotNull(); - assertThat(from(result).getObject("type", Order.Type.class)).isNotNull(); - assertThat(result).doesNotContain("internalAudit"); - - /* - { - "id": "5184d5fc-e359-4cdf-93fa-4054025bef4e", - "type": { - "id": 20, - "name": "Order" - } - } - */ - - } - -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Order.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Order.java deleted file mode 100644 index 69adf1b59d..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Order.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.jackson.general.jsonview; - -import com.fasterxml.jackson.annotation.JsonView; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - @JsonView(Views.Public.class) - private UUID id; - - @JsonView(Views.Public.class) - private Type type; - - @JsonView(Views.Internal.class) - private int internalAudit; - - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Views.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Views.java deleted file mode 100644 index b55997554d..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Views.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.jackson.general.jsonview; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Views { - public static class Public { - } - - public static class Internal extends Public { - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Author.java deleted file mode 100644 index 02dd9470d7..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Author.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import com.fasterxml.jackson.annotation.JsonManagedReference; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - @JsonManagedReference - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java deleted file mode 100644 index 251d25a517..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java deleted file mode 100644 index 5dd66a8ca3..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import com.fasterxml.jackson.annotation.JsonBackReference; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - - @JsonBackReference - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java deleted file mode 100644 index 95c0b35b8b..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Person { - - private UUID id; - private String firstName; - private String lastName; - - public Person() { - } - - public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); - this.firstName = firstName; - this.lastName = lastName; - } - - 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 UUID getId() { - return id; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java deleted file mode 100644 index 7a52a69656..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.Collections; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class ReferenceUnitTest { - - @Test - public void whenSerializingUsingReference_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - Course course = new Course("Java EE Introduction", author); - author.setItems(Collections.singletonList(course)); - course.setAuthors(Collections.singletonList(author)); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getString("items[0].authors")).isNull(); - - /* - Without references defined it throws StackOverflowError. - Authors excluded. - - { - "id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7", - "firstName": "Alex", - "lastName": "Theedom", - "items": [ - { - "id": "f8309629-d178-4d67-93a4-b513ec4a7f47", - "title": "Java EE Introduction", - "price": 0, - "duration": 0, - "medium": null, - "level": null, - "prerequisite": null - } - ] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java deleted file mode 100644 index a3e29776a9..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonautodetect; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonAutoDetectUnitTest { - - @Test - public void whenSerializingUsingJsonAutoDetect_thenCorrect() throws JsonProcessingException { - - // arrange - Order order = new Order(1234567890); - - // act - String result = new ObjectMapper().writeValueAsString(order); - - // assert - assertThat(from(result).getInt("internalAudit")).isEqualTo(1234567890); - - /* - With @JsonAutoDetect - { - "id": "c94774d9-de8f-4244-85d5-624bd3a4567a", - "type": { - "id": 20, - "name": "Order" - }, - "internalAudit": 1234567890 - } - - Without @JsonAutoDetect - { - "id": "c94774d9-de8f-4244-85d5-624bd3a4567a", - "type": { - "id": 20, - "name": "Order" - } - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoretype/JsonIgnoreTypeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoretype/JsonIgnoreTypeUnitTest.java deleted file mode 100644 index e8917ff526..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoretype/JsonIgnoreTypeUnitTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignoretype; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIgnoreTypeUnitTest { - - @Test - public void whenSerializingUsingJsonIgnoreType_thenCorrect() throws JsonProcessingException { - - // arrange - Order.Type type = new Order.Type(); - type.id = 10; - type.name = "Pre-order"; - - Order order = new Order(type); - - // act - String result = new ObjectMapper().writeValueAsString(order); - - // assert - assertThat(from(result).getString("id")).isNotNull(); - assertThat(from(result).getString("type")).isNull(); - - /* - {"id":"ac2428da-523e-443c-a18a-4ea4d2791fea"} - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java deleted file mode 100644 index e922cf9976..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.jackson.polymorphism; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class PolymorphismUnitTest { - - @Test - public void whenSerializingUsingPolymorphism_thenCorrect() throws JsonProcessingException { - - // arrange - Order.InternalType internalType = new Order.InternalType(); - internalType.id = 250; - internalType.name = "staff"; - - Order order = new Order(internalType); - - // act - String result = new ObjectMapper().writeValueAsString(order); - - // assert - assertThat(from(result).getString("type.ordertype")).isEqualTo("internal"); - - /* - { - "id": "7fc898e3-b4e7-41b0-8ffa-664cf3663f2e", - "type": { - "ordertype": "internal", - "id": 250, - "name": "staff" - } - } - */ - - } - - @Test - public void whenDeserializingPolymorphic_thenCorrect() throws IOException { - - // arrange - String orderJson = "{\"type\":{\"ordertype\":\"internal\",\"id\":100,\"name\":\"directors\"}}"; - - // act - Order order = new ObjectMapper().readerFor(Order.class) - .readValue(orderJson); - - // assert - assertThat(from(orderJson).getString("type.ordertype")).isEqualTo("internal"); - assertThat(((Order.InternalType) order.getType()).name).isEqualTo("directors"); - assertThat(((Order.InternalType) order.getType()).id).isEqualTo(100); - assertThat(order.getType() - .getClass()).isEqualTo(Order.InternalType.class); - } -} \ No newline at end of file From 274c740ecbf5601eaf542f5e378e47e0e1dc3982 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 9 Mar 2019 23:55:58 +0200 Subject: [PATCH 159/254] Update README.md --- algorithms-miscellaneous-1/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md index 7ed805f7c4..ea6d6f379b 100644 --- a/algorithms-miscellaneous-1/README.md +++ b/algorithms-miscellaneous-1/README.md @@ -17,3 +17,4 @@ - [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique) - [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations) - [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine) +- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm) From b9d8a8ab0a8c077dcfd38ecf68e8a7fdbb742a68 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 9 Mar 2019 23:56:46 +0200 Subject: [PATCH 160/254] Update README.md --- core-groovy/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-groovy/README.md b/core-groovy/README.md index ec2fcfa574..bac91bf028 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -8,3 +8,4 @@ - [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) - [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) - [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits) +- [Lists in Groovy](https://www.baeldung.com/groovy-lists) From 939a47f464f6b87f33e36fb93282e564064af08b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 9 Mar 2019 23:57:33 +0200 Subject: [PATCH 161/254] Update README.md --- core-java-collections-list/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-collections-list/README.md b/core-java-collections-list/README.md index c5139074e9..bfe06581c0 100644 --- a/core-java-collections-list/README.md +++ b/core-java-collections-list/README.md @@ -30,3 +30,4 @@ - [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal) - [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int) - [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance) +- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list) From ef94015a3696aa9dc428de00a7a15654a2267687 Mon Sep 17 00:00:00 2001 From: Ganesh Pagade Date: Sun, 10 Mar 2019 11:24:33 +0530 Subject: [PATCH 162/254] review comments --- .../java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java index 3bf2afbe4a..5b787f1956 100644 --- a/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java +++ b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java @@ -81,6 +81,7 @@ public class GsonAdvanceUnitTest { assertEquals(2, outList.size()); assertTrue(outList.get(0) instanceof Dog); + assertTrue(outList.get(1) instanceof Cow); } @Test @@ -101,7 +102,7 @@ public class GsonAdvanceUnitTest { Type listOfAnimals = new TypeToken>() {}.getType(); - RuntimeTypeAdapterFactory adapter = RuntimeTypeAdapterFactory.of(Animal.class) + RuntimeTypeAdapterFactory adapter = RuntimeTypeAdapterFactory.of(Animal.class, "type") .registerSubtype(Dog.class) .registerSubtype(Cow.class); @@ -111,5 +112,6 @@ public class GsonAdvanceUnitTest { assertEquals(2, outList.size()); assertTrue(outList.get(0) instanceof Dog); + assertTrue(outList.get(1) instanceof Cow); } } \ No newline at end of file From 7f24cbad71c57d046908431f354cd890059ca3e1 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 10 Mar 2019 09:41:07 +0200 Subject: [PATCH 163/254] new example for jackson article --- .../exception/UserWithRootNamespace.java | 18 ++++++++++ .../test/JacksonAnnotationUnitTest.java | 33 +++++++++++++++++-- 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 jackson/src/test/java/com/baeldung/jackson/exception/UserWithRootNamespace.java diff --git a/jackson/src/test/java/com/baeldung/jackson/exception/UserWithRootNamespace.java b/jackson/src/test/java/com/baeldung/jackson/exception/UserWithRootNamespace.java new file mode 100644 index 0000000000..bf8c85efba --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/exception/UserWithRootNamespace.java @@ -0,0 +1,18 @@ +package com.baeldung.jackson.exception; + +import com.fasterxml.jackson.annotation.JsonRootName; + +@JsonRootName(value = "user", namespace="users") +public class UserWithRootNamespace { + public int id; + public String name; + + public UserWithRootNamespace() { + super(); + } + + public UserWithRootNamespace(final int id, final String name) { + this.id = id; + this.name = name; + } +} diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java index 52d367f739..ee11f8f20e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java @@ -37,6 +37,7 @@ import com.baeldung.jackson.date.EventWithSerializer; import com.baeldung.jackson.dtos.MyMixInForIgnoreType; import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue; import com.baeldung.jackson.exception.UserWithRoot; +import com.baeldung.jackson.exception.UserWithRootNamespace; import com.baeldung.jackson.jsonview.Item; import com.baeldung.jackson.jsonview.Views; import com.fasterxml.jackson.core.JsonProcessingException; @@ -47,6 +48,7 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class JacksonAnnotationUnitTest { @@ -378,13 +380,40 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingUsingJsonAlias_thenCorrect() throws IOException { // arrange - String json = "{\"fName\": \"Alex\", \"lastName\": \"Theedom\"}"; + String json = "{\"fName\": \"John\", \"lastName\": \"Green\"}"; // act AliasBean aliasBean = new ObjectMapper().readerFor(AliasBean.class).readValue(json); // assert - assertThat(aliasBean.getFirstName(), is("Alex")); + assertThat(aliasBean.getFirstName(), is("John")); } + + @Test + public void whenSerializingUsingXMLRootNameWithNameSpace_thenCorrect() throws JsonProcessingException { + + // arrange + UserWithRootNamespace author = new UserWithRootNamespace(1, "John"); + + // act + ObjectMapper mapper = new XmlMapper(); + mapper = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).enable(SerializationFeature.INDENT_OUTPUT); + String result = mapper.writeValueAsString(author); + + // assert + assertThat(result, containsString("")); + + /* + + 3006b44a-cf62-4cfe-b3d8-30dc6c46ea96 + 1 + John + + + */ + + } + + } From 1b48e7943c2942feb1d49b8e4a8a352315a62fa4 Mon Sep 17 00:00:00 2001 From: PranayJain Date: Sun, 10 Mar 2019 17:30:20 +0530 Subject: [PATCH 164/254] BAEL-2719: Fixed the changes to load external file --- spring-boot-ops/pom.xml | 23 ++++++++++ .../baeldung/properties/ConfProperties.java | 43 +++++++++++++++++++ .../ExternalPropertyConfigurer.java | 18 ++++++++ .../ExternalPropertyFileLoader.java | 15 ++++--- .../main/resources/external/conf.properties | 4 -- ...rnalPropertyFileLoaderIntegrationTest.java | 27 ++++++++++++ .../ExternalPropertyFileLoaderUnitTest.java | 25 ----------- .../test/resources/external/conf.properties | 3 ++ 8 files changed, 122 insertions(+), 36 deletions(-) create mode 100644 spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java create mode 100644 spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java delete mode 100644 spring-boot-ops/src/main/resources/external/conf.properties create mode 100644 spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java delete mode 100644 spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderUnitTest.java create mode 100644 spring-boot-ops/src/test/resources/external/conf.properties diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 625b2ad188..6c49351820 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -110,6 +110,29 @@ + + org.apache.maven.plugins + maven-failsafe-plugin + 2.18 + + + + integration-tests + + integration-test + verify + + + + + **/ExternalPropertyFileLoaderIntegrationTest.java + + + + + diff --git a/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java b/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java new file mode 100644 index 0000000000..0b6041bb06 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java @@ -0,0 +1,43 @@ +package com.baeldung.properties; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class ConfProperties { + + @Value("${url}") + private String url; + + @Value("${username}") + private String username; + + @Value("${password}") + private String password; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + +} diff --git a/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java new file mode 100644 index 0000000000..67890d717a --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java @@ -0,0 +1,18 @@ +package com.baeldung.properties; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.core.io.FileSystemResource; + +@Configuration +public class ExternalPropertyConfigurer { + + @Bean + public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer(); + properties.setLocation(new FileSystemResource("src/test/resources/external/conf.properties")); + properties.setIgnoreResourceNotFound(false); + return properties; + } +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java index 233ddc0195..dc5e14549b 100644 --- a/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java +++ b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java @@ -1,17 +1,18 @@ package com.baeldung.properties; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; @SpringBootApplication public class ExternalPropertyFileLoader { + + @Autowired + ConfProperties prop; + public static void main(String[] args) { - ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(ExternalPropertyFileLoader.class).properties("spring.config.name:conf", "spring.config.location:file:src/main/resources/external/") - .build() - .run(args); - ConfigurableEnvironment environment = applicationContext.getEnvironment(); - environment.getProperty("username"); + new SpringApplicationBuilder(ExternalPropertyFileLoader.class).build() + .run(args); } + } diff --git a/spring-boot-ops/src/main/resources/external/conf.properties b/spring-boot-ops/src/main/resources/external/conf.properties deleted file mode 100644 index a724b878b4..0000000000 --- a/spring-boot-ops/src/main/resources/external/conf.properties +++ /dev/null @@ -1,4 +0,0 @@ -url=jdbc:postgresql://localhost:5432/ -username=admin -password=root -spring.main.allow-bean-definition-overriding=true diff --git a/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java new file mode 100644 index 0000000000..2001db57d0 --- /dev/null +++ b/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.properties; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = ExternalPropertyFileLoader.class) +public class ExternalPropertyFileLoaderIntegrationTest { + + @Autowired + ConfProperties props; + + @Test + public void whenExternalisedPropertiesLoaded_thenReadValues() throws IOException { + assertEquals("jdbc:postgresql://localhost:5432/", props.getUrl()); + assertEquals("admin", props.getUsername()); + assertEquals("root", props.getPassword()); + } + +} diff --git a/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderUnitTest.java b/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderUnitTest.java deleted file mode 100644 index 656d8561ec..0000000000 --- a/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderUnitTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.properties; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -public class ExternalPropertyFileLoaderUnitTest { - - @Test - public void whenExternalisedPropertiesLoaded_thenReadValues() { - ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(ExternalPropertyFileLoader.class).properties("spring.config.name:conf", "spring.config.location:file:src/main/resources/external/") - .build() - .run(); - ConfigurableEnvironment environment = applicationContext.getEnvironment(); - Assert.assertEquals(environment.getProperty("url"), "jdbc:postgresql://localhost:5432/"); - Assert.assertEquals(environment.getProperty("username"), "admin"); - Assert.assertEquals(environment.getProperty("password"), "root"); - } - -} diff --git a/spring-boot-ops/src/test/resources/external/conf.properties b/spring-boot-ops/src/test/resources/external/conf.properties new file mode 100644 index 0000000000..da9533fe1f --- /dev/null +++ b/spring-boot-ops/src/test/resources/external/conf.properties @@ -0,0 +1,3 @@ +url=jdbc:postgresql://localhost:5432/ +username=admin +password=root \ No newline at end of file From 9fae5f5a50f3cca4738b8ef0fd1346c8dc2be781 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Sun, 10 Mar 2019 17:40:04 +0000 Subject: [PATCH 165/254] BAEL-2522 - Comments addressed. --- .../XmlGregorianCalendarConverter.java | 29 ------------------- .../XmlGregorianCalendarConverterTest.java | 14 ++------- 2 files changed, 3 insertions(+), 40 deletions(-) delete mode 100644 java-dates/src/main/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverter.java diff --git a/java-dates/src/main/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverter.java b/java-dates/src/main/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverter.java deleted file mode 100644 index 7f7515ec4b..0000000000 --- a/java-dates/src/main/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.xmlgregoriancalendar; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import java.time.LocalDate; - -public class XmlGregorianCalendarConverter { - - public static void main(String[] args) throws DatatypeConfigurationException { - LocalDate localDate = LocalDate.now(); - System.out.println("localdate: " + localDate); - XMLGregorianCalendar xmlGregorianCalendar = fromLocalDate(localDate); - System.out.println("xmlGregorianCalendar: " + xmlGregorianCalendar); - - xmlGregorianCalendar.setTime(1, 1, 30); - System.out.println("xmlGregorianCalendar with time information: " + xmlGregorianCalendar); - LocalDate newLocalDate = fromXMLGregorianCalendar(xmlGregorianCalendar); - System.out.println("newLocalDate: " + newLocalDate); - } - - static XMLGregorianCalendar fromLocalDate(LocalDate localDate) throws DatatypeConfigurationException { - return DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString()); - } - - static LocalDate fromXMLGregorianCalendar(XMLGregorianCalendar xmlGregorianCalendar) { - return LocalDate.of(xmlGregorianCalendar.getYear(), xmlGregorianCalendar.getMonth(), xmlGregorianCalendar.getDay()); - } -} diff --git a/java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java b/java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java index f27c91be7e..7fe1cd36a1 100644 --- a/java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java +++ b/java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java @@ -16,7 +16,7 @@ public class XmlGregorianCalendarConverterTest { @Test public void fromLocalDateToXMLGregorianCalendar() throws DatatypeConfigurationException { LocalDate localDate = LocalDate.of(2017, 4, 25); - XMLGregorianCalendar xmlGregorianCalendar = fromLocalDate(localDate); + XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString()); assertThat(xmlGregorianCalendar.getYear()).isEqualTo(localDate.getYear()); assertThat(xmlGregorianCalendar.getMonth()).isEqualTo(localDate.getMonthValue()); @@ -26,19 +26,11 @@ public class XmlGregorianCalendarConverterTest { @Test public void fromXMLGregorianCalendarToLocalDate() throws DatatypeConfigurationException { XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-04-25"); - LocalDate localDate = fromXMLGregorianCalendar(xmlGregorianCalendar); + LocalDate localDate = LocalDate.of(xmlGregorianCalendar.getYear(), xmlGregorianCalendar.getMonth(), xmlGregorianCalendar.getDay()); assertThat(localDate.getYear()).isEqualTo(xmlGregorianCalendar.getYear()); assertThat(localDate.getMonthValue()).isEqualTo(xmlGregorianCalendar.getMonth()); assertThat(localDate.getDayOfMonth()).isEqualTo(xmlGregorianCalendar.getDay()); } - - @Test - public void compositionOfFunctionsIsIdentity() throws DatatypeConfigurationException { // Only if we don't consider time - LocalDate localDate = LocalDate.of(2017, 4, 25); - XMLGregorianCalendar xmlGregorianCalendar = fromLocalDate(localDate); - LocalDate resultDate = fromXMLGregorianCalendar(xmlGregorianCalendar); - - assertThat(resultDate).isEqualTo(localDate); - } + } From 84d83fb8ec138e3a4f8b321a74e7dc64aa89543e Mon Sep 17 00:00:00 2001 From: Erhan KARAKAYA Date: Sun, 10 Mar 2019 21:37:48 +0300 Subject: [PATCH 166/254] Changed class names to make them more memorable --- .../sampleabstract/AbstractService.java | 57 ------------------- .../baeldung/sampleabstract/BallService.java | 28 +++++++++ ...FooService.java => BasketballService.java} | 7 +-- .../org/baeldung/sampleabstract/DemoApp.java | 10 ---- .../org/baeldung/sampleabstract/FooBean.java | 12 ---- .../{BarBean.java => LogRepository.java} | 8 +-- .../{FooBarBean.java => RuleRepository.java} | 8 +-- 7 files changed, 39 insertions(+), 91 deletions(-) delete mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/AbstractService.java create mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/BallService.java rename spring-all/src/main/java/org/baeldung/sampleabstract/{FooService.java => BasketballService.java} (56%) delete mode 100644 spring-all/src/main/java/org/baeldung/sampleabstract/FooBean.java rename spring-all/src/main/java/org/baeldung/sampleabstract/{BarBean.java => LogRepository.java} (50%) rename spring-all/src/main/java/org/baeldung/sampleabstract/{FooBarBean.java => RuleRepository.java} (50%) diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractService.java deleted file mode 100644 index 51882f20b3..0000000000 --- a/spring-all/src/main/java/org/baeldung/sampleabstract/AbstractService.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.baeldung.sampleabstract; - -import org.springframework.beans.factory.annotation.Autowired; - - -public abstract class AbstractService { - - @Autowired - private FooBean fooBean; - - private BarBean barBean; - - private FooBarBean fooBarBean; - - public AbstractService(FooBarBean fooBarBean) { - - this.fooBarBean = fooBarBean; - } - - public FooBean getFooBean() { - - return fooBean; - } - - public void setFooBean(FooBean fooBean) { - - this.fooBean = fooBean; - } - - public BarBean getBarBean() { - - return barBean; - } - - @Autowired - public void setBarBean(BarBean barBean) { - - this.barBean = barBean; - } - - public FooBarBean getFooBarBean() { - - return fooBarBean; - } - - public void setFooBarBean(FooBarBean fooBarBean) { - - this.fooBarBean = fooBarBean; - } - - public void afterInitialize() { - - System.out.println(fooBean.value()); - System.out.println(barBean.value()); - System.out.println(fooBarBean.value()); - } -} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/BallService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/BallService.java new file mode 100644 index 0000000000..9a75de7fa1 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/BallService.java @@ -0,0 +1,28 @@ +package org.baeldung.sampleabstract; + +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.PostConstruct; + +public abstract class BallService { + + private RuleRepository ruleRepository; + + private LogRepository logRepository; + + public BallService(RuleRepository ruleRepository) { + this.ruleRepository = ruleRepository; + } + + @Autowired + public final void setLogRepository(LogRepository logRepository) { + this.logRepository = logRepository; + } + + @PostConstruct + public void afterInitialize() { + + System.out.println(ruleRepository.toString()); + System.out.println(logRepository.toString()); + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/FooService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/BasketballService.java similarity index 56% rename from spring-all/src/main/java/org/baeldung/sampleabstract/FooService.java rename to spring-all/src/main/java/org/baeldung/sampleabstract/BasketballService.java index 8bc625e098..c117231d3c 100644 --- a/spring-all/src/main/java/org/baeldung/sampleabstract/FooService.java +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/BasketballService.java @@ -4,11 +4,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class FooService extends AbstractService { +public class BasketballService extends BallService { @Autowired - public FooService(FooBarBean fooBarBean) { - - super(fooBarBean); + public BasketballService(RuleRepository ruleRepository) { + super(ruleRepository); } } diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java b/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java index 0c3c4ea083..615d354ecf 100644 --- a/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java @@ -1,28 +1,18 @@ package org.baeldung.sampleabstract; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import javax.annotation.PostConstruct; - @Configuration @ComponentScan(basePackages = "org.baeldung.sampleabstract") public class DemoApp { - @Autowired - private FooService fooService; public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApp.class); } - @PostConstruct - public void afterInitialize() { - - fooService.afterInitialize(); - } } diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/FooBean.java b/spring-all/src/main/java/org/baeldung/sampleabstract/FooBean.java deleted file mode 100644 index 5ef623b5af..0000000000 --- a/spring-all/src/main/java/org/baeldung/sampleabstract/FooBean.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.sampleabstract; - -import org.springframework.stereotype.Component; - -@Component -public class FooBean { - - public String value() { - - return "fooBean"; - } -} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/BarBean.java b/spring-all/src/main/java/org/baeldung/sampleabstract/LogRepository.java similarity index 50% rename from spring-all/src/main/java/org/baeldung/sampleabstract/BarBean.java rename to spring-all/src/main/java/org/baeldung/sampleabstract/LogRepository.java index 8aeb5d2001..3a65671493 100644 --- a/spring-all/src/main/java/org/baeldung/sampleabstract/BarBean.java +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/LogRepository.java @@ -3,10 +3,10 @@ package org.baeldung.sampleabstract; import org.springframework.stereotype.Component; @Component -public class BarBean { +public class LogRepository { - public String value() { - - return "barBean"; + @Override + public String toString() { + return "logRepository"; } } diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/FooBarBean.java b/spring-all/src/main/java/org/baeldung/sampleabstract/RuleRepository.java similarity index 50% rename from spring-all/src/main/java/org/baeldung/sampleabstract/FooBarBean.java rename to spring-all/src/main/java/org/baeldung/sampleabstract/RuleRepository.java index 0f46518a41..fd42178ab6 100644 --- a/spring-all/src/main/java/org/baeldung/sampleabstract/FooBarBean.java +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/RuleRepository.java @@ -3,10 +3,10 @@ package org.baeldung.sampleabstract; import org.springframework.stereotype.Component; @Component -public class FooBarBean { +public class RuleRepository { - public String value() { - - return "fooBarBean"; + @Override + public String toString() { + return "ruleRepository"; } } From d36107b8c0bc1d86445d15500c3de27ed4d836bb Mon Sep 17 00:00:00 2001 From: amit2103 Date: Mon, 11 Mar 2019 00:44:59 +0530 Subject: [PATCH 167/254] [BAEL-10128] Updated spring JPA article --- persistence-modules/spring-jpa/pom.xml | 8 ++++---- .../java/com/baeldung/SpringContextIntegrationTest.java | 2 ++ .../persistence/repository/InMemoryDBIntegrationTest.java | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 29a6996791..3daba6cd55 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -156,13 +156,13 @@ - 4.3.8.RELEASE + 5.1.5.RELEASE 3.21.0-GA - 5.2.10.Final + 5.2.17.Final 6.0.6 - 1.11.3.RELEASE + 2.1.5.RELEASE 1.4.195 @@ -170,7 +170,7 @@ 2.5 - 5.4.1.Final + 6.0.15.Final 1.4.01 2.2.5 diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java index aa85128628..822cbb8ed5 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung; import org.baeldung.config.PersistenceJPAConfigL2Cache; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -11,6 +12,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) @WebAppConfiguration +@DirtiesContext public class SpringContextIntegrationTest { @Test diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index 9ddc48460a..4d1bcbe1b2 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -35,7 +35,7 @@ public class InMemoryDBIntegrationTest { Student student = new Student(ID, NAME); studentRepository.save(student); - Student student2 = studentRepository.findOne(ID); + Student student2 = studentRepository.findById(ID).get(); assertEquals("name incorrect", NAME, student2.getName()); } From 1131705393d1cc04cb1c8166b7fdbd19f29128f7 Mon Sep 17 00:00:00 2001 From: Dhananjay Singh Date: Mon, 11 Mar 2019 00:30:33 +0100 Subject: [PATCH 168/254] REST-assured web --- testing-modules/rest-assured/pom.xml | 37 +++-- .../com/baeldung/restassured/Application.java | 13 ++ .../restassured/controller/AppController.java | 100 ++++++++++++ .../com/baeldung/restassured/model/Movie.java | 58 +++++++ .../restassured/service/AppService.java | 45 ++++++ .../rest-assured/src/main/resources/1 | 1 + .../rest-assured/src/main/resources/2 | 1 + .../AppControllerIntegrationTest.java | 142 ++++++++++++++++++ .../rest-assured/src/test/resources/test.txt | 1 + 9 files changed, 379 insertions(+), 19 deletions(-) create mode 100644 testing-modules/rest-assured/src/main/java/com/baeldung/restassured/Application.java create mode 100644 testing-modules/rest-assured/src/main/java/com/baeldung/restassured/controller/AppController.java create mode 100644 testing-modules/rest-assured/src/main/java/com/baeldung/restassured/model/Movie.java create mode 100644 testing-modules/rest-assured/src/main/java/com/baeldung/restassured/service/AppService.java create mode 100644 testing-modules/rest-assured/src/main/resources/1 create mode 100644 testing-modules/rest-assured/src/main/resources/2 create mode 100644 testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java create mode 100644 testing-modules/rest-assured/src/test/resources/test.txt diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 687a9a2fe4..1d6b7fe933 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -8,16 +8,30 @@ com.baeldung - parent-java + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-java + ../../parent-boot-2 + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + com.google.guava + guava + 18.0 + javax.servlet javax.servlet-api - ${javax.servlet-api.version} javax.servlet @@ -27,49 +41,40 @@ org.eclipse.jetty jetty-security - ${jetty.version} org.eclipse.jetty jetty-servlet - ${jetty.version} org.eclipse.jetty jetty-servlets - ${jetty.version} org.eclipse.jetty jetty-io - ${jetty.version} org.eclipse.jetty jetty-http - ${jetty.version} org.eclipse.jetty jetty-server - ${jetty.version} org.eclipse.jetty jetty-util - ${jetty.version} org.apache.httpcomponents httpcore - ${httpcore.version} org.apache.commons commons-lang3 - ${commons-lang3.version} @@ -92,19 +97,16 @@ joda-time - joda-time - ${joda-time.version} + joda-time com.fasterxml.jackson.core jackson-annotations - ${jackson.version} com.fasterxml.jackson.core jackson-databind - ${jackson.version} @@ -128,7 +130,6 @@ org.apache.httpcomponents httpclient - ${httpclient.version} @@ -145,13 +146,11 @@ io.rest-assured rest-assured - ${rest-assured.version} test io.rest-assured json-schema-validator - ${rest-assured-json-schema-validator.version} com.github.fge diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/Application.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/Application.java new file mode 100644 index 0000000000..8b53a9c63d --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.restassured; + +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); + } + +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/controller/AppController.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/controller/AppController.java new file mode 100644 index 0000000000..d68ebf4b03 --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/controller/AppController.java @@ -0,0 +1,100 @@ +package com.baeldung.restassured.controller; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.util.Set; +import java.util.UUID; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.InputStreamResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.restassured.model.Movie; +import com.baeldung.restassured.service.AppService; + +@RestController +public class AppController { + + @Autowired + AppService appService; + + @GetMapping("/movies") + public ResponseEntity getMovies() { + + Set result = appService.getAll(); + + return ResponseEntity.ok() + .body(result); + } + + @PostMapping("/movie") + @ResponseStatus(HttpStatus.CREATED) + public Movie addMovie(@RequestBody Movie movie) { + + appService.add(movie); + return movie; + } + + @GetMapping("/movie/{id}") + public ResponseEntity getMovie(@PathVariable int id) { + + Movie movie = appService.findMovie(id); + if (movie == null) { + return ResponseEntity.badRequest() + .body("Invalid movie id"); + } + + return ResponseEntity.ok(movie); + } + + @GetMapping("/welcome") + public ResponseEntity welcome(HttpServletResponse response) { + + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8"); + headers.add("sessionId", UUID.randomUUID() + .toString()); + + Cookie cookie = new Cookie("token", "some-token"); + cookie.setDomain("localhost"); + + response.addCookie(cookie); + + return ResponseEntity.noContent() + .headers(headers) + .build(); + } + + @GetMapping("/download/{id}") + public ResponseEntity getFile(@PathVariable int id) throws FileNotFoundException { + + File file = appService.getFile(id); + + if (file == null) { + return ResponseEntity.notFound() + .build(); + } + + InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); + + return ResponseEntity.ok() + .contentLength(file.length()) + .contentType(MediaType.parseMediaType("application/octet-stream")) + .body(resource); + } + +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/model/Movie.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/model/Movie.java new file mode 100644 index 0000000000..00a446fc65 --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/model/Movie.java @@ -0,0 +1,58 @@ +package com.baeldung.restassured.model; + +public class Movie { + + private Integer id; + + private String name; + + private String synopsis; + + public Movie() { + } + + public Movie(Integer id, String name, String synopsis) { + super(); + this.id = id; + this.name = name; + this.synopsis = synopsis; + } + + public Integer getId() { + return id; + } + + public String getName() { + return name; + } + + public String getSynopsis() { + return synopsis; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Movie other = (Movie) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/service/AppService.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/service/AppService.java new file mode 100644 index 0000000000..15685f2924 --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/service/AppService.java @@ -0,0 +1,45 @@ +package com.baeldung.restassured.service; + +import java.io.File; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Service; + +import com.baeldung.restassured.model.Movie; + +@Service +public class AppService { + + private Set movieSet = new HashSet<>(); + + public Set getAll() { + return movieSet; + } + + public void add(Movie movie) { + movieSet.add(movie); + } + + public Movie findMovie(int id) { + return movieSet.stream() + .filter(movie -> movie.getId() + .equals(id)) + .findFirst() + .orElse(null); + } + + public File getFile(int id) { + File file = null; + try { + file = new ClassPathResource(String.valueOf(id)).getFile(); + } catch (IOException e) { + e.printStackTrace(); + } + + return file; + } + +} diff --git a/testing-modules/rest-assured/src/main/resources/1 b/testing-modules/rest-assured/src/main/resources/1 new file mode 100644 index 0000000000..49351eb5b7 --- /dev/null +++ b/testing-modules/rest-assured/src/main/resources/1 @@ -0,0 +1 @@ +File 1 \ No newline at end of file diff --git a/testing-modules/rest-assured/src/main/resources/2 b/testing-modules/rest-assured/src/main/resources/2 new file mode 100644 index 0000000000..9fbb45ed08 --- /dev/null +++ b/testing-modules/rest-assured/src/main/resources/2 @@ -0,0 +1 @@ +File 2 \ No newline at end of file diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java new file mode 100644 index 0000000000..9ad940683f --- /dev/null +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java @@ -0,0 +1,142 @@ +package com.baeldung.restassured.controller; + +import static io.restassured.RestAssured.get; +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.annotation.PostConstruct; + +import org.junit.jupiter.api.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.test.mock.mockito.MockBean; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.restassured.model.Movie; +import com.baeldung.restassured.service.AppService; + +import io.restassured.response.Response; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class AppControllerIntegrationTest { + + @LocalServerPort + private int port; + + private String uri; + + @PostConstruct + public void init() { + uri = "http://localhost:" + port; + } + + @MockBean + AppService appService; + + @Test + public void givenMovieId_whenMakingGetRequestToMovieEndpoint_thenReturnMovie() { + + Movie testMovie = new Movie(1, "movie1", "summary1"); + when(appService.findMovie(1)).thenReturn(testMovie); + + get(uri + "/movie/" + testMovie.getId()).then() + .assertThat() + .statusCode(HttpStatus.OK.value()) + .body("id", equalTo(testMovie.getId())) + .body("name", equalTo(testMovie.getName())) + .body("synopsis", equalTo(testMovie.getSynopsis())); + + Movie result = get(uri + "/movie/" + testMovie.getId()).then() + .assertThat() + .statusCode(HttpStatus.OK.value()) + .extract() + .as(Movie.class); + assertThat(result).isEqualTo(testMovie); + } + + @Test + public void whenCallingMoviesEndpoint_thenReturnAllMovies() { + + Set movieSet = new HashSet<>(); + movieSet.add(new Movie(1, "movie1", "summary1")); + movieSet.add(new Movie(2, "movie2", "summary2")); + when(appService.getAll()).thenReturn(movieSet); + + get(uri + "/movies").then() + .statusCode(HttpStatus.OK.value()) + .assertThat() + .body("size()", is(2)); + + Movie[] movies = get(uri + "/movies").then() + .statusCode(200) + .extract() + .as(Movie[].class); + assertThat(movies.length).isEqualTo(2); + } + + @Test + public void givenMovie_whenMakingPostRequestToMovieEndpoint_thenCorrect() { + + Map request = new HashMap<>(); + request.put("id", "11"); + request.put("name", "movie1"); + request.put("synopsis", "summary1"); + + int movieId = given().contentType("application/json") + .body(request) + .when() + .post(uri + "/movie") + .then() + .assertThat() + .statusCode(HttpStatus.CREATED.value()) + .extract() + .path("id"); + assertThat(movieId).isEqualTo(11); + + } + + @Test + public void whenCallingWelcomeEndpoint_thenCorrect() { + + get(uri + "/welcome").then() + .assertThat() + .header("sessionId", notNullValue()) + .cookie("token", notNullValue()); + + Response response = get(uri + "/welcome"); + + String headerName = response.getHeader("sessionId"); + String cookieValue = response.getCookie("token"); + assertThat(headerName).isNotBlank(); + assertThat(cookieValue).isNotBlank(); + } + + @Test + public void givenId_whenCallingDowloadEndpoint_thenCorrect() throws IOException { + + File file = new ClassPathResource("test.txt").getFile(); + long fileSize = file.length(); + when(appService.getFile(1)).thenReturn(file); + + byte[] result = get(uri + "/download/1").asByteArray(); + + assertThat(result.length).isEqualTo(fileSize); + } + +} diff --git a/testing-modules/rest-assured/src/test/resources/test.txt b/testing-modules/rest-assured/src/test/resources/test.txt new file mode 100644 index 0000000000..84362ca046 --- /dev/null +++ b/testing-modules/rest-assured/src/test/resources/test.txt @@ -0,0 +1 @@ +Test file \ No newline at end of file From 3d5fde2a30e6b7c8c0a0efa210ee1101bb932684 Mon Sep 17 00:00:00 2001 From: Dhananjay Singh Date: Mon, 11 Mar 2019 00:42:05 +0100 Subject: [PATCH 169/254] Mover version down --- testing-modules/rest-assured/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 1d6b7fe933..8128cd0b3f 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -27,7 +27,7 @@ com.google.guava guava - 18.0 + ${guava.version} javax.servlet @@ -170,6 +170,7 @@ + 18.0 2.9.7 1.8 19.0 From 6ab2e7a71a84cbe8808d501b51f98cee64abb109 Mon Sep 17 00:00:00 2001 From: Rodrigo Graciano Date: Sun, 10 Mar 2019 20:34:19 -0400 Subject: [PATCH 170/254] BAEL-2760 --- .../kotlin/com/baeldung/range/CustomColor.kt | 56 +++++++++++++++++++ .../com/baeldung/range/CustomColorTest.kt | 41 ++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt create mode 100644 core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt new file mode 100644 index 0000000000..b4fed13b18 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt @@ -0,0 +1,56 @@ +package com.baeldung.range + +import java.lang.IllegalStateException + +class CustomColor(val rgb: Int): Comparable { + + override fun compareTo(other: CustomColor): Int { + return this.rgb.compareTo(other.rgb) + } + + operator fun rangeTo(that: CustomColor) = ColorRange(this,that) + + operator fun inc(): CustomColor { + return CustomColor(rgb + 1) + } + + init { + if(rgb < 0x000000 || rgb > 0xFFFFFF){ + throw IllegalStateException("RGB must be between 0 and 16777215") + } + } + + override fun toString(): String { + return "CustomColor(rgb=$rgb)" + } +} +class ColorRange(override val start: CustomColor, + override val endInclusive: CustomColor) : ClosedRange, Iterable{ + + override fun iterator(): Iterator { + return ColorIterator(start, endInclusive) + } +} + +class ColorIterator(val start: CustomColor, val endInclusive: CustomColor) : Iterator { + + var initValue = start + + override fun hasNext(): Boolean { + return initValue <= endInclusive + } + + override fun next(): CustomColor { + return initValue++ + } +} + +fun main(args: Array) { + val a = CustomColor(0xABCDEF) + val b = CustomColor(-1) + val c = CustomColor(0xABCDFF) + + for(color in a..c){ + println(color) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt new file mode 100644 index 0000000000..8c8795ac42 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt @@ -0,0 +1,41 @@ +package com.baeldung.range + +import org.junit.Test +import java.lang.IllegalStateException +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +class CustomColorTest { + + @Test + fun testInvalidConstructor(){ + assertFailsWith(IllegalStateException::class){ + CustomColor(-1) + } + } + + @Test + fun assertHas10Colors(){ + assertTrue { + val a = CustomColor(1) + val b = CustomColor(10) + val range = a..b + for(cc in range){ + println(cc) + } + range.toList().size == 10 + } + } + + @Test + fun assertContains0xCCCCCC(){ + assertTrue { + val a = CustomColor(0xBBBBBB) + val b = CustomColor(0xDDDDDD) + val range = a..b + range.contains(CustomColor(0xCCCCCC)) + } + } + +} + From c59211f756f46e818fc766b9f2e01e99e9267c88 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Mon, 11 Mar 2019 03:18:23 +0100 Subject: [PATCH 171/254] BAEL-2776 Chaining Optionals in Java 8 (#6502) * BAEL-2776 Chaining Optionals in Java 8 * BAEL-2776 Improvements after the first review --- .../optional/OptionalChainingUnitTest.java | 110 ++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java new file mode 100644 index 0000000000..70ec324cb3 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java @@ -0,0 +1,110 @@ +package com.baeldung.java8.optional; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Optional; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.junit.Assert.*; + +public class OptionalChainingUnitTest { + + private boolean getEmptyEvaluated; + private boolean getHelloEvaluated; + private boolean getByeEvaluated; + + @Before + public void setUp() { + getEmptyEvaluated = false; + getHelloEvaluated = false; + getByeEvaluated = false; + } + + @Test + public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturned() { + Optional found = Stream.of(getEmpty(), getHello(), getBye()) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst(); + + assertEquals(getHello(), found); + } + + @Test + public void givenTwoEmptyOptionals_whenChaining_thenEmptyOptionalIsReturned() { + Optional found = Stream.of(getEmpty(), getEmpty()) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst(); + + assertFalse(found.isPresent()); + } + + @Test + public void givenTwoEmptyOptionals_whenChaining_thenDefaultIsReturned() { + String found = Stream.>>of( + () -> createOptional("empty"), + () -> createOptional("empty") + ) + .map(Supplier::get) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst() + .orElseGet(() -> "default"); + + assertEquals("default", found); + } + + @Test + public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturnedAndRestNotEvaluated() { + Optional found = Stream.>>of(this::getEmpty, this::getHello, this::getBye) + .map(Supplier::get) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst(); + + assertTrue(this.getEmptyEvaluated); + assertTrue(this.getHelloEvaluated); + assertFalse(this.getByeEvaluated); + assertEquals(getHello(), found); + } + + @Test + public void givenTwoOptionalsReturnedByOneArgMethod_whenChaining_thenFirstNonEmptyIsReturned() { + Optional found = Stream.>>of( + () -> createOptional("empty"), + () -> createOptional("hello") + ) + .map(Supplier::get) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst(); + + assertEquals(createOptional("hello"), found); + } + + private Optional getEmpty() { + this.getEmptyEvaluated = true; + return Optional.empty(); + } + + private Optional getHello() { + this.getHelloEvaluated = true; + return Optional.of("hello"); + } + + private Optional getBye() { + this.getByeEvaluated = true; + return Optional.of("bye"); + } + + private Optional createOptional(String input) { + if (input == null || input == "" || input == "empty") { + return Optional.empty(); + } + + return Optional.of(input); + } +} \ No newline at end of file From dcaf1b35a049195e74c4a1c8b7ac719ce7f3f346 Mon Sep 17 00:00:00 2001 From: PranayJain Date: Mon, 11 Mar 2019 13:04:19 +0530 Subject: [PATCH 172/254] BAEL-2719: Skipped conf.properties from packaging --- spring-boot-ops/pom.xml | 9 +++++++++ .../baeldung/properties/ExternalPropertyConfigurer.java | 2 +- .../src/main/resources/external/conf.properties | 4 ++++ .../src/test/resources/external/conf.properties | 3 --- 4 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 spring-boot-ops/src/main/resources/external/conf.properties delete mode 100644 spring-boot-ops/src/test/resources/external/conf.properties diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 6c49351820..f36434b682 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -95,6 +95,15 @@ ${project.artifactId} + + + src/main/resources + true + + **/conf.properties + + + org.springframework.boot diff --git a/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java index 67890d717a..0cdbb452d5 100644 --- a/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java +++ b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java @@ -11,7 +11,7 @@ public class ExternalPropertyConfigurer { @Bean public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer(); - properties.setLocation(new FileSystemResource("src/test/resources/external/conf.properties")); + properties.setLocation(new FileSystemResource("src/main/resources/external/conf.properties")); properties.setIgnoreResourceNotFound(false); return properties; } diff --git a/spring-boot-ops/src/main/resources/external/conf.properties b/spring-boot-ops/src/main/resources/external/conf.properties new file mode 100644 index 0000000000..cfcd23dc76 --- /dev/null +++ b/spring-boot-ops/src/main/resources/external/conf.properties @@ -0,0 +1,4 @@ +url=jdbc:postgresql://localhost:5432/ +username=admin +password=root +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-ops/src/test/resources/external/conf.properties b/spring-boot-ops/src/test/resources/external/conf.properties deleted file mode 100644 index da9533fe1f..0000000000 --- a/spring-boot-ops/src/test/resources/external/conf.properties +++ /dev/null @@ -1,3 +0,0 @@ -url=jdbc:postgresql://localhost:5432/ -username=admin -password=root \ No newline at end of file From 24552d68dd0881cabb613669cca71318df9ebb31 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 15:35:25 +0800 Subject: [PATCH 173/254] Update README.MD --- spring-boot/README.MD | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 28123687fd..223e0959fc 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -36,3 +36,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) - [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) - [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) +- [Entity To DTO Conversion for a Spring REST API](https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application) From e82e5b2332192178b3d2f8809f68ab8f854bca6a Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 15:39:07 +0800 Subject: [PATCH 174/254] Update README.md --- core-java-io/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-io/README.md b/core-java-io/README.md index 5e0f7bfbd1..22901b22d5 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -40,3 +40,4 @@ - [Create a Directory in Java](https://www.baeldung.com/java-create-directory) - [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv) - [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files) +- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) From c3387be55b9a07d47027fd213b5a6caf5277ebde Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 15:41:51 +0800 Subject: [PATCH 175/254] Update README.md --- core-java-11/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-11/README.md b/core-java-11/README.md index 3c8b94fa28..5e2c07178b 100644 --- a/core-java-11/README.md +++ b/core-java-11/README.md @@ -4,3 +4,4 @@ - [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params) - [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api) - [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control) +- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client) From 56fb8ec854aab3fdce3377f4efbce469e6bbe54f Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 15:43:11 +0800 Subject: [PATCH 176/254] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 67538a3895..ff20f736e0 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -51,3 +51,4 @@ - [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) +- [Sending Emails with Java](https://www.baeldung.com/java-email) From 1c92a79ef98154217b69070c9c2283d41e2b2187 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 16:16:41 +0800 Subject: [PATCH 177/254] Update README.md --- json/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/json/README.md b/json/README.md index c0ca4b00ef..3670b4b9ad 100644 --- a/json/README.md +++ b/json/README.md @@ -13,3 +13,4 @@ - [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key) - [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration) - [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) +- [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping) From bd2ce73a89df8499dc76a20f9bf46677981e07af Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 16:18:14 +0800 Subject: [PATCH 178/254] Update README.md --- core-kotlin/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 7d8001d667..95c57336b9 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -54,3 +54,4 @@ - [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) - [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl) - [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) +- [Inline Functions in Kotlin](https://www.baeldung.com/kotlin-inline-functions) From 9672f704bd954acecb35e7c3e44f40578cb948a5 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 16:20:36 +0800 Subject: [PATCH 179/254] Update README.md --- persistence-modules/hibernate-ogm/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/hibernate-ogm/README.md b/persistence-modules/hibernate-ogm/README.md index f4a5bb6c3b..508aa77b03 100644 --- a/persistence-modules/hibernate-ogm/README.md +++ b/persistence-modules/hibernate-ogm/README.md @@ -1,4 +1,4 @@ ## Relevant articles: -- [Guide to Hibernate OGM](http://www.baeldung.com/xxxx) +- [Guide to Hibernate OGM](https://www.baeldung.com/hibernate-ogm) From 4f03df3933a431913b9c91b4528d644f07b3fc6c Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 16:22:00 +0800 Subject: [PATCH 180/254] Update README.md --- spring-ehcache/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-ehcache/README.md b/spring-ehcache/README.md index 749441375e..ecf96cd7c7 100644 --- a/spring-ehcache/README.md +++ b/spring-ehcache/README.md @@ -3,5 +3,5 @@ A simple example of using ehcache with spring-boot. ### Relevant Articles: -- [Spring Boot Ehcache Example](http://www.baeldung.com/spring-ehcache) +- [Spring Boot Ehcache Example](https://www.baeldung.com/spring-boot-ehcache) From 82831830c033219d4c8dda0b172c2860f7f92352 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 16:24:08 +0800 Subject: [PATCH 181/254] Update README.md --- core-java-concurrency-advanced/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-concurrency-advanced/README.md b/core-java-concurrency-advanced/README.md index bcbec9d687..f48fd30c73 100644 --- a/core-java-concurrency-advanced/README.md +++ b/core-java-concurrency-advanced/README.md @@ -21,4 +21,5 @@ - [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch) - [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) - [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) -- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) \ No newline at end of file +- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) +- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters) From bdb05a0073747f1b671f6f42da1d1e23909aff35 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 11 Mar 2019 16:25:52 +0800 Subject: [PATCH 182/254] Update README.md --- jackson/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jackson/README.md b/jackson/README.md index 25194c7255..e9cf6f212c 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -38,3 +38,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Mapping Nested Values with Jackson](http://www.baeldung.com/jackson-nested-values) - [Convert XML to JSON Using Jackson](https://www.baeldung.com/jackson-convert-xml-json) - [Deserialize Immutable Objects with Jackson](https://www.baeldung.com/jackson-deserialize-immutable-objects) +- [Mapping a Dynamic JSON Object with Jackson](https://www.baeldung.com/jackson-mapping-dynamic-object) + From 6cd8c51b4d6182d098c4c0640f0b80759d5b8c86 Mon Sep 17 00:00:00 2001 From: dionisPrifti Date: Mon, 11 Mar 2019 13:43:15 +0100 Subject: [PATCH 183/254] BAEL-2709: Implementing example for Spring Boot Hibernate. (#6478) --- .../application/ExampleApplication.java | 14 +++++++ .../datasources/DataSourceBean.java | 21 ++++++++++ .../application/models/Book.java | 40 +++++++++++++++++++ .../repositories/BookRepository.java | 9 +++++ .../application/services/BookService.java | 19 +++++++++ .../src/main/resources/application.properties | 6 +++ .../tests/BookServiceUnitTest.java | 27 +++++++++++++ .../src/test/resources/application.properties | 2 +- .../src/test/resources/import_books.sql | 3 ++ 9 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/ExampleApplication.java create mode 100644 persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/datasources/DataSourceBean.java create mode 100644 persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/models/Book.java create mode 100644 persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/repositories/BookRepository.java create mode 100644 persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/services/BookService.java create mode 100644 persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java create mode 100644 persistence-modules/spring-boot-persistence/src/test/resources/import_books.sql diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/ExampleApplication.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/ExampleApplication.java new file mode 100644 index 0000000000..4b6a93ab8b --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/ExampleApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.springboothibernate.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(ExampleApplication.class, args); + } + +} + diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/datasources/DataSourceBean.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/datasources/DataSourceBean.java new file mode 100644 index 0000000000..54a0c4f077 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/datasources/DataSourceBean.java @@ -0,0 +1,21 @@ +package com.baeldung.springboothibernate.application.datasources; + +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.sql.DataSource; + +@Configuration +public class DataSourceBean { + + @Bean + public DataSource getDataSource() { + DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create(); + dataSourceBuilder.driverClassName("org.h2.Driver"); + dataSourceBuilder.url("jdbc:h2:mem:test"); + dataSourceBuilder.username("SA"); + dataSourceBuilder.password(""); + return dataSourceBuilder.build(); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/models/Book.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/models/Book.java new file mode 100644 index 0000000000..7562c072c7 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/models/Book.java @@ -0,0 +1,40 @@ +package com.baeldung.springboothibernate.application.models; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + @GeneratedValue + private Long id; + private String name; + + public Book() { + super(); + } + + public Book(Long id, String name) { + super(); + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/repositories/BookRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/repositories/BookRepository.java new file mode 100644 index 0000000000..3d5789fb4d --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/repositories/BookRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.springboothibernate.application.repositories; + +import com.baeldung.springboothibernate.application.models.Book; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface BookRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/services/BookService.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/services/BookService.java new file mode 100644 index 0000000000..e495045bab --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/services/BookService.java @@ -0,0 +1,19 @@ +package com.baeldung.springboothibernate.application.services; + +import com.baeldung.springboothibernate.application.models.Book; +import com.baeldung.springboothibernate.application.repositories.BookRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class BookService { + + @Autowired + private BookRepository bookRepository; + + public List list() { + return bookRepository.findAll(); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties index b0caf4a809..7b5a467a2b 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties @@ -3,3 +3,9 @@ spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1 spring.datasource.username = sa spring.datasource.password = spring.jpa.hibernate.ddl-auto = create + +# Enabling H2 Console +spring.h2.console.enabled=true + +# Uppercase Table Names +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java new file mode 100644 index 0000000000..fe8bb339a4 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.springboothibernate.application.tests; + +import com.baeldung.springboothibernate.application.models.Book; +import com.baeldung.springboothibernate.application.services.BookService; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class BookServiceUnitTest { + + @Autowired + private BookService bookService; + + @Test + public void test() { + List books = bookService.list(); + + Assert.assertEquals(books.size(), 3); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/test/resources/application.properties b/persistence-modules/spring-boot-persistence/src/test/resources/application.properties index a5c1d983cf..3a6470c8dc 100644 --- a/persistence-modules/spring-boot-persistence/src/test/resources/application.properties +++ b/persistence-modules/spring-boot-persistence/src/test/resources/application.properties @@ -12,5 +12,5 @@ hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory -spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql +spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql, import_books.sql spring.datasource.data=import_*_users.sql \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/test/resources/import_books.sql b/persistence-modules/spring-boot-persistence/src/test/resources/import_books.sql new file mode 100644 index 0000000000..8eaf972a00 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/test/resources/import_books.sql @@ -0,0 +1,3 @@ +insert into book values(1, 'The Tartar Steppe'); +insert into book values(2, 'Poem Strip'); +insert into book values(3, 'Restless Nights: Selected Stories of Dino Buzzati'); \ No newline at end of file From ef9df7f56365ff2687f40b71c44641b8675ac956 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Mon, 11 Mar 2019 19:47:41 +0530 Subject: [PATCH 184/254] BAEL-10957 Moved jhipster project from heavy profile to default-first and integration-lite-first profiles --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3e739daf22..f672d1efce 100644 --- a/pom.xml +++ b/pom.xml @@ -456,6 +456,7 @@ jersey JGit jgroups + jhipster jib jjwt jmeter @@ -924,7 +925,6 @@ core-kotlin-2 jenkins/hello-world - jhipster jws libraries @@ -1091,6 +1091,7 @@ jersey JGit jgroups + jhipster jib jjwt jmeter @@ -1409,7 +1410,6 @@ core-kotlin-2 jenkins/hello-world - jhipster jws libraries From b10782f89ea9979e60ed5cf7e52fada6f5cc3fd0 Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Mon, 11 Mar 2019 11:49:16 -0300 Subject: [PATCH 185/254] Building a web application with Spring Boot and Angular (#6496) * Initial Commit * Delete angularclient folder * Add spring-boot-angular module to root pom.xml * Update pom.xml * Update root pom.xml * Update root pom.xml --- pom.xml | 2 + .../angularclient/.angular-cli.json | 0 .../baeldung => }/angularclient/.editorconfig | 0 .../baeldung => }/angularclient/.gitignore | 0 .../com/baeldung => }/angularclient/README.md | 0 .../angularclient/e2e/app.e2e-spec.ts | 0 .../baeldung => }/angularclient/e2e/app.po.ts | 0 .../angularclient/e2e/tsconfig.e2e.json | 0 .../baeldung => }/angularclient/karma.conf.js | 0 .../angularclient/package-lock.json | 0 .../baeldung => }/angularclient/package.json | 0 .../angularclient/protractor.conf.js | 0 .../src/app/app-routing.module.ts | 0 .../angularclient/src/app/app.component.css | 0 .../angularclient/src/app/app.component.html | 0 .../src/app/app.component.spec.ts | 0 .../angularclient/src/app/app.component.ts | 0 .../angularclient/src/app/app.module.ts | 0 .../angularclient/src/app/model/user.ts | 0 .../src/app/service/user.service.spec.ts | 0 .../src/app/service/user.service.ts | 0 .../src/app/user-form/user-form.component.css | 0 .../app/user-form/user-form.component.html | 0 .../app/user-form/user-form.component.spec.ts | 0 .../src/app/user-form/user-form.component.ts | 0 .../src/app/user-list/user-list.component.css | 0 .../app/user-list/user-list.component.html | 0 .../app/user-list/user-list.component.spec.ts | 0 .../src/app/user-list/user-list.component.ts | 0 .../angularclient/src/assets/.gitkeep | 0 .../src/environments/environment.prod.ts | 0 .../src/environments/environment.ts | 0 .../angularclient/src/favicon.ico | Bin .../angularclient/src/index.html | 0 .../baeldung => }/angularclient/src/main.ts | 0 .../angularclient/src/polyfills.ts | 0 .../angularclient/src/styles.css | 0 .../angularclient/src/tsconfig.app.json | 0 .../angularclient/src/tsconfig.spec.json | 0 .../angularclient/src/typings.d.ts | 0 .../baeldung => }/angularclient/tsconfig.json | 0 .../baeldung => }/angularclient/tslint.json | 0 .../controllers/UserController.java | 2 +- .../repositories/UserRepository.java | 1 - .../src/main/java/com/baeldung/pom.xml | 49 ++++++++++++++++++ 45 files changed, 52 insertions(+), 2 deletions(-) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/.angular-cli.json (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/.editorconfig (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/.gitignore (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/README.md (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/e2e/app.e2e-spec.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/e2e/app.po.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/e2e/tsconfig.e2e.json (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/karma.conf.js (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/package-lock.json (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/package.json (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/protractor.conf.js (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/app-routing.module.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/app.component.css (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/app.component.html (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/app.component.spec.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/app.component.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/app.module.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/model/user.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/service/user.service.spec.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/service/user.service.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/user-form/user-form.component.css (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/user-form/user-form.component.html (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/user-form/user-form.component.spec.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/user-form/user-form.component.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/user-list/user-list.component.css (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/user-list/user-list.component.html (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/user-list/user-list.component.spec.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/app/user-list/user-list.component.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/assets/.gitkeep (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/environments/environment.prod.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/environments/environment.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/favicon.ico (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/index.html (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/main.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/polyfills.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/styles.css (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/tsconfig.app.json (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/tsconfig.spec.json (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/src/typings.d.ts (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/tsconfig.json (100%) rename spring-boot-angular/{src/main/java/com/baeldung => }/angularclient/tslint.json (100%) create mode 100644 spring-boot-angular/src/main/java/com/baeldung/pom.xml diff --git a/pom.xml b/pom.xml index 3e739daf22..594fd47d51 100644 --- a/pom.xml +++ b/pom.xml @@ -587,6 +587,7 @@ spring-boot spring-boot-admin + spring-boot-angular spring-boot-angular-ecommerce spring-boot-autoconfiguration spring-boot-bootstrap @@ -1218,6 +1219,7 @@ spring-boot spring-boot-admin + spring-boot-angular spring-boot-angular-ecommerce spring-boot-autoconfiguration spring-boot-bootstrap diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/.angular-cli.json b/spring-boot-angular/angularclient/.angular-cli.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/.angular-cli.json rename to spring-boot-angular/angularclient/.angular-cli.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/.editorconfig b/spring-boot-angular/angularclient/.editorconfig similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/.editorconfig rename to spring-boot-angular/angularclient/.editorconfig diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/.gitignore b/spring-boot-angular/angularclient/.gitignore similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/.gitignore rename to spring-boot-angular/angularclient/.gitignore diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/README.md b/spring-boot-angular/angularclient/README.md similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/README.md rename to spring-boot-angular/angularclient/README.md diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/app.e2e-spec.ts b/spring-boot-angular/angularclient/e2e/app.e2e-spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/app.e2e-spec.ts rename to spring-boot-angular/angularclient/e2e/app.e2e-spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/app.po.ts b/spring-boot-angular/angularclient/e2e/app.po.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/app.po.ts rename to spring-boot-angular/angularclient/e2e/app.po.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/tsconfig.e2e.json b/spring-boot-angular/angularclient/e2e/tsconfig.e2e.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/tsconfig.e2e.json rename to spring-boot-angular/angularclient/e2e/tsconfig.e2e.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/karma.conf.js b/spring-boot-angular/angularclient/karma.conf.js similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/karma.conf.js rename to spring-boot-angular/angularclient/karma.conf.js diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/package-lock.json b/spring-boot-angular/angularclient/package-lock.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/package-lock.json rename to spring-boot-angular/angularclient/package-lock.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/package.json b/spring-boot-angular/angularclient/package.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/package.json rename to spring-boot-angular/angularclient/package.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/protractor.conf.js b/spring-boot-angular/angularclient/protractor.conf.js similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/protractor.conf.js rename to spring-boot-angular/angularclient/protractor.conf.js diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app-routing.module.ts b/spring-boot-angular/angularclient/src/app/app-routing.module.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app-routing.module.ts rename to spring-boot-angular/angularclient/src/app/app-routing.module.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.css b/spring-boot-angular/angularclient/src/app/app.component.css similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.css rename to spring-boot-angular/angularclient/src/app/app.component.css diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.html b/spring-boot-angular/angularclient/src/app/app.component.html similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.html rename to spring-boot-angular/angularclient/src/app/app.component.html diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.spec.ts b/spring-boot-angular/angularclient/src/app/app.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.spec.ts rename to spring-boot-angular/angularclient/src/app/app.component.spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.ts b/spring-boot-angular/angularclient/src/app/app.component.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.ts rename to spring-boot-angular/angularclient/src/app/app.component.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.module.ts b/spring-boot-angular/angularclient/src/app/app.module.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.module.ts rename to spring-boot-angular/angularclient/src/app/app.module.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/model/user.ts b/spring-boot-angular/angularclient/src/app/model/user.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/model/user.ts rename to spring-boot-angular/angularclient/src/app/model/user.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/service/user.service.spec.ts b/spring-boot-angular/angularclient/src/app/service/user.service.spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/service/user.service.spec.ts rename to spring-boot-angular/angularclient/src/app/service/user.service.spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/service/user.service.ts b/spring-boot-angular/angularclient/src/app/service/user.service.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/service/user.service.ts rename to spring-boot-angular/angularclient/src/app/service/user.service.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.css b/spring-boot-angular/angularclient/src/app/user-form/user-form.component.css similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.css rename to spring-boot-angular/angularclient/src/app/user-form/user-form.component.css diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.html b/spring-boot-angular/angularclient/src/app/user-form/user-form.component.html similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.html rename to spring-boot-angular/angularclient/src/app/user-form/user-form.component.html diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.spec.ts b/spring-boot-angular/angularclient/src/app/user-form/user-form.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.spec.ts rename to spring-boot-angular/angularclient/src/app/user-form/user-form.component.spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.ts b/spring-boot-angular/angularclient/src/app/user-form/user-form.component.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.ts rename to spring-boot-angular/angularclient/src/app/user-form/user-form.component.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.css b/spring-boot-angular/angularclient/src/app/user-list/user-list.component.css similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.css rename to spring-boot-angular/angularclient/src/app/user-list/user-list.component.css diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.html b/spring-boot-angular/angularclient/src/app/user-list/user-list.component.html similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.html rename to spring-boot-angular/angularclient/src/app/user-list/user-list.component.html diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.spec.ts b/spring-boot-angular/angularclient/src/app/user-list/user-list.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.spec.ts rename to spring-boot-angular/angularclient/src/app/user-list/user-list.component.spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.ts b/spring-boot-angular/angularclient/src/app/user-list/user-list.component.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.ts rename to spring-boot-angular/angularclient/src/app/user-list/user-list.component.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/assets/.gitkeep b/spring-boot-angular/angularclient/src/assets/.gitkeep similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/assets/.gitkeep rename to spring-boot-angular/angularclient/src/assets/.gitkeep diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/environments/environment.prod.ts b/spring-boot-angular/angularclient/src/environments/environment.prod.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/environments/environment.prod.ts rename to spring-boot-angular/angularclient/src/environments/environment.prod.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/environments/environment.ts b/spring-boot-angular/angularclient/src/environments/environment.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/environments/environment.ts rename to spring-boot-angular/angularclient/src/environments/environment.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/favicon.ico b/spring-boot-angular/angularclient/src/favicon.ico similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/favicon.ico rename to spring-boot-angular/angularclient/src/favicon.ico diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/index.html b/spring-boot-angular/angularclient/src/index.html similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/index.html rename to spring-boot-angular/angularclient/src/index.html diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/main.ts b/spring-boot-angular/angularclient/src/main.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/main.ts rename to spring-boot-angular/angularclient/src/main.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/polyfills.ts b/spring-boot-angular/angularclient/src/polyfills.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/polyfills.ts rename to spring-boot-angular/angularclient/src/polyfills.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/styles.css b/spring-boot-angular/angularclient/src/styles.css similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/styles.css rename to spring-boot-angular/angularclient/src/styles.css diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/tsconfig.app.json b/spring-boot-angular/angularclient/src/tsconfig.app.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/tsconfig.app.json rename to spring-boot-angular/angularclient/src/tsconfig.app.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/tsconfig.spec.json b/spring-boot-angular/angularclient/src/tsconfig.spec.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/tsconfig.spec.json rename to spring-boot-angular/angularclient/src/tsconfig.spec.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/typings.d.ts b/spring-boot-angular/angularclient/src/typings.d.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/typings.d.ts rename to spring-boot-angular/angularclient/src/typings.d.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/tsconfig.json b/spring-boot-angular/angularclient/tsconfig.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/tsconfig.json rename to spring-boot-angular/angularclient/tsconfig.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/tslint.json b/spring-boot-angular/angularclient/tslint.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/tslint.json rename to spring-boot-angular/angularclient/tslint.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java b/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java index c101ed771f..14c90d5b10 100644 --- a/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java +++ b/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java @@ -1,6 +1,6 @@ package com.baeldung.application.controllers; -import com.application.entities.User; +import com.baeldung.application.entities.User; import com.baeldung.application.repositories.UserRepository; import java.util.List; import org.springframework.web.bind.annotation.CrossOrigin; diff --git a/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java b/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java index f8ef5a4c0c..5a81cadcbe 100644 --- a/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java +++ b/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java @@ -6,5 +6,4 @@ import org.springframework.stereotype.Repository; import org.springframework.web.bind.annotation.CrossOrigin; @Repository -@CrossOrigin(origins = "http://localhost:4200") public interface UserRepository extends CrudRepository{} diff --git a/spring-boot-angular/src/main/java/com/baeldung/pom.xml b/spring-boot-angular/src/main/java/com/baeldung/pom.xml new file mode 100644 index 0000000000..d4ebc870b4 --- /dev/null +++ b/spring-boot-angular/src/main/java/com/baeldung/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + com.baeldung.springbootangular + spring-boot-angular + 1.0 + jar + Spring Boot Angular Application + + org.springframework.boot + spring-boot-starter-parent + 2.1.3.RELEASE + + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file From 9f2f10dfa2a9705ba052b21091e78bc771349252 Mon Sep 17 00:00:00 2001 From: TINO Date: Mon, 11 Mar 2019 22:23:46 +0300 Subject: [PATCH 186/254] BAEL - 1060 Review comments incorporated --- .../baeldung/rxjava/RxJavaHooksUnitTest.java | 410 +++++++++--------- 1 file changed, 193 insertions(+), 217 deletions(-) diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java index e31838448b..79b80f71ab 100644 --- a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java @@ -1,5 +1,8 @@ package com.baeldung.rxjava; +import static org.junit.Assert.assertTrue; + +import org.junit.After; import org.junit.Test; import io.reactivex.Completable; @@ -14,316 +17,289 @@ import io.reactivex.schedulers.Schedulers; public class RxJavaHooksUnitTest { + private boolean initHookCalled = false; + private boolean hookCalled = false; + + @Test + public void givenObservable_whenError_shouldExecuteTheHook() { + RxJavaPlugins.setErrorHandler(throwable -> { + hookCalled = true; + }); + + Observable.error(new IllegalStateException()) + .subscribe(); + assertTrue(hookCalled); + } + @Test public void givenCompletable_whenAssembled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnCompletableAssembly(completable -> { - System.out.println("Assembling Completable"); - return completable; - }); - Completable.fromSingle(Single.just(1)); - } finally { - RxJavaPlugins.reset(); - } + + RxJavaPlugins.setOnCompletableAssembly(completable -> { + hookCalled = true; + return completable; + }); + Completable.fromSingle(Single.just(1)); + assertTrue(hookCalled); } @Test public void givenCompletable_whenSubscribed_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnCompletableSubscribe((completable, observer) -> { - System.out.println("Subscribing to Completable"); - return observer; - }); - Completable.fromSingle(Single.just(1)) - .test(true); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnCompletableSubscribe((completable, observer) -> { + hookCalled = true; + return observer; + }); + + Completable.fromSingle(Single.just(1)) + .test(); + assertTrue(hookCalled); } @Test public void givenObservable_whenAssembled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnObservableAssembly(observable -> { - System.out.println("Assembling Observable"); - return observable; - }); - Observable.range(1, 10); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnObservableAssembly(observable -> { + hookCalled = true; + return observable; + }); + + Observable.range(1, 10); + assertTrue(hookCalled); } @Test public void givenObservable_whenSubscribed_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnObservableSubscribe((observable, observer) -> { - System.out.println("Suscribing to Observable"); - return observer; - }); - Observable.range(1, 10) - .test(true); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnObservableSubscribe((observable, observer) -> { + hookCalled = true; + return observer; + }); + + Observable.range(1, 10) + .test(); + assertTrue(hookCalled); } @Test public void givenConnectableObservable_whenAssembled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnConnectableObservableAssembly(connectableObservable -> { - System.out.println("Assembling ConnectableObservable"); - return connectableObservable; - }); - ConnectableObservable.range(1, 10) - .publish() - .connect(); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnConnectableObservableAssembly(connectableObservable -> { + hookCalled = true; + return connectableObservable; + }); + + ConnectableObservable.range(1, 10) + .publish() + .connect(); + assertTrue(hookCalled); } @Test public void givenFlowable_whenAssembled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnFlowableAssembly(flowable -> { - System.out.println("Assembling Flowable"); - return flowable; - }); - Flowable.range(1, 10); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnFlowableAssembly(flowable -> { + hookCalled = true; + return flowable; + }); + + Flowable.range(1, 10); + assertTrue(hookCalled); } @Test public void givenFlowable_whenSubscribed_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnFlowableSubscribe((flowable, observer) -> { - System.out.println("Suscribing to Flowable"); - return observer; - }); - Flowable.range(1, 10) - .test(); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnFlowableSubscribe((flowable, observer) -> { + hookCalled = true; + return observer; + }); + + Flowable.range(1, 10) + .test(); + assertTrue(hookCalled); } @Test public void givenConnectableFlowable_whenAssembled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnConnectableFlowableAssembly(connectableFlowable -> { - System.out.println("Assembling ConnectableFlowable"); - return connectableFlowable; - }); - ConnectableFlowable.range(1, 10) - .publish() - .connect(); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnConnectableFlowableAssembly(connectableFlowable -> { + hookCalled = true; + return connectableFlowable; + }); + + ConnectableFlowable.range(1, 10) + .publish() + .connect(); + assertTrue(hookCalled); } @Test public void givenParallel_whenAssembled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnParallelAssembly(parallelFlowable -> { - System.out.println("Assembling ParallelFlowable"); - return parallelFlowable; - }); - Flowable.range(1, 10) - .parallel(); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnParallelAssembly(parallelFlowable -> { + hookCalled = true; + return parallelFlowable; + }); + + Flowable.range(1, 10) + .parallel(); + assertTrue(hookCalled); } @Test public void givenMaybe_whenAssembled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnMaybeAssembly(maybe -> { - System.out.println("Assembling Maybe"); - return maybe; - }); - Maybe.just(1); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnMaybeAssembly(maybe -> { + hookCalled = true; + return maybe; + }); + + Maybe.just(1); + assertTrue(hookCalled); } @Test public void givenMaybe_whenSubscribed_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnMaybeSubscribe((maybe, observer) -> { - System.out.println("Suscribing to Maybe"); - return observer; - }); - Maybe.just(1) - .test(); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnMaybeSubscribe((maybe, observer) -> { + hookCalled = true; + return observer; + }); + + Maybe.just(1) + .test(); + assertTrue(hookCalled); } @Test public void givenSingle_whenAssembled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnSingleAssembly(single -> { - System.out.println("Assembling Single"); - return single; - }); - Single.just(1); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setOnSingleAssembly(single -> { + hookCalled = true; + return single; + }); + + Single.just(1); + assertTrue(hookCalled); } @Test public void givenSingle_whenSubscribed_shouldExecuteTheHook() { - try { - RxJavaPlugins.setOnSingleSubscribe((single, observer) -> { - System.out.println("Suscribing to Single"); - return observer; - }); + RxJavaPlugins.setOnSingleSubscribe((single, observer) -> { + hookCalled = true; + return observer; + }); - Single.just(1) - .test(); - } finally { - RxJavaPlugins.reset(); - } + Single.just(1) + .test(); + assertTrue(hookCalled); } @Test public void givenAnyScheduler_whenCalled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setScheduleHandler((runnable) -> { - System.out.println("Executing Scheduler"); - return runnable; - }); - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.single()) - .test(); + RxJavaPlugins.setScheduleHandler((runnable) -> { + hookCalled = true; + return runnable; + }); - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.computation()) - .test(); - } finally { - RxJavaPlugins.reset(); - } + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + hookCalled = false; + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + assertTrue(hookCalled); } @Test public void givenComputationScheduler_whenCalled_shouldExecuteTheHooks() { - try { - RxJavaPlugins.setInitComputationSchedulerHandler((scheduler) -> { - System.out.println("Initializing Computation Scheduler"); - return scheduler.call(); - }); - RxJavaPlugins.setComputationSchedulerHandler((scheduler) -> { - System.out.println("Executing Computation Scheduler"); - return scheduler; - }); - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.computation()) - .test(); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setInitComputationSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + RxJavaPlugins.setComputationSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + assertTrue(hookCalled && initHookCalled); } @Test public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() { - try { - RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { - System.out.println("Initializing IO Scheduler"); - return scheduler.call(); - }); - RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { - System.out.println("Executing IO Scheduler"); - return scheduler; - }); + RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.io()) - .test(); - } finally { - RxJavaPlugins.reset(); - } + RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.io()) + .test(); + assertTrue(hookCalled && initHookCalled); } @Test public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() { - try { - RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { - System.out.println("Initializing newThread Scheduler"); - return scheduler.call(); - }); - RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { - System.out.println("Executing newThread Scheduler"); - return scheduler; - }); + RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); - Observable.range(1, 15) - .map(v -> v * 2) - .subscribeOn(Schedulers.newThread()) - .test(); + RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); - } finally { - RxJavaPlugins.reset(); - } + Observable.range(1, 15) + .map(v -> v * 2) + .subscribeOn(Schedulers.newThread()) + .test(); + assertTrue(hookCalled && initHookCalled); } @Test public void givenSingleScheduler_whenCalled_shouldExecuteTheHooks() { - try { - RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { - System.out.println("Initializing Single Scheduler"); - return scheduler.call(); - }); - RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { - System.out.println("Executing Single Scheduler"); - return scheduler; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.single()) - .test(); - - } finally { - RxJavaPlugins.reset(); - } - } - - @Test - public void givenObservable_whenError_shouldExecuteTheHook() { - RxJavaPlugins.setErrorHandler(throwable -> { - System.out.println("Handling error" + throwable.getCause()); + RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); }); - Observable.error(new IllegalStateException()) - .subscribe(); + RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + assertTrue(hookCalled && initHookCalled); + + } + + @After + public void reset() { + initHookCalled = false; + hookCalled = false; + RxJavaPlugins.reset(); } } From 63b652270afcd5a09a0d21ac4eb175df1424e5a8 Mon Sep 17 00:00:00 2001 From: Loredana Date: Mon, 11 Mar 2019 23:02:10 +0200 Subject: [PATCH 187/254] add new core-java-os module --- core-java-9/README.md | 2 - core-java-os/.gitignore | 26 ++++++ core-java-os/README.md | 8 ++ core-java-os/pom.xml | 82 +++++++++++++++++++ .../baeldung/java9/process/ChildProcess.java | 0 .../java9/process/OutputStreamExample.java | 0 .../process/ProcessCompilationError.java | 2 +- .../java9/process/ProcessUnderstanding.java | 0 .../baeldung/java9/process/ProcessUtils.java | 0 .../baeldung/java9/process/ServiceMain.java | 0 core-java-os/src/main/resources/logback.xml | 13 +++ .../ProcessAPIEnhancementsUnitTest.java | 16 ++-- .../java9/process/ProcessApiUnitTest.java | 14 ++-- .../process/ProcessUnderstandingUnitTest.java | 2 +- .../ProcessBuilderUnitTest.java | 0 core-java-os/src/test/resources/.gitignore | 13 +++ pom.xml | 2 + 17 files changed, 161 insertions(+), 19 deletions(-) create mode 100644 core-java-os/.gitignore create mode 100644 core-java-os/README.md create mode 100644 core-java-os/pom.xml rename {core-java-9 => core-java-os}/src/main/java/com/baeldung/java9/process/ChildProcess.java (100%) rename {core-java-9 => core-java-os}/src/main/java/com/baeldung/java9/process/OutputStreamExample.java (100%) rename {core-java-9 => core-java-os}/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java (87%) rename {core-java-9 => core-java-os}/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java (100%) rename {core-java-9 => core-java-os}/src/main/java/com/baeldung/java9/process/ProcessUtils.java (100%) rename {core-java-9 => core-java-os}/src/main/java/com/baeldung/java9/process/ServiceMain.java (100%) create mode 100644 core-java-os/src/main/resources/logback.xml rename {core-java-9 => core-java-os}/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java (89%) rename {core-java-9 => core-java-os}/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java (85%) rename core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java => core-java-os/src/test/java/com/baeldung/java9/process/ProcessUnderstandingUnitTest.java (99%) rename {core-java-9 => core-java-os}/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java (100%) create mode 100644 core-java-os/src/test/resources/.gitignore diff --git a/core-java-9/README.md b/core-java-9/README.md index 224306db19..fb7f69dc42 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -9,7 +9,6 @@ - [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods) - [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) - [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture) -- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) - [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api) - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) - [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional) @@ -25,7 +24,6 @@ - [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) -- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) - [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) - [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar) - [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation) diff --git a/core-java-os/.gitignore b/core-java-os/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-os/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-os/README.md b/core-java-os/README.md new file mode 100644 index 0000000000..90e1d29a58 --- /dev/null +++ b/core-java-os/README.md @@ -0,0 +1,8 @@ +========= + +This module uses Java 9, so make sure to have the JDK 9 installed to run it. + +## +### Relevant Articles: +- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) +- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) diff --git a/core-java-os/pom.xml b/core-java-os/pom.xml new file mode 100644 index 0000000000..c9097cb554 --- /dev/null +++ b/core-java-os/pom.xml @@ -0,0 +1,82 @@ + + 4.0.0 + com.baeldung + core-java-os + 0.1.0-SNAPSHOT + core-java-os + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-os + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + 3.5 + 4.1 + 4.01 + + + 3.6.1 + 1.8.9 + 1.9 + 1.9 + 25.1-jre + + diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java b/core-java-os/src/main/java/com/baeldung/java9/process/ChildProcess.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ChildProcess.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java b/core-java-os/src/main/java/com/baeldung/java9/process/OutputStreamExample.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java rename to core-java-os/src/main/java/com/baeldung/java9/process/OutputStreamExample.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java b/core-java-os/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java similarity index 87% rename from core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java index 8b6ae0b441..73eacddc4c 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java +++ b/core-java-os/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java @@ -3,5 +3,5 @@ package com.baeldung.java9.process; public class ProcessCompilationError { //This method has been written to generate error to display //how process errorStream() can consume error - public static void(); + //public static void(); } diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java b/core-java-os/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java b/core-java-os/src/main/java/com/baeldung/java9/process/ProcessUtils.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ProcessUtils.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-os/src/main/java/com/baeldung/java9/process/ServiceMain.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ServiceMain.java diff --git a/core-java-os/src/main/resources/logback.xml b/core-java-os/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-os/src/main/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/core-java-9/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java similarity index 89% rename from core-java-9/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java rename to core-java-os/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java index 9a227a9c8f..8cefceef1d 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java +++ b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java @@ -18,13 +18,13 @@ import org.slf4j.LoggerFactory; public class ProcessAPIEnhancementsUnitTest { - Logger log = LoggerFactory.getLogger(ProcessAPIEnhancementsTest.class); + Logger log = LoggerFactory.getLogger(ProcessAPIEnhancementsUnitTest.class); @Test public void givenCurrentProcess_whenInvokeGetInfo_thenSuccess() throws IOException { ProcessHandle processHandle = ProcessHandle.current(); ProcessHandle.Info processInfo = processHandle.info(); - assertNotNull(processHandle.getPid()); + assertNotNull(processHandle.pid()); assertEquals(false, processInfo.arguments() .isPresent()); assertEquals(true, processInfo.command() @@ -51,7 +51,7 @@ public class ProcessAPIEnhancementsUnitTest { .start(); ProcessHandle processHandle = process.toHandle(); ProcessHandle.Info processInfo = processHandle.info(); - assertNotNull(processHandle.getPid()); + assertNotNull(processHandle.pid()); assertEquals(false, processInfo.arguments() .isPresent()); assertEquals(true, processInfo.command() @@ -72,7 +72,7 @@ public class ProcessAPIEnhancementsUnitTest { Stream liveProcesses = ProcessHandle.allProcesses(); liveProcesses.filter(ProcessHandle::isAlive) .forEach(ph -> { - assertNotNull(ph.getPid()); + assertNotNull(ph.pid()); assertEquals(true, ph.info() .command() .isPresent()); @@ -102,12 +102,12 @@ public class ProcessAPIEnhancementsUnitTest { Stream children = ProcessHandle.current() .children(); children.filter(ProcessHandle::isAlive) - .forEach(ph -> log.info("PID: {}, Cmd: {}", ph.getPid(), ph.info() + .forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info() .command())); Stream descendants = ProcessHandle.current() .descendants(); descendants.filter(ProcessHandle::isAlive) - .forEach(ph -> log.info("PID: {}, Cmd: {}", ph.getPid(), ph.info() + .forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info() .command())); } @@ -121,12 +121,12 @@ public class ProcessAPIEnhancementsUnitTest { .start(); ProcessHandle processHandle = process.toHandle(); - log.info("PID: {} has started", processHandle.getPid()); + log.info("PID: {} has started", processHandle.pid()); CompletableFuture onProcessExit = processHandle.onExit(); onProcessExit.get(); assertEquals(false, processHandle.isAlive()); onProcessExit.thenAccept(ph -> { - log.info("PID: {} has stopped", ph.getPid()); + log.info("PID: {} has stopped", ph.pid()); }); } diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java similarity index 85% rename from core-java-9/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java rename to core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java index e125f10da7..8bdf8cb09f 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java +++ b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java @@ -30,7 +30,7 @@ public class ProcessApiUnitTest { @Test public void processInfoExample() throws NoSuchAlgorithmException { ProcessHandle self = ProcessHandle.current(); - long PID = self.getPid(); + long PID = self.pid(); ProcessHandle.Info procInfo = self.info(); Optional args = procInfo.arguments(); Optional cmd = procInfo.commandLine(); @@ -45,7 +45,7 @@ public class ProcessApiUnitTest { Stream allProc = ProcessHandle.current().children(); allProc.forEach(p -> { - System.out.println("Proc " + p.getPid()); + System.out.println("Proc " + p.pid()); }); } @@ -54,7 +54,7 @@ public class ProcessApiUnitTest { public void createAndDestroyProcess() throws IOException, InterruptedException { int numberOfChildProcesses = 5; for (int i = 0; i < numberOfChildProcesses; i++) { - createNewJVM(ServiceMain.class, i).getPid(); + createNewJVM(ServiceMain.class, i).pid(); } Stream childProc = ProcessHandle.current().children(); @@ -62,10 +62,10 @@ public class ProcessApiUnitTest { childProc = ProcessHandle.current().children(); childProc.forEach(processHandle -> { - assertTrue("Process " + processHandle.getPid() + " should be alive!", processHandle.isAlive()); + assertTrue("Process " + processHandle.pid() + " should be alive!", processHandle.isAlive()); CompletableFuture onProcExit = processHandle.onExit(); onProcExit.thenAccept(procHandle -> { - System.out.println("Process with PID " + procHandle.getPid() + " has stopped"); + System.out.println("Process with PID " + procHandle.pid() + " has stopped"); }); }); @@ -73,14 +73,14 @@ public class ProcessApiUnitTest { childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { - assertTrue("Could not kill process " + procHandle.getPid(), procHandle.destroy()); + assertTrue("Could not kill process " + procHandle.pid(), procHandle.destroy()); }); Thread.sleep(5000); childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { - assertFalse("Process " + procHandle.getPid() + " should not be alive!", procHandle.isAlive()); + assertFalse("Process " + procHandle.pid() + " should not be alive!", procHandle.isAlive()); }); } diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessUnderstandingUnitTest.java similarity index 99% rename from core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java rename to core-java-os/src/test/java/com/baeldung/java9/process/ProcessUnderstandingUnitTest.java index 2c5525b9ed..6ad07c5c3a 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java +++ b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessUnderstandingUnitTest.java @@ -14,7 +14,7 @@ import java.lang.Integer; import org.junit.jupiter.api.Test; -class ProcessUnderstandingTest { +class ProcessUnderstandingUnitTest { @Test public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException { diff --git a/core-java-9/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java b/core-java-os/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java similarity index 100% rename from core-java-9/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java rename to core-java-os/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java diff --git a/core-java-os/src/test/resources/.gitignore b/core-java-os/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-os/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/pom.xml b/pom.xml index 3e739daf22..e9aef8bf35 100644 --- a/pom.xml +++ b/pom.xml @@ -379,6 +379,7 @@ core-java-8 + core-java-arrays core-java-collections core-java-collections-list @@ -1015,6 +1016,7 @@ core-java-8 + core-java-arrays core-java-collections core-java-collections-list From 4a0810acc8ce940488c692b1c41a27be89329881 Mon Sep 17 00:00:00 2001 From: Surapaneni Venkata Kiran Date: Mon, 11 Mar 2019 23:49:24 -0400 Subject: [PATCH 188/254] BAEL-2575 : Disable auto configuration of data source (#6513) --- .../disabledatasource/application/Application.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/disabledatasource/application/Application.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/disabledatasource/application/Application.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/disabledatasource/application/Application.java new file mode 100644 index 0000000000..79273ba141 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/disabledatasource/application/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.disabledatasource.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; + +@SpringBootApplication(exclude=DataSourceAutoConfiguration.class) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} From 51cc4612750c2ec51c4538f1b26482285cb868ee Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Tue, 12 Mar 2019 15:30:51 +0800 Subject: [PATCH 189/254] Update README.md --- persistence-modules/hibernate-ogm/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/hibernate-ogm/README.md b/persistence-modules/hibernate-ogm/README.md index 508aa77b03..df99cce129 100644 --- a/persistence-modules/hibernate-ogm/README.md +++ b/persistence-modules/hibernate-ogm/README.md @@ -1,4 +1,4 @@ ## Relevant articles: -- [Guide to Hibernate OGM](https://www.baeldung.com/hibernate-ogm) +- [A Guide to Hibernate OGM](https://www.baeldung.com/hibernate-ogm) From 527e3440acfae883ded0bca0c47ae0a7ca0460a6 Mon Sep 17 00:00:00 2001 From: Sumeet Gajbhar Date: Tue, 12 Mar 2019 22:11:02 +0530 Subject: [PATCH 190/254] BAEL-2520 code moved to java-jpa module (#6525) * BAEL-2520 code changes done * BAEL-2520 moved code to java-jpa module * BAEL-2520 moved code to java-jpa module --- .../baeldung/jpa/criteria/entity/Item.java | 49 +++++ .../repository/CustomItemRepository.java | 12 ++ .../impl/CustomItemRepositoryImpl.java | 77 +++++++ .../main/resources/META-INF/persistence.xml | 201 ++++++++++-------- .../CustomItemRepositoryIntegrationTest.java | 44 ++++ .../java-jpa/src/test/resources/item.sql | 4 + .../repositories/CustomItemRepository.java | 5 - .../impl/CustomItemRepositoryImpl.java | 55 ----- .../CustomItemRepositoryIntegrationTest.java | 94 -------- 9 files changed, 297 insertions(+), 244 deletions(-) create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/entity/Item.java create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/CustomItemRepository.java create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryImpl.java create mode 100644 persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryIntegrationTest.java create mode 100644 persistence-modules/java-jpa/src/test/resources/item.sql delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/entity/Item.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/entity/Item.java new file mode 100644 index 0000000000..64ef46f265 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/entity/Item.java @@ -0,0 +1,49 @@ +package com.baeldung.jpa.criteria.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Table(name = "item") +@Entity +public class Item { + + @Id + private Long id; + private String color; + private String grade; + private String name; + + public String getColor() { + return color; + } + + public String getGrade() { + return grade; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public void setColor(String color) { + this.color = color; + } + + public void setGrade(String grade) { + this.grade = grade; + } + + public void setId(Long id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/CustomItemRepository.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/CustomItemRepository.java new file mode 100644 index 0000000000..c55dc4a592 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/CustomItemRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.jpa.criteria.repository; + +import java.util.List; + +import com.baeldung.jpa.criteria.entity.Item; + +public interface CustomItemRepository { + + List findItemsByColorAndGrade(); + + List findItemByColorOrGrade(); +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryImpl.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryImpl.java new file mode 100644 index 0000000000..bf1d3eed0b --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryImpl.java @@ -0,0 +1,77 @@ +package com.baeldung.jpa.criteria.repository.impl; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import com.baeldung.jpa.criteria.entity.Item; +import com.baeldung.jpa.criteria.repository.CustomItemRepository; + +public class CustomItemRepositoryImpl implements CustomItemRepository { + + private EntityManager entityManager; + + public CustomItemRepositoryImpl() { + super(); + EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-criteria"); + entityManager = factory.createEntityManager(); + } + + @Override + public List findItemsByColorAndGrade() { + + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); + Root itemRoot = criteriaQuery.from(Item.class); + + Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); + Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); + Predicate predicateForColor = criteriaBuilder.or(predicateForBlueColor, predicateForRedColor); + + Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "A"); + Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); + Predicate predicateForGrade = criteriaBuilder.or(predicateForGradeA, predicateForGradeB); + + // final search filter + Predicate finalPredicate = criteriaBuilder.and(predicateForColor, predicateForGrade); + + criteriaQuery.where(finalPredicate); + + List items = entityManager.createQuery(criteriaQuery) + .getResultList(); + return items; + } + + @Override + public List findItemByColorOrGrade() { + + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); + Root itemRoot = criteriaQuery.from(Item.class); + + Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); + Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "D"); + Predicate predicateForBlueColorAndGradeA = criteriaBuilder.and(predicateForBlueColor, predicateForGradeA); + + Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); + Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); + Predicate predicateForRedColorAndGradeB = criteriaBuilder.and(predicateForRedColor, predicateForGradeB); + + // final search filter + Predicate finalPredicate = criteriaBuilder.or(predicateForBlueColorAndGradeA, predicateForRedColorAndGradeB); + + criteriaQuery.where(finalPredicate); + + List items = entityManager.createQuery(criteriaQuery) + .getResultList(); + return items; + } +} diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 8592fce533..6382f329c1 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -1,91 +1,112 @@ - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.sqlresultsetmapping.ScheduledDay - com.baeldung.sqlresultsetmapping.Employee - true - - - - - - - - - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.stringcast.Message - true - - - - - - - - - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.model.Car - true - - - - - - - - - - - - com.baeldung.jpa.entitygraph.model.Post - com.baeldung.jpa.entitygraph.model.User - com.baeldung.jpa.entitygraph.model.Comment - true - - - - - - - - - - - - - org.eclipse.persistence.jpa.PersistenceProvider - com.baeldung.jpa.datetime.JPA22DateTimeEntity - true - - - - - - - - - - - - - - + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.sqlresultsetmapping.ScheduledDay + com.baeldung.sqlresultsetmapping.Employee + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.stringcast.Message + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.model.Car + true + + + + + + + + + + + + com.baeldung.jpa.entitygraph.model.Post + com.baeldung.jpa.entitygraph.model.User + com.baeldung.jpa.entitygraph.model.Comment + true + + + + + + + + + + + + + org.eclipse.persistence.jpa.PersistenceProvider + com.baeldung.jpa.datetime.JPA22DateTimeEntity + true + + + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.criteria.entity.Item + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryIntegrationTest.java new file mode 100644 index 0000000000..169fb44618 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.jpa.criteria.repository.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.List; + +import org.junit.Test; + +import com.baeldung.jpa.criteria.entity.Item; +import com.baeldung.jpa.criteria.repository.CustomItemRepository; + +public class CustomItemRepositoryIntegrationTest { + + CustomItemRepository customItemRepository = new CustomItemRepositoryImpl(); + + @Test + public void givenItems_whenFindItemsByColorAndGrade_thenReturnItems() { + + List items = customItemRepository.findItemsByColorAndGrade(); + + assertFalse("No items found", items.isEmpty()); + assertEquals("There should be only one item", 1, items.size()); + + Item item = items.get(0); + + assertEquals("this item do not have blue color", "blue", item.getColor()); + assertEquals("this item does not belong to A grade", "A", item.getGrade()); + } + + @Test + public void givenItems_whenFindItemByColorOrGrade_thenReturnItems() { + + List items = customItemRepository.findItemByColorOrGrade(); + + assertFalse("No items found", items.isEmpty()); + assertEquals("There should be only one item", 1, items.size()); + + Item item = items.get(0); + + assertEquals("this item do not have red color", "red", item.getColor()); + assertEquals("this item does not belong to D grade", "D", item.getGrade()); + } +} diff --git a/persistence-modules/java-jpa/src/test/resources/item.sql b/persistence-modules/java-jpa/src/test/resources/item.sql new file mode 100644 index 0000000000..faf50f6829 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/resources/item.sql @@ -0,0 +1,4 @@ +insert into item(id,grade,color) values (10,'C','blue'); +insert into item(id,grade,color) values (11,'C','red'); +insert into item(id,grade,color) values (12,'A','blue'); +insert into item(id,grade,color) values (13,'D','red'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java index 4299f9e3bb..f5b94e507c 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java @@ -1,7 +1,5 @@ package com.baeldung.dao.repositories; -import java.util.List; - import org.springframework.stereotype.Repository; import com.baeldung.domain.Item; @@ -15,7 +13,4 @@ public interface CustomItemRepository { void findThenDelete(Long id); - List findItemsByColorAndGrade(); - - List findItemByColorOrGrade(); } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java index 9791cb0aa7..5538448c49 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java @@ -1,12 +1,6 @@ package com.baeldung.dao.repositories.impl; -import java.util.List; - import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @@ -36,53 +30,4 @@ public class CustomItemRepositoryImpl implements CustomItemRepository { entityManager.remove(item); } - @Override - public List findItemsByColorAndGrade() { - - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); - Root itemRoot = criteriaQuery.from(Item.class); - - Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); - Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); - Predicate predicateForColor = criteriaBuilder.or(predicateForBlueColor, predicateForRedColor); - - Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "A"); - Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); - Predicate predicateForGrade = criteriaBuilder.or(predicateForGradeA, predicateForGradeB); - - // final search filter - Predicate finalPredicate = criteriaBuilder.and(predicateForColor, predicateForGrade); - - criteriaQuery.where(finalPredicate); - - List items = entityManager.createQuery(criteriaQuery) - .getResultList(); - return items; - } - - @Override - public List findItemByColorOrGrade() { - - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); - Root itemRoot = criteriaQuery.from(Item.class); - - Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); - Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "D"); - Predicate predicateForBlueColorAndGradeA = criteriaBuilder.and(predicateForBlueColor, predicateForGradeA); - - Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); - Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); - Predicate predicateForRedColorAndGradeB = criteriaBuilder.and(predicateForRedColor, predicateForGradeB); - - // final search filter - Predicate finalPredicate = criteriaBuilder.or(predicateForBlueColorAndGradeA, predicateForRedColorAndGradeB); - - criteriaQuery.where(finalPredicate); - - List items = entityManager.createQuery(criteriaQuery) - .getResultList(); - return items; - } } diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java deleted file mode 100644 index c5fb7fa25f..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.baeldung.dao.repositories.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.CollectionUtils; - -import com.baeldung.config.PersistenceConfiguration; -import com.baeldung.config.PersistenceProductConfiguration; -import com.baeldung.config.PersistenceUserConfiguration; -import com.baeldung.dao.repositories.CustomItemRepository; -import com.baeldung.domain.Item; - -@RunWith(SpringRunner.class) -@DataJpaTest(excludeAutoConfiguration = { PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class }) -public class CustomItemRepositoryIntegrationTest { - - @Autowired - CustomItemRepository customItemRepositoryImpl; - - @Autowired - EntityManager entityManager; - - @Before - public void setUp() { - - Item firstItem = new Item(); - firstItem.setColor("blue"); - firstItem.setGrade("C"); - firstItem.setId(10l); - - entityManager.persist(firstItem); - - Item secondItem = new Item(); - secondItem.setColor("red"); - secondItem.setGrade("C"); - secondItem.setId(11l); - - entityManager.persist(secondItem); - - Item thirdItem = new Item(); - thirdItem.setColor("blue"); - thirdItem.setGrade("A"); - thirdItem.setId(12l); - - entityManager.persist(thirdItem); - - Item fourthItem = new Item(); - fourthItem.setColor("red"); - fourthItem.setGrade("D"); - fourthItem.setId(13l); - - entityManager.persist(fourthItem); - } - - @Test - public void givenItems_whenFindItemsByColorAndGrade_thenReturnItems() { - - List items = customItemRepositoryImpl.findItemsByColorAndGrade(); - - assertFalse("No items found", CollectionUtils.isEmpty(items)); - assertEquals("There should be only one item", 1, items.size()); - - Item item = items.get(0); - - assertEquals("this item do not have blue color", "blue", item.getColor()); - assertEquals("this item does not belong to A grade", "A", item.getGrade()); - } - - @Test - public void givenItems_whenFindItemByColorOrGrade_thenReturnItems() { - - List items = customItemRepositoryImpl.findItemByColorOrGrade(); - - assertFalse("No items found", CollectionUtils.isEmpty(items)); - assertEquals("There should be only one item", 1, items.size()); - - Item item = items.get(0); - - assertEquals("this item do not have red color", "red", item.getColor()); - assertEquals("this item does not belong to D grade", "D", item.getGrade()); - } - -} From 57a1096c1fd3e26674367b6b28b1ad8ba2559e38 Mon Sep 17 00:00:00 2001 From: Adam InTae Gerard Date: Tue, 12 Mar 2019 20:55:59 -0700 Subject: [PATCH 191/254] BAEL-2338 (#6150) * BAEL-2338 * Update Application.java * merged and updated * updated pom.xml * improved and updated * corrected per request * removed annotations * formatting --- xml/README.md | 1 + xml/pom.xml | 16 +++ .../com/baeldung/xmlhtml/Application.java | 10 ++ .../java/com/baeldung/xmlhtml/Constants.java | 22 ++++ .../baeldung/xmlhtml/helpers/XMLRunner.java | 16 +++ .../xmlhtml/helpers/jaxb/JAXBHelper.java | 77 ++++++++++++ .../xmlhtml/helpers/jaxp/CustomHandler.java | 34 ++++++ .../xmlhtml/helpers/jaxp/JAXPHelper.java | 90 ++++++++++++++ .../xmlhtml/helpers/stax/STAXHelper.java | 112 ++++++++++++++++++ .../xmlhtml/pojo/jaxb/html/ExampleHTML.java | 38 ++++++ .../xmlhtml/pojo/jaxb/html/elements/Body.java | 29 +++++ .../jaxb/html/elements/CustomElement.java | 18 +++ .../xmlhtml/pojo/jaxb/html/elements/Meta.java | 30 +++++ .../jaxb/html/elements/NestedElement.java | 17 +++ .../xmlhtml/pojo/jaxb/xml/XMLExample.java | 21 ++++ .../pojo/jaxb/xml/elements/Ancestor.java | 28 +++++ .../pojo/jaxb/xml/elements/DescendantOne.java | 19 +++ .../jaxb/xml/elements/DescendantThree.java | 18 +++ .../pojo/jaxb/xml/elements/DescendantTwo.java | 17 +++ .../com/baeldung/xmlhtml/pojo/stax/Body.java | 23 ++++ .../xmlhtml/pojo/stax/CustomElement.java | 13 ++ .../xmlhtml/pojo/stax/NestedElement.java | 13 ++ xml/src/main/resources/xml/in.xml | 11 ++ xml/src/main/resources/xml/jaxb.html | 14 +++ xml/src/main/resources/xml/jaxp.html | 13 ++ xml/src/main/resources/xml/stax.html | 15 +++ 26 files changed, 715 insertions(+) create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/Application.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/Constants.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/helpers/XMLRunner.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxb/JAXBHelper.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/CustomHandler.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/JAXPHelper.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/helpers/stax/STAXHelper.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/ExampleHTML.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Body.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/CustomElement.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Meta.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/NestedElement.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/XMLExample.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/Ancestor.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantOne.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantThree.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantTwo.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/Body.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/CustomElement.java create mode 100644 xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/NestedElement.java create mode 100644 xml/src/main/resources/xml/in.xml create mode 100644 xml/src/main/resources/xml/jaxb.html create mode 100644 xml/src/main/resources/xml/jaxp.html create mode 100644 xml/src/main/resources/xml/stax.html diff --git a/xml/README.md b/xml/README.md index fb070100db..9d889ef8e9 100644 --- a/xml/README.md +++ b/xml/README.md @@ -4,3 +4,4 @@ - [XML Libraries Support in Java](http://www.baeldung.com/java-xml-libraries) - [DOM parsing with Xerces](http://www.baeldung.com/java-xerces-dom-parsing) - [Write an org.w3.dom.Document to a File](https://www.baeldung.com/java-write-xml-document-file) +- [Convert XML to HTML](https://www.baeldung.com/) diff --git a/xml/pom.xml b/xml/pom.xml index dfdec4da16..ba6a734dc9 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -30,6 +30,22 @@ ${jdom2.version} + + javax.xml + jaxb-api + 2.1 + + + javax.xml + jaxp-api + 1.4.2 + + + javax.xml.stream + stax-api + 1.0-2 + + commons-io diff --git a/xml/src/main/java/com/baeldung/xmlhtml/Application.java b/xml/src/main/java/com/baeldung/xmlhtml/Application.java new file mode 100644 index 0000000000..063a833810 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/Application.java @@ -0,0 +1,10 @@ +package com.baeldung.xmlhtml; + +import com.baeldung.xmlhtml.helpers.XMLRunner; + +public class Application { + + public static void main(String[] args) { + XMLRunner.doWork(); + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/Constants.java b/xml/src/main/java/com/baeldung/xmlhtml/Constants.java new file mode 100644 index 0000000000..88fc5637df --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/Constants.java @@ -0,0 +1,22 @@ +package com.baeldung.xmlhtml; + +public class Constants { + + public static final String XML_FILE_IN = "src/main/resources/xml/in.xml"; + public static final String JAXB_FILE_OUT = "src/main/resources/xml/jaxb.html"; + public static final String JAXP_FILE_OUT = "src/main/resources/xml/jaxp.html"; + public static final String STAX_FILE_OUT = "src/main/resources/xml/stax.html"; + + public static final String EXCEPTION_ENCOUNTERED = "Generic exception! Error: "; + + public static final String LINE_BREAK = System.getProperty("line.separator"); + public static final String WHITE_SPACE = " "; + + public static final String DOCUMENT_START = "Document parsing has begun!"; + public static final String DOCUMENT_END = "Document parsing has ended!"; + public static final String ELEMENT_START = "Element parsing has begun!"; + public static final String ELEMENT_END = "Element parsing has ended!"; + + public static final String BREAK = "\n"; + public static final String TAB = "\t"; +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/XMLRunner.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/XMLRunner.java new file mode 100644 index 0000000000..02b2577795 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/XMLRunner.java @@ -0,0 +1,16 @@ +package com.baeldung.xmlhtml.helpers; + + +import com.baeldung.xmlhtml.helpers.jaxb.JAXBHelper; +import com.baeldung.xmlhtml.helpers.jaxp.JAXPHelper; +import com.baeldung.xmlhtml.helpers.stax.STAXHelper; + +public class XMLRunner { + + public static void doWork() { + JAXBHelper.example(); + JAXPHelper.saxParser(); + JAXPHelper.documentBuilder(); + STAXHelper.write(STAXHelper.read()); + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxb/JAXBHelper.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxb/JAXBHelper.java new file mode 100644 index 0000000000..715f963f2e --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxb/JAXBHelper.java @@ -0,0 +1,77 @@ +package com.baeldung.xmlhtml.helpers.jaxb; + +import com.baeldung.xmlhtml.pojo.jaxb.html.ExampleHTML; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Body; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.CustomElement; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Meta; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.NestedElement; +import com.baeldung.xmlhtml.pojo.jaxb.xml.XMLExample; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; + +import java.io.File; + +import static com.baeldung.xmlhtml.Constants.*; + +public class JAXBHelper { + + private static void print(String xmlContent) { + System.out.println(xmlContent); + } + + private static Unmarshaller getContextUnmarshaller(Class clazz) { + Unmarshaller unmarshaller = null; + try { + JAXBContext context = JAXBContext.newInstance(clazz); + unmarshaller = context.createUnmarshaller(); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return unmarshaller; + } + + private static Marshaller getContextMarshaller(Class clazz) { + Marshaller marshaller = null; + try { + JAXBContext context = JAXBContext.newInstance(clazz); + marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + marshaller.setProperty("jaxb.fragment", Boolean.TRUE); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return marshaller; + } + + public static void example() { + try { + XMLExample xml = (XMLExample) JAXBHelper.getContextUnmarshaller(XMLExample.class).unmarshal(new File(XML_FILE_IN)); + JAXBHelper.print(xml.toString()); + ExampleHTML html = new ExampleHTML(); + + Body body = new Body(); + CustomElement customElement = new CustomElement(); + NestedElement nested = new NestedElement(); + CustomElement child = new CustomElement(); + + customElement.setValue("descendantOne: " + xml.getAncestor().getDescendantOne().getValue()); + child.setValue("descendantThree: " + xml.getAncestor().getDescendantTwo().getDescendantThree().getValue()); + nested.setCustomElement(child); + + body.setCustomElement(customElement); + body.setNestedElement(nested); + + Meta meta = new Meta(); + meta.setTitle("example"); + html.getHead().add(meta); + html.setBody(body); + + JAXBHelper.getContextMarshaller(ExampleHTML.class).marshal(html, new File(JAXB_FILE_OUT)); + + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + } +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/CustomHandler.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/CustomHandler.java new file mode 100644 index 0000000000..e6351c9e22 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/CustomHandler.java @@ -0,0 +1,34 @@ +package com.baeldung.xmlhtml.helpers.jaxp; + +import org.xml.sax.ContentHandler; +import org.xml.sax.Locator; + +import static com.baeldung.xmlhtml.Constants.*; + +public class CustomHandler implements ContentHandler { + + public void startDocument() {} + + public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) { } + + public void endDocument() { + System.out.println(DOCUMENT_END); + } + + public void endElement(String uri, String localName, String qName) { } + + public void startPrefixMapping(String prefix, String uri) { } + + public void endPrefixMapping(String prefix) { } + + public void setDocumentLocator(Locator locator) { } + + public void characters(char[] ch, int start, int length) { } + + public void ignorableWhitespace(char[] ch, int start, int length) { } + + public void processingInstruction(String target, String data) { } + + public void skippedEntity(String name) { } + +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/JAXPHelper.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/JAXPHelper.java new file mode 100644 index 0000000000..3196d543da --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/JAXPHelper.java @@ -0,0 +1,90 @@ +package com.baeldung.xmlhtml.helpers.jaxp; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.XMLReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.File; + +import static com.baeldung.xmlhtml.Constants.*; + +public class JAXPHelper { + + private static void print(Document document) { + NodeList list = document.getChildNodes(); + try { + for (int i = 0; i < list.getLength(); i++) { + Node node = list.item(i); + String message = + node.getNodeType() + + WHITE_SPACE + + node.getNodeName() + + LINE_BREAK; + System.out.println(message); + } + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + } + + public static void saxParser() { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + try { + SAXParser saxParser = spf.newSAXParser(); + XMLReader xmlReader = saxParser.getXMLReader(); + xmlReader.setContentHandler(new CustomHandler()); + xmlReader.parse(XML_FILE_IN); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + } + + public static void documentBuilder() { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + try { + DocumentBuilder db = dbf.newDocumentBuilder(); + Document parsed = db.parse(new File(XML_FILE_IN)); + Element xml = parsed.getDocumentElement(); + + Document doc = db.newDocument(); + Element html = doc.createElement("html"); + Element head = doc.createElement("head"); + html.appendChild(head); + + Element body = doc.createElement("body"); + Element descendantOne = doc.createElement("p"); + descendantOne.setTextContent("descendantOne: " + + xml.getElementsByTagName("descendantOne") + .item(0).getTextContent()); + Element descendantThree = doc.createElement("p"); + descendantThree.setTextContent("descendantThree: " + + xml.getElementsByTagName("descendantThree") + .item(0).getTextContent()); + Element nested = doc.createElement("div"); + nested.appendChild(descendantThree); + + body.appendChild(descendantOne); + body.appendChild(nested); + html.appendChild(body); + doc.appendChild(html); + + TransformerFactory tFactory = TransformerFactory.newInstance(); + tFactory + .newTransformer() + .transform(new DOMSource(doc), new StreamResult(new File(JAXP_FILE_OUT))); + + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/stax/STAXHelper.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/stax/STAXHelper.java new file mode 100644 index 0000000000..a9b9217b6a --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/stax/STAXHelper.java @@ -0,0 +1,112 @@ +package com.baeldung.xmlhtml.helpers.stax; + +import com.baeldung.xmlhtml.pojo.stax.Body; +import com.baeldung.xmlhtml.pojo.stax.CustomElement; +import com.baeldung.xmlhtml.pojo.stax.NestedElement; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; +import java.io.FileInputStream; +import java.io.FileWriter; + +import static com.baeldung.xmlhtml.Constants.*; + +public class STAXHelper { + + private static XMLStreamReader reader() { + XMLStreamReader xmlStreamReader = null; + try { + xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(XML_FILE_IN)); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return xmlStreamReader; + } + + private static XMLStreamWriter writer() { + XMLStreamWriter xmlStreamWriter = null; + try { + xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(STAX_FILE_OUT)); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return xmlStreamWriter; + } + + public static Body read() { + Body body = new Body(); + try { + XMLStreamReader xmlStreamReader = reader(); + + CustomElement customElement = new CustomElement(); + NestedElement nestedElement = new NestedElement(); + CustomElement child = new CustomElement(); + + while (xmlStreamReader.hasNext()) { + xmlStreamReader.next(); + if (xmlStreamReader.isStartElement()) { + System.out.println(xmlStreamReader.getLocalName()); + if (xmlStreamReader.getLocalName().equals("descendantOne")) { + customElement.setValue(xmlStreamReader.getElementText()); + } + if (xmlStreamReader.getLocalName().equals("descendantThree")) { + child.setValue(xmlStreamReader.getElementText()); + } + } + } + + nestedElement.setCustomElement(child); + body.setCustomElement(customElement); + body.setNestedElement(nestedElement); + + xmlStreamReader.close(); + + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return body; + } + + public static void write(Body body) { + try { + + XMLStreamWriter xmlStreamWriter = writer(); + xmlStreamWriter.writeStartElement("html"); + xmlStreamWriter.writeCharacters(BREAK + TAB); + xmlStreamWriter.writeStartElement("head"); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB); + xmlStreamWriter.writeStartElement("meta"); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB); + xmlStreamWriter.writeStartElement("body"); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB); + xmlStreamWriter.writeStartElement("p"); + xmlStreamWriter.writeCharacters("descendantOne: " + body.getCustomElement().getValue()); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB); + xmlStreamWriter.writeStartElement("div"); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB + TAB); + xmlStreamWriter.writeStartElement("p"); + xmlStreamWriter.writeCharacters(BREAK); + xmlStreamWriter.writeCharacters(TAB + TAB + TAB + TAB + "descendantThree: " + body.getNestedElement().getCustomElement().getValue()); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB + TAB); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK); + xmlStreamWriter.writeEndDocument(); + xmlStreamWriter.flush(); + xmlStreamWriter.close(); + + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/ExampleHTML.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/ExampleHTML.java new file mode 100644 index 0000000000..d44c81f309 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/ExampleHTML.java @@ -0,0 +1,38 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html; + +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Body; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Meta; + +import javax.xml.bind.annotation.*; +import java.util.ArrayList; +import java.util.List; + +@XmlType(propOrder = {"head", "body"}) +@XmlRootElement(name = "html") +public class ExampleHTML { + + private List head = new ArrayList<>(); + + private Body body; + + public ExampleHTML() { } + + public List getHead() { + return head; + } + + @XmlElementWrapper(name = "head") + @XmlElement(name = "meta") + public void setHead(List head) { + this.head = head; + } + + public Body getBody() { + return body; + } + + @XmlElement(name = "body") + public void setBody(Body body) { + this.body = body; + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Body.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Body.java new file mode 100644 index 0000000000..36c6c13a04 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Body.java @@ -0,0 +1,29 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html.elements; + +import javax.xml.bind.annotation.XmlElement; + +public class Body { + + private CustomElement customElement; + + public CustomElement getCustomElement() { + return customElement; + } + + @XmlElement(name = "p") + public void setCustomElement(CustomElement customElement) { + this.customElement = customElement; + } + + private NestedElement nestedElement; + + public NestedElement getNestedElement() { + return nestedElement; + } + + @XmlElement(name = "div") + public void setNestedElement(NestedElement nestedElement) { + this.nestedElement = nestedElement; + } + +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/CustomElement.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/CustomElement.java new file mode 100644 index 0000000000..832c5e746e --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/CustomElement.java @@ -0,0 +1,18 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html.elements; + +import javax.xml.bind.annotation.XmlValue; + +public class CustomElement { + + private String value; + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Meta.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Meta.java new file mode 100644 index 0000000000..11b6b86c05 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Meta.java @@ -0,0 +1,30 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html.elements; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlValue; + +public class Meta { + + private String title; + + public String getTitle() { + return title; + } + + @XmlAttribute(name = "title") + public void setTitle(String title) { + this.title = title; + } + + private String value; + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/NestedElement.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/NestedElement.java new file mode 100644 index 0000000000..20557064bb --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/NestedElement.java @@ -0,0 +1,17 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html.elements; + +import javax.xml.bind.annotation.XmlElement; + +public class NestedElement { + + private CustomElement customElement; + + public CustomElement getCustomElement() { + return customElement; + } + + @XmlElement(name = "p") + public void setCustomElement(CustomElement customElement) { + this.customElement = customElement; + } +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/XMLExample.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/XMLExample.java new file mode 100644 index 0000000000..587cf69223 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/XMLExample.java @@ -0,0 +1,21 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml; + +import com.baeldung.xmlhtml.pojo.jaxb.xml.elements.Ancestor; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "xmlexample") +public class XMLExample { + + private Ancestor ancestor; + + @XmlElement(name = "ancestor") + public void setAncestor(Ancestor ancestor) { + this.ancestor = ancestor; + } + + public Ancestor getAncestor() { + return ancestor; + } +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/Ancestor.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/Ancestor.java new file mode 100644 index 0000000000..ff2b928206 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/Ancestor.java @@ -0,0 +1,28 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml.elements; + +import javax.xml.bind.annotation.XmlElement; + +public class Ancestor { + + private DescendantOne descendantOne; + private DescendantTwo descendantTwo; + + public DescendantOne getDescendantOne() { + return descendantOne; + } + + @XmlElement(name = "descendantOne") + public void setDescendantOne(DescendantOne descendantOne) { + this.descendantOne = descendantOne; + } + + public DescendantTwo getDescendantTwo() { + return descendantTwo; + } + + @XmlElement(name = "descendantTwo") + public void setDescendantTwo(DescendantTwo descendantTwo) { + this.descendantTwo = descendantTwo; + } +} + diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantOne.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantOne.java new file mode 100644 index 0000000000..50624cb9fa --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantOne.java @@ -0,0 +1,19 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml.elements; + +import javax.xml.bind.annotation.XmlValue; + +public class DescendantOne { + + private String value; + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} + diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantThree.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantThree.java new file mode 100644 index 0000000000..7c3ce9b6f7 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantThree.java @@ -0,0 +1,18 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml.elements; + +import javax.xml.bind.annotation.XmlValue; + +public class DescendantThree { + + private String value; + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantTwo.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantTwo.java new file mode 100644 index 0000000000..1ca989560b --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantTwo.java @@ -0,0 +1,17 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml.elements; + +import javax.xml.bind.annotation.XmlElement; + +public class DescendantTwo { + + private DescendantThree descendantThree; + + public DescendantThree getDescendantThree() { + return descendantThree; + } + + @XmlElement(name = "descendantThree") + public void setDescendant(DescendantThree descendantThree) { + this.descendantThree = descendantThree; + } +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/Body.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/Body.java new file mode 100644 index 0000000000..630dfe967f --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/Body.java @@ -0,0 +1,23 @@ +package com.baeldung.xmlhtml.pojo.stax; + +public class Body { + + private CustomElement customElement; + + public CustomElement getCustomElement() { + return customElement; + } + public void setCustomElement(CustomElement customElement) { + this.customElement = customElement; + } + + private NestedElement nestedElement; + + public NestedElement getNestedElement() { + return nestedElement; + } + public void setNestedElement(NestedElement nestedElement) { + this.nestedElement = nestedElement; + } + +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/CustomElement.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/CustomElement.java new file mode 100644 index 0000000000..6fc1d7b787 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/CustomElement.java @@ -0,0 +1,13 @@ +package com.baeldung.xmlhtml.pojo.stax; + +public class CustomElement { + + private String value; + + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/NestedElement.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/NestedElement.java new file mode 100644 index 0000000000..146ee068af --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/NestedElement.java @@ -0,0 +1,13 @@ +package com.baeldung.xmlhtml.pojo.stax; + +public class NestedElement { + + private CustomElement customElement; + + public CustomElement getCustomElement() { + return customElement; + } + public void setCustomElement(CustomElement customElement) { + this.customElement = customElement; + } +} diff --git a/xml/src/main/resources/xml/in.xml b/xml/src/main/resources/xml/in.xml new file mode 100644 index 0000000000..6fcb404012 --- /dev/null +++ b/xml/src/main/resources/xml/in.xml @@ -0,0 +1,11 @@ + + + + Yo + + + DustyOrb + + + + \ No newline at end of file diff --git a/xml/src/main/resources/xml/jaxb.html b/xml/src/main/resources/xml/jaxb.html new file mode 100644 index 0000000000..80b894cff7 --- /dev/null +++ b/xml/src/main/resources/xml/jaxb.html @@ -0,0 +1,14 @@ + + + + + + +

descendantOne: Yo

+
+

descendantThree: + DustyOrb +

+
+ + diff --git a/xml/src/main/resources/xml/jaxp.html b/xml/src/main/resources/xml/jaxp.html new file mode 100644 index 0000000000..5392eef509 --- /dev/null +++ b/xml/src/main/resources/xml/jaxp.html @@ -0,0 +1,13 @@ + + + + + +

descendantOne: Yo

+
+

descendantThree: + DustyOrb +

+
+ + diff --git a/xml/src/main/resources/xml/stax.html b/xml/src/main/resources/xml/stax.html new file mode 100644 index 0000000000..01951dc7de --- /dev/null +++ b/xml/src/main/resources/xml/stax.html @@ -0,0 +1,15 @@ + + + + + +

descendantOne: Yo

+
+

+ descendantThree: + DustyOrb + +

+
+ + \ No newline at end of file From 8ecfd8de08ea13acfd0559116359f10c080d7f4a Mon Sep 17 00:00:00 2001 From: pcoates33 Date: Wed, 13 Mar 2019 04:54:34 +0000 Subject: [PATCH 192/254] Bael 2721 - JSON deserialization mapping different JSON fields to same Java field (#6434) * BAEL-2721 Examples of @JsonAlias and Gson's alternate parameter * BAEL-2721 Update class and method names for JsonAlias and GsonAlternate --- .../org/baeldung/gson/entities/Weather.java | 40 +++++++++++++++++ .../GsonAlternateUnitTest.java | 39 ++++++++++++++++ .../baeldung/jackson/entities/Weather.java | 44 +++++++++++++++++++ .../jsonalias/JsonAliasUnitTest.java | 38 ++++++++++++++++ 4 files changed, 161 insertions(+) create mode 100644 gson/src/main/java/org/baeldung/gson/entities/Weather.java create mode 100644 gson/src/test/java/org/baeldung/gson/deserialization/GsonAlternateUnitTest.java create mode 100644 jackson/src/main/java/com/baeldung/jackson/entities/Weather.java create mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java diff --git a/gson/src/main/java/org/baeldung/gson/entities/Weather.java b/gson/src/main/java/org/baeldung/gson/entities/Weather.java new file mode 100644 index 0000000000..383e9ef41c --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Weather.java @@ -0,0 +1,40 @@ +package org.baeldung.gson.entities; + +import com.google.gson.annotations.SerializedName; + +public class Weather { + + @SerializedName(value = "location", alternate = "place") + private String location; + + @SerializedName(value = "temp", alternate = "temperature") + private int temp; + + @SerializedName(value = "outlook", alternate = "weather") + private String outlook; + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public int getTemp() { + return temp; + } + + public void setTemp(int temp) { + this.temp = temp; + } + + public String getOutlook() { + return outlook; + } + + public void setOutlook(String outlook) { + this.outlook = outlook; + } + +} diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/GsonAlternateUnitTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/GsonAlternateUnitTest.java new file mode 100644 index 0000000000..f3a5d24e3e --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/deserialization/GsonAlternateUnitTest.java @@ -0,0 +1,39 @@ +package org.baeldung.gson.deserialization; + +import static org.junit.Assert.assertEquals; + +import org.baeldung.gson.entities.Weather; +import org.junit.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class GsonAlternateUnitTest { + + @Test + public void givenTwoJsonFormats_whenDeserialized_thenWeatherObjectsCreated() throws Exception { + + Gson gson = new GsonBuilder().create(); + + Weather weather = gson.fromJson("{" + + "\"location\": \"London\"," + + "\"temp\": 15," + + "\"weather\": \"Cloudy\"" + + "}", Weather.class); + + assertEquals("London", weather.getLocation()); + assertEquals("Cloudy", weather.getOutlook()); + assertEquals(15, weather.getTemp()); + + weather = gson.fromJson("{" + + "\"place\": \"Lisbon\"," + + "\"temperature\": 35," + + "\"outlook\": \"Sunny\"" + + "}", Weather.class); + + assertEquals("Lisbon", weather.getLocation()); + assertEquals("Sunny", weather.getOutlook()); + assertEquals(35, weather.getTemp()); + + } +} diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/Weather.java b/jackson/src/main/java/com/baeldung/jackson/entities/Weather.java new file mode 100644 index 0000000000..4a8cea052f --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/entities/Weather.java @@ -0,0 +1,44 @@ +package com.baeldung.jackson.entities; + +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Weather { + + @JsonProperty("location") + @JsonAlias("place") + private String location; + + @JsonProperty("temp") + @JsonAlias("temperature") + private int temp; + + @JsonProperty("outlook") + @JsonAlias("weather") + private String outlook; + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public int getTemp() { + return temp; + } + + public void setTemp(int temp) { + this.temp = temp; + } + + public String getOutlook() { + return outlook; + } + + public void setOutlook(String outlook) { + this.outlook = outlook; + } + +} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java new file mode 100644 index 0000000000..b5940a7bd7 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.jackson.deserialization.jsonalias; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.jackson.entities.Weather; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonAliasUnitTest { + + @Test + public void givenTwoJsonFormats_whenDeserialized_thenWeatherObjectsCreated() throws Exception { + + ObjectMapper mapper = new ObjectMapper(); + + Weather weather = mapper.readValue("{" + + "\"location\": \"London\"," + + "\"temp\": 15," + + "\"weather\": \"Cloudy\"" + + "}", Weather.class); + + assertEquals("London", weather.getLocation()); + assertEquals("Cloudy", weather.getOutlook()); + assertEquals(15, weather.getTemp()); + + weather = mapper.readValue("{" + + "\"place\": \"Lisbon\"," + + "\"temperature\": 35," + + "\"outlook\": \"Sunny\"" + + "}", Weather.class); + + assertEquals("Lisbon", weather.getLocation()); + assertEquals("Sunny", weather.getOutlook()); + assertEquals(35, weather.getTemp()); + + } +} From c9ac3be4c5b7e04fef8cc79ab2e7bbddccbe4b0c Mon Sep 17 00:00:00 2001 From: letcodespeak <44544000+letcodespeak@users.noreply.github.com> Date: Wed, 13 Mar 2019 15:58:13 +1100 Subject: [PATCH 193/254] BAEL-2569 : EnvironmentPostProcessor in Spring Boot (#6479) * BAEL-2569 : EnvironmentPostProcessor in Spring Boot * BAEL-2569 add test * BAEL-2569 update test --- .../PriceCalculationApplication.java | 59 +++++++++++++++ ...ceCalculationEnvironmentPostProcessor.java | 71 +++++++++++++++++++ .../PriceCalculationAutoConfig.java | 32 +++++++++ .../calculator/GrossPriceCalculator.java | 23 ++++++ .../calculator/NetPriceCalculator.java | 17 +++++ .../calculator/PriceCalculator.java | 5 ++ .../service/PriceCalculationService.java | 17 +++++ .../main/resources/META-INF/spring.factories | 8 ++- ...ationEnvironmentPostProcessorLiveTest.java | 26 +++++++ 9 files changed, 257 insertions(+), 1 deletion(-) create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java create mode 100644 spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java new file mode 100644 index 0000000000..01be08d6ae --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java @@ -0,0 +1,59 @@ +package com.baeldung.environmentpostprocessor; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import com.baeldung.environmentpostprocessor.service.PriceCalculationService; + +@SpringBootApplication +public class PriceCalculationApplication implements CommandLineRunner { + + @Autowired + PriceCalculationService priceCalculationService; + + private static final Logger logger = LoggerFactory.getLogger(PriceCalculationApplication.class); + + public static void main(String[] args) { + SpringApplication.run(PriceCalculationApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + + List params = Arrays.stream(args) + .collect(Collectors.toList()); + if (verifyArguments(params)) { + double singlePrice = Double.valueOf(params.get(0)); + int quantity = Integer.valueOf(params.get(1)); + priceCalculationService.productTotalPrice(singlePrice, quantity); + } else { + logger.error("Invalid arguments " + params.toString()); + } + + } + + private boolean verifyArguments(List args) { + boolean successful = true; + if (args.size() != 2) { + successful = false; + return successful; + } + try { + double singlePrice = Double.valueOf(args.get(0)); + int quantity = Integer.valueOf(args.get(1)); + } catch (NumberFormatException e) { + successful = false; + } + return successful; + + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java new file mode 100644 index 0000000000..1b3099453e --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java @@ -0,0 +1,71 @@ +package com.baeldung.environmentpostprocessor; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.env.StandardEnvironment; + +public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + + private static final Logger logger = LoggerFactory.getLogger(PriceCalculationEnvironmentPostProcessor.class); + + public static final int DEFAULT_ORDER = Ordered.LOWEST_PRECEDENCE; + private int order = DEFAULT_ORDER; + private static final String PROPERTY_PREFIX = "com.baeldung.environmentpostprocessor."; + private static final String OS_ENV_PROPERTY_CALCUATION_MODE = "calculation_mode"; + private static final String OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE = "gross_calculation_tax_rate"; + private static final String OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE = "NET"; + private static final double OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE = 0; + + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + + PropertySource systemEnvironmentPropertySource = environment.getPropertySources() + .get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + + Map priceCalculationConfiguration = new LinkedHashMap<>(); + if (isActive(systemEnvironmentPropertySource)) { + priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_CALCUATION_MODE)); + priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)); + } else { + logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE, + OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); + priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE); + priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); + } + + PropertySource priceCalcuationPropertySource = new MapPropertySource("priceCalcuationPS", priceCalculationConfiguration); + environment.getPropertySources() + .addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, priceCalcuationPropertySource); + + } + + private String key(String key) { + return PROPERTY_PREFIX + key.replaceAll("\\_", "."); + } + + private boolean isActive(PropertySource systemEnvpropertySource) { + if (systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_CALCUATION_MODE) && systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)) { + return true; + } else + return false; + } + + public void setOrder(int order) { + this.order = order; + } + + @Override + public int getOrder() { + return order; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java new file mode 100644 index 0000000000..c884f043a0 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.environmentpostprocessor.autoconfig; + +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; + +import com.baeldung.environmentpostprocessor.calculator.GrossPriceCalculator; +import com.baeldung.environmentpostprocessor.calculator.NetPriceCalculator; +import com.baeldung.environmentpostprocessor.calculator.PriceCalculator; + +@Configuration +@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) +public class PriceCalculationAutoConfig { + + @Bean + @ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "NET") + @ConditionalOnMissingBean + public PriceCalculator getNetPriceCalculator() { + return new NetPriceCalculator(); + } + + @Bean + @ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "GROSS") + @ConditionalOnMissingBean + public PriceCalculator getGrossPriceCalculator() { + return new GrossPriceCalculator(); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java new file mode 100644 index 0000000000..f8f797bd66 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java @@ -0,0 +1,23 @@ +package com.baeldung.environmentpostprocessor.calculator; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; + +public class GrossPriceCalculator implements PriceCalculator { + + private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class); + + @Value("${com.baeldung.environmentpostprocessor.gross.calculation.tax.rate}") + double taxRate; + + @Override + public double calculate(double singlePrice, int quantity) { + logger.info("Gross based price calculation with input parameters [singlePrice = {},quantity= {} ], {} percent tax applied.", singlePrice, quantity, taxRate * 100); + double netPrice = singlePrice * quantity; + double result = Math.round(netPrice * (1 + taxRate)); + logger.info("Calcuation result is {}", result); + return result; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java new file mode 100644 index 0000000000..263dff6247 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java @@ -0,0 +1,17 @@ +package com.baeldung.environmentpostprocessor.calculator; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NetPriceCalculator implements PriceCalculator { + + private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class); + + @Override + public double calculate(double singlePrice, int quantity) { + logger.info("Net based price calculation with input parameters [singlePrice = {},quantity= {} ], NO tax applied.", singlePrice, quantity); + double result = Math.round(singlePrice * quantity); + logger.info("Calcuation result is {}", result); + return result; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java new file mode 100644 index 0000000000..9d7bef93a4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java @@ -0,0 +1,5 @@ +package com.baeldung.environmentpostprocessor.calculator; + +public interface PriceCalculator { + public double calculate(double singlePrice, int quantity); +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java new file mode 100644 index 0000000000..0e4eb39506 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java @@ -0,0 +1,17 @@ +package com.baeldung.environmentpostprocessor.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.environmentpostprocessor.calculator.PriceCalculator; + +@Service +public class PriceCalculationService { + + @Autowired + PriceCalculator priceCalculator; + + public double productTotalPrice(double singlePrice, int quantity) { + return priceCalculator.calculate(singlePrice, quantity); + } +} diff --git a/spring-boot/src/main/resources/META-INF/spring.factories b/spring-boot/src/main/resources/META-INF/spring.factories index e3d3aa4c8e..d8a01bbf82 100644 --- a/spring-boot/src/main/resources/META-INF/spring.factories +++ b/spring-boot/src/main/resources/META-INF/spring.factories @@ -1 +1,7 @@ -org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer \ No newline at end of file +org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig + +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor + diff --git a/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java b/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java new file mode 100644 index 0000000000..54af217346 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java @@ -0,0 +1,26 @@ +package com.baeldung.environmentpostprocessor; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.environmentpostprocessor.service.PriceCalculationService; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PriceCalculationApplication.class) +public class PriceCalculationEnvironmentPostProcessorLiveTest { + + @Autowired + PriceCalculationService pcService; + + @Test + public void whenSetNetEnvironmentVariablebyDefault_thenNoTaxApplied() { + double total = pcService.productTotalPrice(100, 4); + assertEquals(400.0, total, 0); + } + +} From 9578f0de93099ad5c8de8a0140cb7eaeab978b21 Mon Sep 17 00:00:00 2001 From: Jan Hauer Date: Mon, 11 Mar 2019 07:33:59 +0100 Subject: [PATCH 194/254] BAEL-2400: Adds examples for currying --- patterns/design-patterns/README.md | 1 + .../java/com/baeldung/currying/Letter.java | 110 ++++++++++++++++++ .../com/baeldung/currying/LetterUnitTest.java | 58 +++++++++ 3 files changed, 169 insertions(+) create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/currying/Letter.java create mode 100644 patterns/design-patterns/src/test/java/com/baeldung/currying/LetterUnitTest.java diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index a4513b7d95..c43ea48505 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -19,3 +19,4 @@ - [The Command Pattern in Java](http://www.baeldung.com/java-command-pattern) - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern) +- [Currying in Java](https://baeldung.com/currying-in-java) diff --git a/patterns/design-patterns/src/main/java/com/baeldung/currying/Letter.java b/patterns/design-patterns/src/main/java/com/baeldung/currying/Letter.java new file mode 100644 index 0000000000..0939569d3c --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/currying/Letter.java @@ -0,0 +1,110 @@ +package com.baeldung.currying; + +import java.time.LocalDate; +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.Function; + +public class Letter { + private String returningAddress; + private String insideAddress; + private LocalDate dateOfLetter; + private String salutation; + private String body; + private String closing; + + Letter(String returningAddress, String insideAddress, LocalDate dateOfLetter, String salutation, String body, String closing) { + this.returningAddress = returningAddress; + this.insideAddress = insideAddress; + this.dateOfLetter = dateOfLetter; + this.salutation = salutation; + this.body = body; + this.closing = closing; + } + + Letter(String salutation, String body) { + this(null, null, LocalDate.now(), salutation, body, null); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Letter letter = (Letter) o; + return Objects.equals(returningAddress, letter.returningAddress) && + Objects.equals(insideAddress, letter.insideAddress) && + Objects.equals(dateOfLetter, letter.dateOfLetter) && + Objects.equals(salutation, letter.salutation) && + Objects.equals(body, letter.body) && + Objects.equals(closing, letter.closing); + } + + @Override + public int hashCode() { + return Objects.hash(returningAddress, insideAddress, dateOfLetter, salutation, body, closing); + } + + @Override + public String toString() { + return "Letter{" + "returningAddress='" + returningAddress + '\'' + ", insideAddress='" + insideAddress + '\'' + + ", dateOfLetter=" + dateOfLetter + ", salutation='" + salutation + '\'' + ", body='" + body + '\'' + + ", closing='" + closing + '\'' + '}'; + } + + static Letter createLetter(String salutation, String body) { + return new Letter(salutation, body); + } + + static BiFunction SIMPLE_LETTER_CREATOR = // + (salutation, body) -> new Letter(salutation, body); + + static Function> SIMPLE_CURRIED_LETTER_CREATOR = // + saluation -> body -> new Letter(saluation, body); + + static Function>>>>> LETTER_CREATOR = // + returnAddress + -> closing + -> dateOfLetter + -> insideAddress + -> salutation + -> body + -> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing); + + static AddReturnAddress builder() { + return returnAddress + -> closing + -> dateOfLetter + -> insideAddress + -> salutation + -> body + -> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing); + } + + interface AddReturnAddress { + Letter.AddClosing withReturnAddress(String returnAddress); + } + + interface AddClosing { + Letter.AddDateOfLetter withClosing(String closing); + } + + interface AddDateOfLetter { + Letter.AddInsideAddress withDateOfLetter(LocalDate dateOfLetter); + } + + interface AddInsideAddress { + Letter.AddSalutation withInsideAddress(String insideAddress); + } + + interface AddSalutation { + Letter.AddBody withSalutation(String salutation); + } + + interface AddBody { + Letter withBody(String body); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/test/java/com/baeldung/currying/LetterUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/currying/LetterUnitTest.java new file mode 100644 index 0000000000..bf1bafe72c --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/currying/LetterUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.currying; + +import org.junit.Test; + +import java.time.LocalDate; + +import static com.baeldung.currying.Letter.LETTER_CREATOR; +import static com.baeldung.currying.Letter.SIMPLE_CURRIED_LETTER_CREATOR; +import static com.baeldung.currying.Letter.SIMPLE_LETTER_CREATOR; +import static org.junit.Assert.assertEquals; + +public class LetterUnitTest { + private static final String BODY = "BODY"; + private static final String SALUTATION = "SALUTATION"; + private static final String RETURNING_ADDRESS = "RETURNING ADDRESS"; + private static final String INSIDE_ADDRESS = "INSIDE ADDRESS"; + private static final LocalDate DATE_OF_LETTER = LocalDate.of(2013, 3, 1); + private static final String CLOSING = "CLOSING"; + private static final Letter SIMPLE_LETTER = new Letter(SALUTATION, BODY); + private static final Letter LETTER = new Letter(RETURNING_ADDRESS, INSIDE_ADDRESS, DATE_OF_LETTER, SALUTATION, BODY, CLOSING); + + @Test + public void whenStaticCreateMethodIsCalled_thenaSimpleLetterIsCreated() { + assertEquals(SIMPLE_LETTER, Letter.createLetter(SALUTATION, BODY)); + } + + @Test + public void whenStaticBiFunctionIsCalled_thenaSimpleLetterIsCreated() { + assertEquals(SIMPLE_LETTER, SIMPLE_LETTER_CREATOR.apply(SALUTATION, BODY)); + } + + @Test + public void whenStaticSimpleCurriedFunctionIsCalled_thenaSimpleLetterIsCreated() { + assertEquals(SIMPLE_LETTER, SIMPLE_CURRIED_LETTER_CREATOR.apply(SALUTATION).apply(BODY)); + } + + @Test + public void whenStaticCurriedFunctionIsCalled_thenaLetterIsCreated() { + assertEquals(LETTER, LETTER_CREATOR + .apply(RETURNING_ADDRESS) + .apply(CLOSING) + .apply(DATE_OF_LETTER) + .apply(INSIDE_ADDRESS) + .apply(SALUTATION) + .apply(BODY)); + } + + @Test + public void whenStaticBuilderIsCalled_thenaLetterIsCreated() { + assertEquals(LETTER, Letter.builder() + .withReturnAddress(RETURNING_ADDRESS) + .withClosing(CLOSING) + .withDateOfLetter(DATE_OF_LETTER) + .withInsideAddress(INSIDE_ADDRESS) + .withSalutation(SALUTATION) + .withBody(BODY)); + } +} \ No newline at end of file From e5f6da559f6d8c387405d2c7fc1aef2dfbd5a3f2 Mon Sep 17 00:00:00 2001 From: Johan Janssen Date: Wed, 13 Mar 2019 14:26:53 +0100 Subject: [PATCH 195/254] Moved tests to core-kotlin-2 (#6522) * Kotlin split list in pairs examples. * Renamed some items. * Moved test. --- .../src/test/kotlin/com/baeldung/splitting/SplittingTest.kt | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {core-kotlin => core-kotlin-2}/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt (100%) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt rename to core-kotlin-2/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt From cd57889230a3cab66f1904e32bbda48ba205216d Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 13 Mar 2019 17:29:19 +0200 Subject: [PATCH 196/254] maven cleanup --- spring-data-rest/pom.xml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index 772d6f2553..e563a6a3b5 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - com.baeldung spring-data-rest + 1.0 spring-data-rest jar @@ -40,11 +40,7 @@ org.xerial sqlite-jdbc - ${sqlite.version} - @@ -53,8 +49,6 @@ com.baeldung.SpringDataRestApplication - 3.25.2 - 2.1.0.RELEASE From 47e617fc39ba62cbfbda09f19d1b5d8764668801 Mon Sep 17 00:00:00 2001 From: cdjole Date: Wed, 13 Mar 2019 16:31:14 +0100 Subject: [PATCH 197/254] Method inlining example. (#6520) * Method inlining example. * Test added --- .../inlining/ConsecutiveNumbersSum.java | 19 ++++++++++++++++ .../baeldung/inlining/InliningExample.java | 16 ++++++++++++++ .../ConsecutiveNumbersSumUnitTest.java | 22 +++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java create mode 100644 core-java/src/main/java/com/baeldung/inlining/InliningExample.java create mode 100644 core-java/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java b/core-java/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java new file mode 100644 index 0000000000..7de642f1c0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java @@ -0,0 +1,19 @@ +package com.baeldung.inlining; + +public class ConsecutiveNumbersSum { + + private long totalSum; + private int totalNumbers; + + public ConsecutiveNumbersSum(int totalNumbers) { + this.totalNumbers = totalNumbers; + } + + public long getTotalSum() { + totalSum = 0; + for (int i = 1; i <= totalNumbers; i++) { + totalSum += i; + } + return totalSum; + } +} diff --git a/core-java/src/main/java/com/baeldung/inlining/InliningExample.java b/core-java/src/main/java/com/baeldung/inlining/InliningExample.java new file mode 100644 index 0000000000..4c1802d0e4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/inlining/InliningExample.java @@ -0,0 +1,16 @@ +package com.baeldung.inlining; + +public class InliningExample { + + public static final int NUMBERS_OF_ITERATIONS = 15000; + + public static void main(String[] args) { + for (int i = 1; i < NUMBERS_OF_ITERATIONS; i++) { + calculateSum(i); + } + } + + private static long calculateSum(int n) { + return new ConsecutiveNumbersSum(n).getTotalSum(); + } +} diff --git a/core-java/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java b/core-java/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java new file mode 100644 index 0000000000..8e4b0353e6 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.inlining; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ConsecutiveNumbersSumUnitTest { + + private static final int TOTAL_NUMBERS = 10; + + @Test + public void givenTotalIntegersNumber_whenSumCalculated_thenEquals() { + ConsecutiveNumbersSum consecutiveNumbersSum = new ConsecutiveNumbersSum(TOTAL_NUMBERS); + long expectedSum = calculateExpectedSum(TOTAL_NUMBERS); + + assertEquals(expectedSum, consecutiveNumbersSum.getTotalSum()); + } + + private long calculateExpectedSum(int totalNumbers) { + return totalNumbers * (totalNumbers + 1) / 2; + } +} From 895aad42f97d967284fa8e11f55d0cb9c1ef5be5 Mon Sep 17 00:00:00 2001 From: nguyennamthai Date: Wed, 13 Mar 2019 23:06:11 +0700 Subject: [PATCH 198/254] Bael 2280 (#6320) * Fix a division method mistake * BAEL-2280 Programmatically Creating Sequences with Project Reactor * BAEL-2280 Update * BAEL-2280 Update --- reactor-core/pom.xml | 16 ++--- .../reactor/creation/FibonacciState.java | 27 +++++++ .../reactor/creation/SequenceCreator.java | 14 ++++ .../reactor/creation/SequenceGenerator.java | 31 ++++++++ .../reactor/creation/SequenceHandler.java | 13 ++++ .../reactor/creation/SequenceUnitTest.java | 70 +++++++++++++++++++ 6 files changed, 163 insertions(+), 8 deletions(-) create mode 100644 reactor-core/src/main/java/com/baeldung/reactor/creation/FibonacciState.java create mode 100644 reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceCreator.java create mode 100644 reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceGenerator.java create mode 100644 reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceHandler.java create mode 100644 reactor-core/src/test/java/com/baeldung/reactor/creation/SequenceUnitTest.java diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index db9550df7b..66c634e113 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -16,7 +16,13 @@ io.projectreactor reactor-core - ${reactor-core.version} + ${reactor.version} + + + io.projectreactor + reactor-test + ${reactor.version} + test org.assertj @@ -24,16 +30,10 @@ ${assertj.version} test - - io.projectreactor - reactor-test - ${reactor-core.version} - test - - 3.1.3.RELEASE + 3.2.6.RELEASE 3.6.1 diff --git a/reactor-core/src/main/java/com/baeldung/reactor/creation/FibonacciState.java b/reactor-core/src/main/java/com/baeldung/reactor/creation/FibonacciState.java new file mode 100644 index 0000000000..291002e1f9 --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/creation/FibonacciState.java @@ -0,0 +1,27 @@ +package com.baeldung.reactor.creation; + +public class FibonacciState { + private int former; + private int latter; + + public FibonacciState(int former, int latter) { + this.former = former; + this.latter = latter; + } + + public int getFormer() { + return former; + } + + public void setFormer(int former) { + this.former = former; + } + + public int getLatter() { + return latter; + } + + public void setLatter(int latter) { + this.latter = latter; + } +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceCreator.java b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceCreator.java new file mode 100644 index 0000000000..fb53b1cab1 --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceCreator.java @@ -0,0 +1,14 @@ +package com.baeldung.reactor.creation; + +import reactor.core.publisher.Flux; + +import java.util.List; +import java.util.function.Consumer; + +public class SequenceCreator { + public Consumer> consumer; + + public Flux createNumberSequence() { + return Flux.create(sink -> SequenceCreator.this.consumer = items -> items.forEach(sink::next)); + } +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceGenerator.java b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceGenerator.java new file mode 100644 index 0000000000..44d83d06bf --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceGenerator.java @@ -0,0 +1,31 @@ +package com.baeldung.reactor.creation; + +import reactor.core.publisher.Flux; +import reactor.util.function.Tuples; + +public class SequenceGenerator { + public Flux generateFibonacciWithTuples() { + return Flux.generate( + () -> Tuples.of(0, 1), + (state, sink) -> { + sink.next(state.getT1()); + return Tuples.of(state.getT2(), state.getT1() + state.getT2()); + } + ); + } + + public Flux generateFibonacciWithCustomClass(int limit) { + return Flux.generate( + () -> new FibonacciState(0, 1), + (state, sink) -> { + sink.next(state.getFormer()); + if (state.getLatter() > limit) { + sink.complete(); + } + int temp = state.getFormer(); + state.setFormer(state.getLatter()); + state.setLatter(temp + state.getLatter()); + return state; + }); + } +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceHandler.java b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceHandler.java new file mode 100644 index 0000000000..a9611c63e2 --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceHandler.java @@ -0,0 +1,13 @@ +package com.baeldung.reactor.creation; + +import reactor.core.publisher.Flux; + +public class SequenceHandler { + public Flux handleIntegerSequence(Flux sequence) { + return sequence.handle((number, sink) -> { + if (number % 2 == 0) { + sink.next(number / 2); + } + }); + } +} diff --git a/reactor-core/src/test/java/com/baeldung/reactor/creation/SequenceUnitTest.java b/reactor-core/src/test/java/com/baeldung/reactor/creation/SequenceUnitTest.java new file mode 100644 index 0000000000..78af1d2478 --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/reactor/creation/SequenceUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.reactor.creation; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SequenceUnitTest { + @Test + public void whenGeneratingNumbersWithTuplesState_thenFibonacciSequenceIsProduced() { + SequenceGenerator sequenceGenerator = new SequenceGenerator(); + Flux fibonacciFlux = sequenceGenerator.generateFibonacciWithTuples().take(5); + + StepVerifier.create(fibonacciFlux) + .expectNext(0, 1, 1, 2, 3) + .expectComplete() + .verify(); + } + + @Test + public void whenGeneratingNumbersWithCustomClass_thenFibonacciSequenceIsProduced() { + SequenceGenerator sequenceGenerator = new SequenceGenerator(); + + StepVerifier.create(sequenceGenerator.generateFibonacciWithCustomClass(10)) + .expectNext(0, 1, 1, 2, 3, 5, 8) + .expectComplete() + .verify(); + } + + @Test + public void whenCreatingNumbers_thenSequenceIsProducedAsynchronously() throws InterruptedException { + SequenceGenerator sequenceGenerator = new SequenceGenerator(); + List sequence1 = sequenceGenerator.generateFibonacciWithTuples().take(3).collectList().block(); + List sequence2 = sequenceGenerator.generateFibonacciWithTuples().take(4).collectList().block(); + + SequenceCreator sequenceCreator = new SequenceCreator(); + Thread producingThread1 = new Thread( + () -> sequenceCreator.consumer.accept(sequence1) + ); + Thread producingThread2 = new Thread( + () -> sequenceCreator.consumer.accept(sequence2) + ); + + List consolidated = new ArrayList<>(); + sequenceCreator.createNumberSequence().subscribe(consolidated::add); + + producingThread1.start(); + producingThread2.start(); + producingThread1.join(); + producingThread2.join(); + + assertThat(consolidated).containsExactlyInAnyOrder(0, 1, 1, 0, 1, 1, 2); + } + + @Test + public void whenHandlingNumbers_thenSequenceIsMappedAndFiltered() { + SequenceHandler sequenceHandler = new SequenceHandler(); + SequenceGenerator sequenceGenerator = new SequenceGenerator(); + Flux sequence = sequenceGenerator.generateFibonacciWithTuples().take(10); + + StepVerifier.create(sequenceHandler.handleIntegerSequence(sequence)) + .expectNext(0, 1, 4, 17) + .expectComplete() + .verify(); + } +} From 22dea679618d7e7ba460f14290643ae7015c0985 Mon Sep 17 00:00:00 2001 From: TINO Date: Wed, 13 Mar 2019 20:07:48 +0300 Subject: [PATCH 199/254] BAEL - 1060 Review comments incorporated --- .../rxjava/RxJavaHooksManualTest.java | 84 +++++++++++++++++++ .../baeldung/rxjava/RxJavaHooksUnitTest.java | 61 -------------- 2 files changed, 84 insertions(+), 61 deletions(-) create mode 100644 rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java new file mode 100644 index 0000000000..b79fa9af22 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java @@ -0,0 +1,84 @@ +package com.baeldung.rxjava; + +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Test; + +import io.reactivex.Observable; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; + +public class RxJavaHooksManualTest { + + private boolean initHookCalled = false; + private boolean hookCalled = false; + + @Test + public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.io()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @Test + public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() { + + RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 15) + .map(v -> v * 2) + .subscribeOn(Schedulers.newThread()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @Test + public void givenSingleScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + assertTrue(hookCalled && initHookCalled); + + } + + @After + public void reset() { + hookCalled = false; + initHookCalled = false; + RxJavaPlugins.reset(); + } +} diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java index 79b80f71ab..dd4287a4a9 100644 --- a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java @@ -235,67 +235,6 @@ public class RxJavaHooksUnitTest { assertTrue(hookCalled && initHookCalled); } - @Test - public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() { - - RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - - RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.io()) - .test(); - assertTrue(hookCalled && initHookCalled); - } - - @Test - public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() { - - RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - - RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 15) - .map(v -> v * 2) - .subscribeOn(Schedulers.newThread()) - .test(); - assertTrue(hookCalled && initHookCalled); - } - - @Test - public void givenSingleScheduler_whenCalled_shouldExecuteTheHooks() { - - RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - - RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.single()) - .test(); - assertTrue(hookCalled && initHookCalled); - - } - @After public void reset() { initHookCalled = false; From ddd3591e0b11a0d04c469e1c5271b0c43d0228cb Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Wed, 13 Mar 2019 23:10:59 +0530 Subject: [PATCH 200/254] BAEL-13321 Fixed test-data creation logic in live test --- .../com/baeldung/projection/SpringDataProjectionLiveTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java index ad219ccd53..274ae3bc1d 100644 --- a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java @@ -37,7 +37,7 @@ public class SpringDataProjectionLiveTest { @Before public void setup() { - if (bookRepo.findById(1L) == null) { + if (!bookRepo.findById(1L).isPresent()) { Book book = new Book("Animal Farm"); book.setIsbn("978-1943138425"); book = bookRepo.save(book); From 64418480e70e0eb4ca1d614edf11b2902c7b9463 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:09:25 +0800 Subject: [PATCH 201/254] Update README.md --- spring-security-mvc-ldap/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-security-mvc-ldap/README.md b/spring-security-mvc-ldap/README.md index fe6a667c40..ac080c138d 100644 --- a/spring-security-mvc-ldap/README.md +++ b/spring-security-mvc-ldap/README.md @@ -6,7 +6,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Article: - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) -- [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication) - [Intro to Spring Security LDAP](http://www.baeldung.com/spring-security-ldap) ### Notes From d2196736f9cd30fad1627ab6f122c01132279dd2 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:09:57 +0800 Subject: [PATCH 202/254] Update README.md --- spring-all/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-all/README.md b/spring-all/README.md index 81dd435007..82d876768e 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -22,7 +22,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Guide to the Spring Task Scheduler](http://www.baeldung.com/spring-task-scheduler) - [Guide to Spring Retry](http://www.baeldung.com/spring-retry) - [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope) -- [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent) - [A CLI with Spring Shell](http://www.baeldung.com/spring-shell-cli) - [JasperReports with Spring](http://www.baeldung.com/spring-jasper) - [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view) From 801605392b404134c2bf6177d2f7543d0f04f7ff Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:11:14 +0800 Subject: [PATCH 203/254] Update README.md --- spring-mvc-java/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 851a3689ab..497b0f4c1f 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -29,6 +29,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) -- [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) From f6de1aff0ab620ba36dd148db52e6a875632aa20 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:11:50 +0800 Subject: [PATCH 204/254] Update README.MD --- spring-session/spring-session-jdbc/README.MD | 2 -- 1 file changed, 2 deletions(-) diff --git a/spring-session/spring-session-jdbc/README.MD b/spring-session/spring-session-jdbc/README.MD index 9293dfc953..94fd1cd3e7 100644 --- a/spring-session/spring-session-jdbc/README.MD +++ b/spring-session/spring-session-jdbc/README.MD @@ -2,5 +2,3 @@ This module is for Spring Session with JDBC tutorial. Jira BAEL-1911 ### Relevant Articles: - -- [Spring Session with JDBC](http://www.baeldung.com/spring-session-jdbc) From d66aa3c28df5a4bac6a306687a2a1f12fc73d040 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:12:08 +0800 Subject: [PATCH 205/254] Rename README.MD to README.md --- spring-session/spring-session-jdbc/{README.MD => README.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename spring-session/spring-session-jdbc/{README.MD => README.md} (100%) diff --git a/spring-session/spring-session-jdbc/README.MD b/spring-session/spring-session-jdbc/README.md similarity index 100% rename from spring-session/spring-session-jdbc/README.MD rename to spring-session/spring-session-jdbc/README.md From 7d3486e19af3603f5814a0485920a4fe573fffaf Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:12:25 +0800 Subject: [PATCH 206/254] Update README.md --- spring-session/spring-session-redis/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-session/spring-session-redis/README.md b/spring-session/spring-session-redis/README.md index 5e9304d778..5865913711 100644 --- a/spring-session/spring-session-redis/README.md +++ b/spring-session/spring-session-redis/README.md @@ -3,4 +3,3 @@ ## Spring Session Examples ### Relevant Articles: -- [Guide to Spring Session](http://www.baeldung.com/spring-session) From 5b89544fb72fd85e0f3532a99d077ae4a58d8ca7 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:16:46 +0800 Subject: [PATCH 207/254] Update README.md --- core-java/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/core-java/README.md b/core-java/README.md index ff20f736e0..e1325ab29f 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -29,7 +29,6 @@ - [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) - [Class Loaders in Java](http://www.baeldung.com/java-classloaders) -- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Guide to Java Clock Class](http://www.baeldung.com/java-clock) - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) - [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) @@ -51,4 +50,3 @@ - [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) -- [Sending Emails with Java](https://www.baeldung.com/java-email) From 9a41f5983dcdad5170b6b0ff6f602ee681497e18 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:17:15 +0800 Subject: [PATCH 208/254] Update README.md --- httpclient/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/httpclient/README.md b/httpclient/README.md index 7c5122c5b8..87fb38706d 100644 --- a/httpclient/README.md +++ b/httpclient/README.md @@ -12,7 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [HttpClient 4 – Cancel / Abort Request](http://www.baeldung.com/httpclient-cancel-request) - [HttpClient 4 Cookbook](http://www.baeldung.com/httpclient4) - [Unshorten URLs with HttpClient](http://www.baeldung.com/unshorten-url-httpclient) -- [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) - [HttpClient 4 – Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post) - [Custom HTTP Header with the HttpClient](http://www.baeldung.com/httpclient-custom-http-header) - [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication) From 608db123a8b2e6a5ff445a7900dbe9f7eae7a7d1 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:17:39 +0800 Subject: [PATCH 209/254] Update README.md --- spring-5-mvc/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index fa9d48ab72..7e83077f54 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -2,4 +2,3 @@ - [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) - [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) -- [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) From fa3020aa3e169f9faa3da1c830c1c93cb04ffce2 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:18:09 +0800 Subject: [PATCH 210/254] Update README.md --- spring-rest-simple/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-rest-simple/README.md b/spring-rest-simple/README.md index 179e556202..882d0ac301 100644 --- a/spring-rest-simple/README.md +++ b/spring-rest-simple/README.md @@ -3,6 +3,5 @@ - [Guide to UriComponentsBuilder in Spring](http://www.baeldung.com/spring-uricomponentsbuilder) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) - [Spring RequestMapping](http://www.baeldung.com/spring-requestmapping) -- [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) - [Spring and Apache FileUpload](http://www.baeldung.com/spring-apache-file-upload) - [Test a REST API with curl](http://www.baeldung.com/curl-rest) From 97ec5d69562dbe59657828bcf7dbe3d4bf9f7c2e Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:18:33 +0800 Subject: [PATCH 211/254] Update README.md --- gradle/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/gradle/README.md b/gradle/README.md index a1f5c74c57..14e460f225 100644 --- a/gradle/README.md +++ b/gradle/README.md @@ -3,5 +3,4 @@ - [Writing Custom Gradle Plugins](http://www.baeldung.com/gradle-create-plugin) - [Creating a Fat Jar in Gradle](http://www.baeldung.com/gradle-fat-jar) - [A Custom Task in Gradle](http://www.baeldung.com/gradle-custom-task) -- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection) - [Using JUnit 5 with Gradle](https://www.baeldung.com/junit-5-gradle) From 17a5f6f6ed34d755c7ebca340f63f1514d80c200 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:19:23 +0800 Subject: [PATCH 212/254] Update README.md --- spring-rest-full/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index ed6df1675f..e0d3a70626 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -12,7 +12,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Project Configuration with Spring](http://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) -- [Bootstrap a Web Application with Spring 5](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) From e6e26f6947cab6a028aad48bbd7bbdc42ff0cc99 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:19:56 +0800 Subject: [PATCH 213/254] Update README.md --- spring-boot-bootstrap/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 70fcd90118..6a88f25bd7 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -1,6 +1,5 @@ ### Relevant Articles: - [Spring Boot Tutorial – Bootstrap a Simple Application](http://www.baeldung.com/spring-boot-start) -- [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) - [Thin JARs with Spring Boot](http://www.baeldung.com/spring-boot-thin-jar) - [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry) - [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine) From c1ae56b3bfdb13463be7a0e6320d39001e41a2e6 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:21:46 +0800 Subject: [PATCH 214/254] Update README.md --- logging-modules/log4j/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/logging-modules/log4j/README.md b/logging-modules/log4j/README.md index 9f4184ccba..a7a7ea9643 100644 --- a/logging-modules/log4j/README.md +++ b/logging-modules/log4j/README.md @@ -1,7 +1,5 @@ ### Relevant Articles: - [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro) - [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) -- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) -- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) - [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders) - [Logging Exceptions Using SLF4J](https://www.baeldung.com/slf4j-log-exceptions) From 8f5c4b0c891205d2886979a74049c287b38abcb3 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:23:29 +0800 Subject: [PATCH 215/254] Update README.md --- google-web-toolkit/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/google-web-toolkit/README.md b/google-web-toolkit/README.md index 65264375bc..3526fe9962 100644 --- a/google-web-toolkit/README.md +++ b/google-web-toolkit/README.md @@ -1,3 +1,2 @@ ### Relevant Articles: - [Introduction to GWT](http://www.baeldung.com/gwt) -- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) From d8931291f742ad958a650e9481e61275272f8874 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:26:38 +0800 Subject: [PATCH 216/254] Delete README.md --- .../src/main/java/com/baeldung/enums/README.md | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md b/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md deleted file mode 100644 index 6ccfa725f5..0000000000 --- a/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) From 00dc9ff6850c21c46e3688462353451a91fbf1ae Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:29:41 +0800 Subject: [PATCH 217/254] Update README.md --- guava-modules/guava-18/README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/guava-modules/guava-18/README.md b/guava-modules/guava-18/README.md index 9924d7c16f..fd5de4170a 100644 --- a/guava-modules/guava-18/README.md +++ b/guava-modules/guava-18/README.md @@ -4,9 +4,5 @@ ### Relevant Articles: -- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections) -- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order) - [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates) -- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays) -- [Partition a List in Java](http://www.baeldung.com/java-list-split) - [Guava 18: What’s New?](http://www.baeldung.com/whats-new-in-guava-18) From 78fe53192c452479665c2d74de1d18646bb6a6a3 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:31:00 +0800 Subject: [PATCH 218/254] Update README.md --- apache-fop/README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/apache-fop/README.md b/apache-fop/README.md index 772681ad57..1e734a5f36 100644 --- a/apache-fop/README.md +++ b/apache-fop/README.md @@ -3,7 +3,3 @@ ## Core Java Cookbooks and Examples ### Relevant Articles: -- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list) -- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file) -- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string) - From 0bb77443469b995c8ff1008fa9e71ee6e6b443c5 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:31:42 +0800 Subject: [PATCH 219/254] Update README.md --- core-java-lang-oop/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-lang-oop/README.md b/core-java-lang-oop/README.md index 200415fe21..970a8d44b1 100644 --- a/core-java-lang-oop/README.md +++ b/core-java-lang-oop/README.md @@ -5,7 +5,6 @@ ### Relevant Articles: - [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode) - [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) -- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) - [Polymorphism in Java](http://www.baeldung.com/java-polymorphism) - [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override) - [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy) From 52dbb4a9f8ee484e5acde21e4608f53265c7abfe Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:32:58 +0800 Subject: [PATCH 220/254] Update README.md --- core-java-io/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-io/README.md b/core-java-io/README.md index 22901b22d5..05b9165147 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -30,7 +30,6 @@ - [Download a File From an URL in Java](http://www.baeldung.com/java-download-file) - [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink) - [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) -- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) - [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist) - [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream) - [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array) From b7e197ee6459cad56c5fb4b1cc629a9dbba65cac Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:40:57 +0800 Subject: [PATCH 221/254] Update README.md --- testing-modules/mocks/README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/testing-modules/mocks/README.md b/testing-modules/mocks/README.md index 2b24ed8536..3cb20dcf92 100644 --- a/testing-modules/mocks/README.md +++ b/testing-modules/mocks/README.md @@ -1,8 +1,4 @@ ## Relevant articles: -- [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage) -- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) -- [JMockit 101](http://www.baeldung.com/jmockit-101) -- [Mockito vs EasyMock vs JMockit](http://www.baeldung.com/mockito-vs-easymock-vs-jmockit) - [EasyMock Argument Matchers](http://www.baeldung.com/easymock-argument-matchers) - [Mock Static Method using JMockit](https://www.baeldung.com/jmockit-static-method) From e7d06b00044b05bb3434e3ee3aae27b4e989d67d Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:41:20 +0800 Subject: [PATCH 222/254] Update README.md --- testing-modules/mocks/jmockit/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/testing-modules/mocks/jmockit/README.md b/testing-modules/mocks/jmockit/README.md index 3063fdc31d..0e44b93d6e 100644 --- a/testing-modules/mocks/jmockit/README.md +++ b/testing-modules/mocks/jmockit/README.md @@ -6,5 +6,4 @@ ### Relevant Articles: - [JMockit 101](http://www.baeldung.com/jmockit-101) - [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) -- [JMockit Advanced Topics](http://www.baeldung.com/jmockit-advanced-topics) - [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage) From 6a7e36193b973e1c44951d176eae27784bbada69 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:42:26 +0800 Subject: [PATCH 223/254] Delete README.md --- noexception/README.md | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 noexception/README.md diff --git a/noexception/README.md b/noexception/README.md deleted file mode 100644 index 9dd4c11190..0000000000 --- a/noexception/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception) From e681a5447a76236a4b7ffcaa3052a69d0ef3202f Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:44:44 +0800 Subject: [PATCH 224/254] Delete README.md --- testing-modules/junit5-migration/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 testing-modules/junit5-migration/README.md diff --git a/testing-modules/junit5-migration/README.md b/testing-modules/junit5-migration/README.md deleted file mode 100644 index 5fe7fc1f16..0000000000 --- a/testing-modules/junit5-migration/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: -- [JUnit4 -> JUnit5 migration guide](http://www.baeldung.com/junit4-junit5-migration-guide) - From 6869885cf415e7268adca1ff1426cb8dd2d47993 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Wed, 13 Mar 2019 19:45:09 +0000 Subject: [PATCH 225/254] BAEL-2522 Moved to another module --- java-dates-2/.gitignore | 29 ++++++++++ java-dates-2/pom.xml | 55 +++++++++++++++++++ ...XmlGregorianCalendarConverterUnitTest.java | 6 +- 3 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 java-dates-2/.gitignore create mode 100644 java-dates-2/pom.xml rename java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java => java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java (85%) diff --git a/java-dates-2/.gitignore b/java-dates-2/.gitignore new file mode 100644 index 0000000000..6471aabbcf --- /dev/null +++ b/java-dates-2/.gitignore @@ -0,0 +1,29 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml + +#jenv +.java-version \ No newline at end of file diff --git a/java-dates-2/pom.xml b/java-dates-2/pom.xml new file mode 100644 index 0000000000..93216e3ffa --- /dev/null +++ b/java-dates-2/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + com.baeldung + java-dates-2 + 0.1.0-SNAPSHOT + jar + java-dates-2 + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-dates-2 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + 3.6.1 + 1.9 + 1.9 + + diff --git a/java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java b/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java similarity index 85% rename from java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java rename to java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java index 7fe1cd36a1..34510a3167 100644 --- a/java-dates/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterTest.java +++ b/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java @@ -7,11 +7,9 @@ import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.time.LocalDate; -import static com.baeldung.xmlgregoriancalendar.XmlGregorianCalendarConverter.fromLocalDate; -import static com.baeldung.xmlgregoriancalendar.XmlGregorianCalendarConverter.fromXMLGregorianCalendar; import static org.assertj.core.api.Assertions.assertThat; -public class XmlGregorianCalendarConverterTest { +public class XmlGregorianCalendarConverterUnitTest { @Test public void fromLocalDateToXMLGregorianCalendar() throws DatatypeConfigurationException { @@ -32,5 +30,5 @@ public class XmlGregorianCalendarConverterTest { assertThat(localDate.getMonthValue()).isEqualTo(xmlGregorianCalendar.getMonth()); assertThat(localDate.getDayOfMonth()).isEqualTo(xmlGregorianCalendar.getDay()); } - + } From 557049bbd1d560b16ab5182639e01856b29e742f Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Mar 2019 03:45:40 +0800 Subject: [PATCH 226/254] Update README.md --- jjwt/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/jjwt/README.md b/jjwt/README.md index 54a5226056..ed18363dfc 100644 --- a/jjwt/README.md +++ b/jjwt/README.md @@ -42,7 +42,6 @@ Available commands (assumes httpie - https://github.com/jkbrzt/httpie): Parse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim ``` -The Baeldung post that compliments this repo can be found [here](http://www.baeldung.com/) ## Relevant articles: From bde5b5f559adbfd5508a23c24fb54d977339806e Mon Sep 17 00:00:00 2001 From: mikr Date: Sun, 10 Mar 2019 19:28:09 +0100 Subject: [PATCH 227/254] BAEL-2562 New section in Generics article --- .../src/main/java/com/baeldung/generics/Generics.java | 7 +++++++ .../java/com/baeldung/generics/GenericsUnitTest.java | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java b/core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java index e0536ca02e..1c4082c58b 100644 --- a/core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java +++ b/core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java @@ -1,5 +1,6 @@ package com.baeldung.generics; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; @@ -28,4 +29,10 @@ public class Generics { buildings.forEach(Building::paint); } + public static List createList(int a) { + List list = new ArrayList<>(); + list.add(a); + return list; + } + } \ No newline at end of file diff --git a/core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java index aca0b182a0..0bdf0afc15 100644 --- a/core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java +++ b/core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java @@ -6,6 +6,7 @@ import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; @@ -66,4 +67,12 @@ public class GenericsUnitTest { } } + @Test + public void givenAnInt_whenAddedToAGenericIntegerList_thenAListItemCanBeAssignedToAnInt() { + int number = 7; + List list = Generics.createList(number); + int otherNumber = list.get(0); + assertThat(otherNumber, is(number)); + } + } \ No newline at end of file From f90dd073cb63e823d6563826d4d5b12aadaed49c Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Thu, 14 Mar 2019 09:32:06 +0000 Subject: [PATCH 228/254] BAEL-2522 - Updated parent pom with the new module --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 58d57ade05..ac1273b28d 100644 --- a/pom.xml +++ b/pom.xml @@ -440,6 +440,7 @@ java-collections-conversions java-collections-maps + java-dates-2 java-lite java-numbers From 05e3bf3a828f6d9c056de42b47bf8e642a4a4c3f Mon Sep 17 00:00:00 2001 From: jarpz Date: Thu, 14 Mar 2019 14:54:14 -0500 Subject: [PATCH 229/254] How to return 404 with Spring WebFlux (#6509) * feat(response-status): return response http status * fix(style): improve code style * BAEL-2716: How to return 404 with Spring WebFlux * style: apply baeldung intellij formatter * Delete .gitignore * config: remove gitignore & remove unused maven plugin --- spring-5-webflux/pom.xml | 70 +++++++++++++++++++ .../ResponseStatusController.java | 64 +++++++++++++++++ .../SpringResponseStatusApp.java | 12 ++++ .../ResponseStatusControllerTests.java | 70 +++++++++++++++++++ 4 files changed, 216 insertions(+) create mode 100644 spring-5-webflux/pom.xml create mode 100644 spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/ResponseStatusController.java create mode 100644 spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/SpringResponseStatusApp.java create mode 100644 spring-5-webflux/src/test/java/com/baeldung/spring/responsestatus/ResponseStatusControllerTests.java diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml new file mode 100644 index 0000000000..d7fb7b7930 --- /dev/null +++ b/spring-5-webflux/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.baeldung + spring-5-webflux + 1.0-SNAPSHOT + + spring-5-webflux + + http://www.baeldung.com + + + UTF-8 + 1.8 + 1.8 + 2.0.2.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.projectlombok + lombok + + + + org.springframework.boot + spring-boot-starter-test + test + + + + junit + junit + test + + + + + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + + diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/ResponseStatusController.java b/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/ResponseStatusController.java new file mode 100644 index 0000000000..bc4f628ab1 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/ResponseStatusController.java @@ -0,0 +1,64 @@ +package com.baeldung.spring.responsestatus; + +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; + +@RequestMapping("/statuses") +@RestController +public class ResponseStatusController { + + @GetMapping(value = "/ok", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + public Flux ok() { + return Flux.just("ok"); + } + + @GetMapping(value = "/no-content", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @ResponseStatus(HttpStatus.NO_CONTENT) + public Flux noContent() { + return Flux.empty(); + } + + @GetMapping(value = "/accepted", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + public Flux accepted(ServerHttpResponse response) { + response.setStatusCode(HttpStatus.ACCEPTED); + return Flux.just("accepted"); + } + + @GetMapping(value = "/bad-request") + public Mono badRequest() { + return Mono.error(new IllegalArgumentException()); + } + + @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal arguments") + @ExceptionHandler(IllegalArgumentException.class) + public void illegalArgument() { + + } + + @GetMapping(value = "/unauthorized") + public ResponseEntity> unathorized() { + return ResponseEntity + .status(HttpStatus.UNAUTHORIZED) + .header("X-Reason", "user-invalid") + .body(Mono.just("unauthorized")); + } + + @Bean + public RouterFunction notFound() { + return RouterFunctions.route(GET("/statuses/not-found"), request -> ServerResponse + .notFound() + .build()); + } + +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/SpringResponseStatusApp.java b/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/SpringResponseStatusApp.java new file mode 100644 index 0000000000..1d90511d9d --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/SpringResponseStatusApp.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.responsestatus; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringResponseStatusApp { + + public static void main(String[] args) { + SpringApplication.run(SpringResponseStatusApp.class, args); + } +} diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/responsestatus/ResponseStatusControllerTests.java b/spring-5-webflux/src/test/java/com/baeldung/spring/responsestatus/ResponseStatusControllerTests.java new file mode 100644 index 0000000000..5112c8ceb2 --- /dev/null +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/responsestatus/ResponseStatusControllerTests.java @@ -0,0 +1,70 @@ +package com.baeldung.spring.responsestatus; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ResponseStatusControllerTests { + + @Autowired + private WebTestClient testClient; + + @Test + public void whenCallRest_thenStatusIsOk() { + testClient.get() + .uri("/statuses/ok") + .exchange() + .expectStatus() + .isOk(); + } + + @Test + public void whenCallRest_thenStatusIsNoContent() { + testClient.get() + .uri("/statuses/no-content") + .exchange() + .expectStatus() + .isNoContent(); + } + + @Test + public void whenCallRest_thenStatusIsAccepted() { + testClient.get() + .uri("/statuses/accepted") + .exchange() + .expectStatus() + .isAccepted(); + } + + @Test + public void whenCallRest_thenStatusIsBadRequest() { + testClient.get() + .uri("/statuses/bad-request") + .exchange() + .expectStatus() + .isBadRequest(); + } + + @Test + public void whenCallRest_thenStatusIsUnauthorized() { + testClient.get() + .uri("/statuses/unauthorized") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + public void whenCallRest_thenStatusIsNotFound() { + testClient.get() + .uri("/statuses/not-found") + .exchange() + .expectStatus() + .isNotFound(); + } +} From b3fc27088b6513513fee6b3d9b4c524bda9cd02e Mon Sep 17 00:00:00 2001 From: dionisPrifti Date: Thu, 14 Mar 2019 20:55:45 +0100 Subject: [PATCH 230/254] Bael 2709 (#6527) * BAEL-2709: Implementing example for Spring Boot Hibernate. * BAEL-2709: Changed test name. --- .../application/tests/BookServiceUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java index fe8bb339a4..655a852001 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java +++ b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java @@ -19,7 +19,7 @@ public class BookServiceUnitTest { private BookService bookService; @Test - public void test() { + public void whenApplicationStarts_thenHibernateCreatesInitialRecords() { List books = bookService.list(); Assert.assertEquals(books.size(), 3); From dc72b8b39755a78670bf790d451001b331ea67bb Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Fri, 15 Mar 2019 11:22:27 +0530 Subject: [PATCH 231/254] Adding source code for the tutorial tracked under BAEL-2759 (#6533) --- pom.xml | 5 ++ tensorflow-java/.gitignore | 6 +++ tensorflow-java/README.md | 3 ++ tensorflow-java/pom.xml | 52 +++++++++++++++++++ .../baeldung/tensorflow/TensorflowGraph.java | 41 +++++++++++++++ .../tensorflow/TensorflowSavedModel.java | 14 +++++ .../src/main/python/tensorflowGraph.py | 16 ++++++ .../tensorflow/TensorflowGraphUnitTest.java | 21 ++++++++ 8 files changed, 158 insertions(+) create mode 100644 tensorflow-java/.gitignore create mode 100644 tensorflow-java/README.md create mode 100644 tensorflow-java/pom.xml create mode 100644 tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java create mode 100644 tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java create mode 100644 tensorflow-java/src/main/python/tensorflowGraph.py create mode 100644 tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java diff --git a/pom.xml b/pom.xml index 18e3ace31b..826b8eea63 100644 --- a/pom.xml +++ b/pom.xml @@ -526,6 +526,9 @@ rxjava rxjava-2 software-security/sql-injection-samples + + tensorflow-java + @@ -742,6 +745,8 @@ xml xmlunit-2 xstream + + tensorflow-java diff --git a/tensorflow-java/.gitignore b/tensorflow-java/.gitignore new file mode 100644 index 0000000000..eaea64ae48 --- /dev/null +++ b/tensorflow-java/.gitignore @@ -0,0 +1,6 @@ +/.settings +/model +/target +.classpath +.project +.springBeans \ No newline at end of file diff --git a/tensorflow-java/README.md b/tensorflow-java/README.md new file mode 100644 index 0000000000..aac5b7544c --- /dev/null +++ b/tensorflow-java/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [TensorFlow for Java](https://www.baeldung.com/xxxx) diff --git a/tensorflow-java/pom.xml b/tensorflow-java/pom.xml new file mode 100644 index 0000000000..e9d92157e8 --- /dev/null +++ b/tensorflow-java/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + com.baeldung + tensorflow-java + 1.0-SNAPSHOT + jar + http://maven.apache.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.8 + 1.12.0 + 5.4.0 + + + + + org.tensorflow + tensorflow + ${tensorflow.version} + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java b/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java new file mode 100644 index 0000000000..a44ef4c4ee --- /dev/null +++ b/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java @@ -0,0 +1,41 @@ +package org.baeldung.tensorflow; + +import org.tensorflow.DataType; +import org.tensorflow.Graph; +import org.tensorflow.Operation; +import org.tensorflow.Session; +import org.tensorflow.Tensor; + +public class TensorflowGraph { + + public static Graph createGraph() { + Graph graph = new Graph(); + Operation a = graph.opBuilder("Const", "a").setAttr("dtype", DataType.fromClass(Double.class)) + .setAttr("value", Tensor.create(3.0, Double.class)).build(); + Operation b = graph.opBuilder("Const", "b").setAttr("dtype", DataType.fromClass(Double.class)) + .setAttr("value", Tensor.create(2.0, Double.class)).build(); + Operation x = graph.opBuilder("Placeholder", "x").setAttr("dtype", DataType.fromClass(Double.class)).build(); + Operation y = graph.opBuilder("Placeholder", "y").setAttr("dtype", DataType.fromClass(Double.class)).build(); + Operation ax = graph.opBuilder("Mul", "ax").addInput(a.output(0)).addInput(x.output(0)).build(); + Operation by = graph.opBuilder("Mul", "by").addInput(b.output(0)).addInput(y.output(0)).build(); + graph.opBuilder("Add", "z").addInput(ax.output(0)).addInput(by.output(0)).build(); + return graph; + } + + public static Object runGraph(Graph graph, Double x, Double y) { + Object result; + try (Session sess = new Session(graph)) { + result = sess.runner().fetch("z").feed("x", Tensor.create(x, Double.class)) + .feed("y", Tensor.create(y, Double.class)).run().get(0).expect(Double.class) + .doubleValue(); + } + return result; + } + + public static void main(String[] args) { + Graph graph = TensorflowGraph.createGraph(); + Object result = TensorflowGraph.runGraph(graph, 3.0, 6.0); + System.out.println(result); + graph.close(); + } +} \ No newline at end of file diff --git a/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java b/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java new file mode 100644 index 0000000000..4259a787e8 --- /dev/null +++ b/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java @@ -0,0 +1,14 @@ +package org.baeldung.tensorflow; + +import org.tensorflow.SavedModelBundle; +import org.tensorflow.Tensor; + +public class TensorflowSavedModel { + + public static void main(String[] args) { + SavedModelBundle model = SavedModelBundle.load("./model", "serve"); + Tensor tensor = model.session().runner().fetch("z").feed("x", Tensor.create(3, Integer.class)) + .feed("y", Tensor.create(3, Integer.class)).run().get(0).expect(Integer.class); + System.out.println(tensor.intValue()); + } +} \ No newline at end of file diff --git a/tensorflow-java/src/main/python/tensorflowGraph.py b/tensorflow-java/src/main/python/tensorflowGraph.py new file mode 100644 index 0000000000..ab7f8810ac --- /dev/null +++ b/tensorflow-java/src/main/python/tensorflowGraph.py @@ -0,0 +1,16 @@ +import tensorflow as tf +graph = tf.Graph() +builder = tf.saved_model.builder.SavedModelBuilder('./model') +writer = tf.summary.FileWriter('.') +with graph.as_default(): + a = tf.constant(2, name='a') + b = tf.constant(3, name='b') + x = tf.placeholder(tf.int32, name='x') + y = tf.placeholder(tf.int32, name='y') + z = tf.math.add(a*x, b*y, name='z') + writer.add_graph(tf.get_default_graph()) + writer.flush() + sess = tf.Session() + sess.run(z, feed_dict = {x: 2, y: 3}) + builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING]) + builder.save() diff --git a/tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java b/tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java new file mode 100644 index 0000000000..51df6a4322 --- /dev/null +++ b/tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java @@ -0,0 +1,21 @@ +package org.baeldung.tensorflow; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Test; +import org.tensorflow.Graph; + +public class TensorflowGraphUnitTest { + + @Test + public void givenTensorflowGraphWhenRunInSessionReturnsExpectedResult() { + + Graph graph = TensorflowGraph.createGraph(); + Object result = TensorflowGraph.runGraph(graph, 3.0, 6.0); + assertEquals(21.0, result); + System.out.println(result); + graph.close(); + + } + +} From bac1103dccb43872ff84e7b3598bfc7916b927a9 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Fri, 15 Mar 2019 14:38:26 +0000 Subject: [PATCH 232/254] BAEL-2522 - Reverting changes --- java-dates-2/.gitignore | 29 ---------- java-dates-2/pom.xml | 55 ------------------- ...XmlGregorianCalendarConverterUnitTest.java | 34 ------------ pom.xml | 1 - 4 files changed, 119 deletions(-) delete mode 100644 java-dates-2/.gitignore delete mode 100644 java-dates-2/pom.xml delete mode 100644 java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java diff --git a/java-dates-2/.gitignore b/java-dates-2/.gitignore deleted file mode 100644 index 6471aabbcf..0000000000 --- a/java-dates-2/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -*.class - -0.* - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - -# Files generated by integration tests -*.txt -backup-pom.xml -/bin/ -/temp - -#IntelliJ specific -.idea/ -*.iml - -#jenv -.java-version \ No newline at end of file diff --git a/java-dates-2/pom.xml b/java-dates-2/pom.xml deleted file mode 100644 index 93216e3ffa..0000000000 --- a/java-dates-2/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - 4.0.0 - com.baeldung - java-dates-2 - 0.1.0-SNAPSHOT - jar - java-dates-2 - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - java-dates-2 - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - - - 3.6.1 - 1.9 - 1.9 - - diff --git a/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java b/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java deleted file mode 100644 index 34510a3167..0000000000 --- a/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.xmlgregoriancalendar; - -import org.junit.Test; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -public class XmlGregorianCalendarConverterUnitTest { - - @Test - public void fromLocalDateToXMLGregorianCalendar() throws DatatypeConfigurationException { - LocalDate localDate = LocalDate.of(2017, 4, 25); - XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString()); - - assertThat(xmlGregorianCalendar.getYear()).isEqualTo(localDate.getYear()); - assertThat(xmlGregorianCalendar.getMonth()).isEqualTo(localDate.getMonthValue()); - assertThat(xmlGregorianCalendar.getDay()).isEqualTo(localDate.getDayOfMonth()); - } - - @Test - public void fromXMLGregorianCalendarToLocalDate() throws DatatypeConfigurationException { - XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-04-25"); - LocalDate localDate = LocalDate.of(xmlGregorianCalendar.getYear(), xmlGregorianCalendar.getMonth(), xmlGregorianCalendar.getDay()); - - assertThat(localDate.getYear()).isEqualTo(xmlGregorianCalendar.getYear()); - assertThat(localDate.getMonthValue()).isEqualTo(xmlGregorianCalendar.getMonth()); - assertThat(localDate.getDayOfMonth()).isEqualTo(xmlGregorianCalendar.getDay()); - } - -} diff --git a/pom.xml b/pom.xml index ac1273b28d..58d57ade05 100644 --- a/pom.xml +++ b/pom.xml @@ -440,7 +440,6 @@ java-collections-conversions java-collections-maps - java-dates-2 java-lite java-numbers From 9b6a3a0f881e71df01327ef778d772df5ca5aa3e Mon Sep 17 00:00:00 2001 From: cdjole Date: Fri, 15 Mar 2019 17:56:19 +0100 Subject: [PATCH 233/254] New module core-java-jvm added (#6539) --- core-java-jvm/README.md | 6 +++ core-java-jvm/pom.xml | 40 +++++++++++++++++++ .../inlining/ConsecutiveNumbersSum.java | 0 .../baeldung/inlining/InliningExample.java | 0 .../ConsecutiveNumbersSumUnitTest.java | 0 pom.xml | 3 +- 6 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 core-java-jvm/README.md create mode 100644 core-java-jvm/pom.xml rename {core-java => core-java-jvm}/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java (100%) rename {core-java => core-java-jvm}/src/main/java/com/baeldung/inlining/InliningExample.java (100%) rename {core-java => core-java-jvm}/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java (100%) diff --git a/core-java-jvm/README.md b/core-java-jvm/README.md new file mode 100644 index 0000000000..529453f3c4 --- /dev/null +++ b/core-java-jvm/README.md @@ -0,0 +1,6 @@ +========= + +## Core Java JVM Cookbooks and Examples + +### Relevant Articles: +- [Method Inlining in the JVM](http://www.baeldung.com/method-inlining-in-the-jvm/) diff --git a/core-java-jvm/pom.xml b/core-java-jvm/pom.xml new file mode 100644 index 0000000000..752b26f03f --- /dev/null +++ b/core-java-jvm/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + com.baeldung + core-java-jvm + 0.1.0-SNAPSHOT + jar + core-java-jvm + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + junit + junit + ${junit.version} + test + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 3.5 + 3.6.1 + + diff --git a/core-java/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java b/core-java-jvm/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java similarity index 100% rename from core-java/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java rename to core-java-jvm/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java diff --git a/core-java/src/main/java/com/baeldung/inlining/InliningExample.java b/core-java-jvm/src/main/java/com/baeldung/inlining/InliningExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/inlining/InliningExample.java rename to core-java-jvm/src/main/java/com/baeldung/inlining/InliningExample.java diff --git a/core-java/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java b/core-java-jvm/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java rename to core-java-jvm/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java diff --git a/pom.xml b/pom.xml index 826b8eea63..5858df01e1 100644 --- a/pom.xml +++ b/pom.xml @@ -393,7 +393,8 @@ core-java-networking core-java-perf core-java-sun - core-java + core-java + core-java-jvm core-scala couchbase custom-pmd From 2b28336cd6f7709d1751a2d5f1838017e69b8266 Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Fri, 15 Mar 2019 23:45:56 +0100 Subject: [PATCH 234/254] Add the code for article "Kotlin Annotations" (BAEL-2579) (#6540) --- .../com/baeldung/annotations/Annotations.kt | 7 ++++ .../kotlin/com/baeldung/annotations/Item.kt | 3 ++ .../kotlin/com/baeldung/annotations/Main.kt | 7 ++++ .../com/baeldung/annotations/Validator.kt | 38 +++++++++++++++++ .../annotations/ValidationUnitTest.kt | 42 +++++++++++++++++++ 5 files changed, 97 insertions(+) create mode 100644 core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Annotations.kt create mode 100644 core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Item.kt create mode 100644 core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Main.kt create mode 100644 core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Validator.kt create mode 100644 core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationUnitTest.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Annotations.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Annotations.kt new file mode 100644 index 0000000000..a8f83446dc --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Annotations.kt @@ -0,0 +1,7 @@ +package com.baeldung.annotations + +@Target(AnnotationTarget.FIELD) +annotation class Positive + +@Target(AnnotationTarget.FIELD) +annotation class AllowedNames(val names: Array) diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Item.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Item.kt new file mode 100644 index 0000000000..6864fe416e --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Item.kt @@ -0,0 +1,3 @@ +package com.baeldung.annotations + +class Item(@Positive val amount: Float, @AllowedNames(["Alice", "Bob"]) val name: String) \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Main.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Main.kt new file mode 100644 index 0000000000..2b7f2c5590 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Main.kt @@ -0,0 +1,7 @@ +package com.baeldung.annotations + +fun main(args: Array) { + val item = Item(amount = 1.0f, name = "Bob") + val validator = Validator() + println("Is instance valid? ${validator.isValid(item)}") +} diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Validator.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Validator.kt new file mode 100644 index 0000000000..40139048ab --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Validator.kt @@ -0,0 +1,38 @@ +package com.baeldung.annotations + +/** + * Naive annotation-based validator. + * @author A.Shcherbakov + */ +class Validator() { + + /** + * Return true if every item's property annotated with @Positive is positive and if + * every item's property annotated with @AllowedNames has a value specified in that annotation. + */ + fun isValid(item: Item): Boolean { + val fields = item::class.java.declaredFields + for (field in fields) { + field.isAccessible = true + for (annotation in field.annotations) { + val value = field.get(item) + if (field.isAnnotationPresent(Positive::class.java)) { + val amount = value as Float + if (amount < 0) { + return false + } + } + if (field.isAnnotationPresent(AllowedNames::class.java)) { + val allowedNames = field.getAnnotation(AllowedNames::class.java)?.names + val name = value as String + allowedNames?.let { + if (!it.contains(name)) { + return false + } + } + } + } + } + return true + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationUnitTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationUnitTest.kt new file mode 100644 index 0000000000..506b7a24b5 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationUnitTest.kt @@ -0,0 +1,42 @@ +package com.baeldung.annotations + +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Test + + +class ValidationUnitTest { + + @Test + fun whenAmountIsOneAndNameIsAlice_thenTrue() { + assertTrue(Validator().isValid(Item(1f, "Alice"))) + } + + @Test + fun whenAmountIsOneAndNameIsBob_thenTrue() { + assertTrue(Validator().isValid(Item(1f, "Bob"))) + } + + + @Test + fun whenAmountIsMinusOneAndNameIsAlice_thenFalse() { + assertFalse(Validator().isValid(Item(-1f, "Alice"))) + } + + @Test + fun whenAmountIsMinusOneAndNameIsBob_thenFalse() { + assertFalse(Validator().isValid(Item(-1f, "Bob"))) + } + + @Test + fun whenAmountIsOneAndNameIsTom_thenFalse() { + assertFalse(Validator().isValid(Item(1f, "Tom"))) + } + + @Test + fun whenAmountIsMinusOneAndNameIsTom_thenFalse() { + assertFalse(Validator().isValid(Item(-1f, "Tom"))) + } + + +} \ No newline at end of file From 4ef58c00667058c2cd6ebd7d64285b4e0ee5d84a Mon Sep 17 00:00:00 2001 From: Dhananjay Singh Date: Sat, 16 Mar 2019 12:45:16 +0100 Subject: [PATCH 235/254] Modified tests --- .../controller/AppControllerIntegrationTest.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java index 9ad940683f..a55c0a69e4 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java @@ -60,7 +60,7 @@ public class AppControllerIntegrationTest { .statusCode(HttpStatus.OK.value()) .body("id", equalTo(testMovie.getId())) .body("name", equalTo(testMovie.getName())) - .body("synopsis", equalTo(testMovie.getSynopsis())); + .body("synopsis", notNullValue()); Movie result = get(uri + "/movie/" + testMovie.getId()).then() .assertThat() @@ -68,6 +68,13 @@ public class AppControllerIntegrationTest { .extract() .as(Movie.class); assertThat(result).isEqualTo(testMovie); + + String responseString = get(uri + "/movie/" + testMovie.getId()).then() + .assertThat() + .statusCode(HttpStatus.OK.value()) + .extract() + .asString(); + assertThat(responseString).isNotEmpty(); } @Test From 6ad4766776065f629a3f05ccc75fee8bc60e0422 Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Sat, 16 Mar 2019 15:50:04 +0100 Subject: [PATCH 236/254] Adjust the unit test (#6543) * Add the code for article "Kotlin Annotations" (BAEL-2579) * Adjust the Validation test --- .../baeldung/annotations/ValidationTest.kt | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt new file mode 100644 index 0000000000..97fb3434ee --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt @@ -0,0 +1,41 @@ +package com.baeldung.annotations + +import org.junit.Test +import kotlin.test.assertTrue +import kotlin.test.assertFalse + +class ValidationUnitTest { + + @Test + fun whenAmountIsOneAndNameIsAlice_thenTrue() { + assertTrue(Validator().isValid(Item(1f, "Alice"))) + } + + @Test + fun whenAmountIsOneAndNameIsBob_thenTrue() { + assertTrue(Validator().isValid(Item(1f, "Bob"))) + } + + + @Test + fun whenAmountIsMinusOneAndNameIsAlice_thenFalse() { + assertFalse(Validator().isValid(Item(-1f, "Alice"))) + } + + @Test + fun whenAmountIsMinusOneAndNameIsBob_thenFalse() { + assertFalse(Validator().isValid(Item(-1f, "Bob"))) + } + + @Test + fun whenAmountIsOneAndNameIsTom_thenFalse() { + assertFalse(Validator().isValid(Item(1f, "Tom"))) + } + + @Test + fun whenAmountIsMinusOneAndNameIsTom_thenFalse() { + assertFalse(Validator().isValid(Item(-1f, "Tom"))) + } + + +} \ No newline at end of file From d5e91a8d341ee6e937061c20db9e17d0b8594a8c Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Sat, 16 Mar 2019 22:15:22 +0000 Subject: [PATCH 237/254] Revert "BAEL-2522 - Reverting changes" This reverts commit bac1103dccb43872ff84e7b3598bfc7916b927a9. --- java-dates-2/.gitignore | 29 ++++++++++ java-dates-2/pom.xml | 55 +++++++++++++++++++ ...XmlGregorianCalendarConverterUnitTest.java | 34 ++++++++++++ pom.xml | 1 + 4 files changed, 119 insertions(+) create mode 100644 java-dates-2/.gitignore create mode 100644 java-dates-2/pom.xml create mode 100644 java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java diff --git a/java-dates-2/.gitignore b/java-dates-2/.gitignore new file mode 100644 index 0000000000..6471aabbcf --- /dev/null +++ b/java-dates-2/.gitignore @@ -0,0 +1,29 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml + +#jenv +.java-version \ No newline at end of file diff --git a/java-dates-2/pom.xml b/java-dates-2/pom.xml new file mode 100644 index 0000000000..93216e3ffa --- /dev/null +++ b/java-dates-2/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + com.baeldung + java-dates-2 + 0.1.0-SNAPSHOT + jar + java-dates-2 + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-dates-2 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + 3.6.1 + 1.9 + 1.9 + + diff --git a/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java b/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java new file mode 100644 index 0000000000..34510a3167 --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.xmlgregoriancalendar; + +import org.junit.Test; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +public class XmlGregorianCalendarConverterUnitTest { + + @Test + public void fromLocalDateToXMLGregorianCalendar() throws DatatypeConfigurationException { + LocalDate localDate = LocalDate.of(2017, 4, 25); + XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString()); + + assertThat(xmlGregorianCalendar.getYear()).isEqualTo(localDate.getYear()); + assertThat(xmlGregorianCalendar.getMonth()).isEqualTo(localDate.getMonthValue()); + assertThat(xmlGregorianCalendar.getDay()).isEqualTo(localDate.getDayOfMonth()); + } + + @Test + public void fromXMLGregorianCalendarToLocalDate() throws DatatypeConfigurationException { + XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-04-25"); + LocalDate localDate = LocalDate.of(xmlGregorianCalendar.getYear(), xmlGregorianCalendar.getMonth(), xmlGregorianCalendar.getDay()); + + assertThat(localDate.getYear()).isEqualTo(xmlGregorianCalendar.getYear()); + assertThat(localDate.getMonthValue()).isEqualTo(xmlGregorianCalendar.getMonth()); + assertThat(localDate.getDayOfMonth()).isEqualTo(xmlGregorianCalendar.getDay()); + } + +} diff --git a/pom.xml b/pom.xml index 58d57ade05..ac1273b28d 100644 --- a/pom.xml +++ b/pom.xml @@ -440,6 +440,7 @@ java-collections-conversions java-collections-maps + java-dates-2 java-lite java-numbers From 227ad26d0bd09869f76c631a02b90e3056987f04 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Sat, 16 Mar 2019 22:16:48 +0000 Subject: [PATCH 238/254] BAEL-2522 - Commenting module --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ac1273b28d..d6a43db409 100644 --- a/pom.xml +++ b/pom.xml @@ -440,7 +440,7 @@ java-collections-conversions java-collections-maps - java-dates-2 + java-lite java-numbers From b7c109246031cad59efce302ac4e0b650ac865c0 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sat, 16 Mar 2019 17:56:54 -0500 Subject: [PATCH 239/254] BAEL-2711: Add spring-boot-angular module to pom.xml (#6492) * BAEL-2246: add link back to article * BAEL-2174: rename core-java-net module to core-java-networking * BAEL-2174: add link back to article * BAEL-2363 BAEL-2337 BAEL-1996 BAEL-2277 add links back to articles * BAEL-2367: add link back to article * BAEL-2335: add link back to article * BAEL-2413: add link back to article * Update README.MD * BAEL-2577: add link back to article * BAEL-2490: add link back to article * BAEL-2471: add link back to article * BAEL-2583: add link back to article * BAEL-2738: add link back to article * BAEL-2711: Add spring-boot-angular module to root pom * BAEL-2544 BAEL-2711 BAEL-2575 BAEL-2657 Add links back to articles --- core-kotlin-2/README.md | 2 ++ java-streams-2/README.md | 3 +++ persistence-modules/spring-boot-persistence/README.MD | 1 + spring-boot-angular/README.md | 3 +++ 4 files changed, 9 insertions(+) create mode 100644 java-streams-2/README.md create mode 100644 spring-boot-angular/README.md diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md index 8d22c4f1a8..da2f7548d9 100644 --- a/core-kotlin-2/README.md +++ b/core-kotlin-2/README.md @@ -2,3 +2,5 @@ - [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type) - [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges) +- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) + diff --git a/java-streams-2/README.md b/java-streams-2/README.md new file mode 100644 index 0000000000..83ef97686f --- /dev/null +++ b/java-streams-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) + diff --git a/persistence-modules/spring-boot-persistence/README.MD b/persistence-modules/spring-boot-persistence/README.MD index f62ca57a19..ee7c2e298e 100644 --- a/persistence-modules/spring-boot-persistence/README.MD +++ b/persistence-modules/spring-boot-persistence/README.MD @@ -7,3 +7,4 @@ - [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot) - [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb) - [Configuring a DataSource Programmatically in Spring Boot](https://www.baeldung.com/spring-boot-configure-data-source-programmatic) +- [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source) diff --git a/spring-boot-angular/README.md b/spring-boot-angular/README.md new file mode 100644 index 0000000000..cfc1ea69f4 --- /dev/null +++ b/spring-boot-angular/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Building a Web Application with Spring Boot and Angular](https://www.baeldung.com/spring-boot-angular-web) + From f62a8d0f70bd1a1b21a3fbb350b78a91db7a5b7a Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 17 Mar 2019 12:26:00 +0200 Subject: [PATCH 240/254] small fixes to match articles --- .../baeldung/SpringBootRestApplication.java | 2 ++ .../com/baeldung/persistence/IOperations.java | 2 +- .../service/common/AbstractService.java | 5 ++-- .../java/com/baeldung/spring/WebConfig.java | 2 +- .../web/controller/FooController.java | 30 ++++++++++++++----- .../web/controller/RootController.java | 16 ++++------ ...sultsRetrievedDiscoverabilityListener.java | 2 +- .../src/main/resources/application.properties | 5 ++-- .../src/test/java/com/baeldung/Consts.java | 2 +- .../baeldung/common/web/AbstractLiveTest.java | 2 +- .../web/FooControllerAppIntegrationTest.java | 2 +- ...ooControllerCustomEtagIntegrationTest.java | 2 +- .../FooControllerWebLayerIntegrationTest.java | 2 +- .../com/baeldung/web/FooPageableLiveTest.java | 2 +- .../foo_API_test.postman_collection.json | 20 +++++-------- 15 files changed, 51 insertions(+), 45 deletions(-) diff --git a/spring-boot-rest/src/main/java/com/baeldung/SpringBootRestApplication.java b/spring-boot-rest/src/main/java/com/baeldung/SpringBootRestApplication.java index 62aae7619d..496f6acdfa 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/SpringBootRestApplication.java +++ b/spring-boot-rest/src/main/java/com/baeldung/SpringBootRestApplication.java @@ -1,11 +1,13 @@ package com.baeldung; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRestApplication { + public static void main(String[] args) { SpringApplication.run(SpringBootRestApplication.class, args); } diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java index 1cc732ab08..fbbba23013 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java @@ -9,7 +9,7 @@ public interface IOperations { // read - one - T findOne(final long id); + T findById(final long id); // read - all diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java index 5900c443b8..f589eaecf5 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java @@ -18,9 +18,8 @@ public abstract class AbstractService implements IOperat @Override @Transactional(readOnly = true) - public T findOne(final long id) { - return getDao().findById(id) - .get(); + public T findById(final long id) { + return getDao().findById(id).orElse(null); } // read - all diff --git a/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java b/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java index 4b876a8338..ab16b61e1d 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java +++ b/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java @@ -55,7 +55,7 @@ public class WebConfig implements WebMvcConfigurer { @Bean public FilterRegistrationBean shallowEtagHeaderFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>( new ShallowEtagHeaderFilter()); - filterRegistrationBean.addUrlPatterns("/auth/foos/*"); + filterRegistrationBean.addUrlPatterns("/foos/*"); filterRegistrationBean.setName("etagFilter"); return filterRegistrationBean; } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java index 255fcaabb7..0162d561b4 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java @@ -5,6 +5,7 @@ import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -20,6 +21,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; import org.springframework.web.util.UriComponentsBuilder; import com.baeldung.persistence.model.Foo; @@ -32,7 +34,7 @@ import com.baeldung.web.util.RestPreconditions; import com.google.common.base.Preconditions; @RestController -@RequestMapping(value = "/auth/foos") +@RequestMapping(value = "/foos") public class FooController { @Autowired @@ -40,6 +42,10 @@ public class FooController { @Autowired private IFooService service; + + + @Value("${version}") + Integer version; public FooController() { super(); @@ -51,28 +57,36 @@ public class FooController { @GetMapping(value = "/{id}/custom-etag") public ResponseEntity findByIdWithCustomEtag(@PathVariable("id") final Long id, final HttpServletResponse response) { - final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + final Foo foo = RestPreconditions.checkFound(service.findById(id)); eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); return ResponseEntity.ok() - .eTag(Long.toString(resourceById.getVersion())) - .body(resourceById); + .eTag(Long.toString(foo.getVersion())) + .body(foo); } // read - one @GetMapping(value = "/{id}") public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { - final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + try { + final Foo resourceById = RestPreconditions.checkFound(service.findById(id)); + + eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); + return resourceById; + } + catch (MyResourceNotFoundException exc) { + throw new ResponseStatusException( + HttpStatus.NOT_FOUND, "Foo Not Found", exc); + } - eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); - return resourceById; } // read - all @GetMapping public List findAll() { + System.out.println(version); return service.findAll(); } @@ -120,7 +134,7 @@ public class FooController { @ResponseStatus(HttpStatus.OK) public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { Preconditions.checkNotNull(resource); - RestPreconditions.checkFound(service.findOne(resource.getId())); + RestPreconditions.checkFound(service.findById(resource.getId())); service.update(resource); } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/RootController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/RootController.java index 436e41e8eb..d618e9f0bf 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/RootController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/RootController.java @@ -7,34 +7,28 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.util.UriTemplate; import com.baeldung.web.util.LinkUtil; @Controller -@RequestMapping(value = "/auth/") public class RootController { - public RootController() { - super(); - } - // API // discover - @RequestMapping(value = "admin", method = RequestMethod.GET) + @GetMapping("/") @ResponseStatus(value = HttpStatus.NO_CONTENT) public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { final String rootUri = request.getRequestURL() .toString(); - final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); - final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); - response.addHeader("Link", linkToFoo); + final URI fooUri = new UriTemplate("{rootUri}{resource}").expand(rootUri, "foos"); + final String linkToFoos = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); + response.addHeader("Link", linkToFoos); } } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java index 31555ef353..afcd364cce 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java @@ -115,7 +115,7 @@ class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationLis protected void plural(final UriComponentsBuilder uriBuilder, final Class clazz) { final String resourceName = clazz.getSimpleName() .toLowerCase() + "s"; - uriBuilder.path("/auth/" + resourceName); + uriBuilder.path("/" + resourceName); } } diff --git a/spring-boot-rest/src/main/resources/application.properties b/spring-boot-rest/src/main/resources/application.properties index a0179f1e4b..6ac3c2ebd2 100644 --- a/spring-boot-rest/src/main/resources/application.properties +++ b/spring-boot-rest/src/main/resources/application.properties @@ -1,6 +1,7 @@ -server.port=8082 server.servlet.context-path=/spring-boot-rest ### Spring Boot default error handling configurations #server.error.whitelabel.enabled=false -#server.error.include-stacktrace=always \ No newline at end of file +#server.error.include-stacktrace=always + +version=1 \ No newline at end of file diff --git a/spring-boot-rest/src/test/java/com/baeldung/Consts.java b/spring-boot-rest/src/test/java/com/baeldung/Consts.java index e33efd589e..4850a1b36a 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/Consts.java +++ b/spring-boot-rest/src/test/java/com/baeldung/Consts.java @@ -1,5 +1,5 @@ package com.baeldung; public interface Consts { - int APPLICATION_PORT = 8082; + int APPLICATION_PORT = 8080; } diff --git a/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractLiveTest.java b/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractLiveTest.java index d26632bc38..18f612d398 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractLiveTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractLiveTest.java @@ -59,7 +59,7 @@ public abstract class AbstractLiveTest { // protected String getURL() { - return "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/auth/foos"; + return "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/foos"; } } diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java index bd5b5eb58e..3300b91fde 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java @@ -27,7 +27,7 @@ public class FooControllerAppIntegrationTest { @Test public void whenFindPaginatedRequest_thenEmptyResponse() throws Exception { - this.mockMvc.perform(get("/auth/foos").param("page", "0") + this.mockMvc.perform(get("/foos").param("page", "0") .param("size", "2")) .andExpect(status().isOk()) .andExpect(content().json("[]")); diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java index dc48c21b30..9e7b60ed8c 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java @@ -29,7 +29,7 @@ public class FooControllerCustomEtagIntegrationTest { @Autowired private MockMvc mvc; - private String FOOS_ENDPOINT = "/auth/foos/"; + private String FOOS_ENDPOINT = "/foos/"; private String CUSTOM_ETAG_ENDPOINT_SUFFIX = "/custom-etag"; private static String serializeFoo(Foo foo) throws Exception { diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java index 7e41cf6393..bd98523b0a 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java @@ -51,7 +51,7 @@ public class FooControllerWebLayerIntegrationTest { doNothing().when(publisher) .publishEvent(any(PaginatedResultsRetrievedEvent.class)); - this.mockMvc.perform(get("/auth/foos").param("page", "0") + this.mockMvc.perform(get("/foos").param("page", "0") .param("size", "2")) .andExpect(status().isOk()) .andExpect(jsonPath("$",Matchers.hasSize(1))); diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooPageableLiveTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooPageableLiveTest.java index 359a62a4d8..6a365f3bd5 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/FooPageableLiveTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooPageableLiveTest.java @@ -74,7 +74,7 @@ public class FooPageableLiveTest extends AbstractBasicLiveTest { } protected String getPageableURL() { - return "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/auth/foos/pageable"; + return "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/foos/pageable"; } } diff --git a/spring-boot-rest/src/test/resources/foo_API_test.postman_collection.json b/spring-boot-rest/src/test/resources/foo_API_test.postman_collection.json index 5a6230bd22..dc4acafab3 100644 --- a/spring-boot-rest/src/test/resources/foo_API_test.postman_collection.json +++ b/spring-boot-rest/src/test/resources/foo_API_test.postman_collection.json @@ -42,15 +42,14 @@ "raw": "{\n \"name\": \"Transformers\"\n}" }, "url": { - "raw": "http://localhost:8082/spring-boot-rest/auth/foos", + "raw": "http://localhost:8080/spring-boot-rest/foos", "protocol": "http", "host": [ "localhost" ], - "port": "8082", + "port": "8080", "path": [ "spring-boot-rest", - "auth", "foos" ] } @@ -85,15 +84,14 @@ "raw": "" }, "url": { - "raw": "http://localhost:8082/spring-boot-rest/auth/foos/{{id}}", + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", "protocol": "http", "host": [ "localhost" ], - "port": "8082", + "port": "8080", "path": [ "spring-boot-rest", - "auth", "foos", "{{id}}" ] @@ -123,15 +121,14 @@ "raw": "" }, "url": { - "raw": "http://localhost:8082/spring-boot-rest/auth/foos/{{id}}", + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", "protocol": "http", "host": [ "localhost" ], - "port": "8082", + "port": "8080", "path": [ "spring-boot-rest", - "auth", "foos", "{{id}}" ] @@ -164,15 +161,14 @@ "raw": "" }, "url": { - "raw": "http://localhost:8082/spring-boot-rest/auth/foos/{{id}}", + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", "protocol": "http", "host": [ "localhost" ], - "port": "8082", + "port": "8080", "path": [ "spring-boot-rest", - "auth", "foos", "{{id}}" ] From af544b87364c8763d1f065a542d13360298cb420 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 17 Mar 2019 12:27:29 +0200 Subject: [PATCH 241/254] remove extra import --- .../src/main/java/com/baeldung/SpringBootRestApplication.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/spring-boot-rest/src/main/java/com/baeldung/SpringBootRestApplication.java b/spring-boot-rest/src/main/java/com/baeldung/SpringBootRestApplication.java index 496f6acdfa..62aae7619d 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/SpringBootRestApplication.java +++ b/spring-boot-rest/src/main/java/com/baeldung/SpringBootRestApplication.java @@ -1,13 +1,11 @@ package com.baeldung; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRestApplication { - public static void main(String[] args) { SpringApplication.run(SpringBootRestApplication.class, args); } From 20002723abe8ad4b1b919031a82d4ba0ba1437e9 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 17 Mar 2019 12:28:28 +0200 Subject: [PATCH 242/254] remove extra import --- .../java/com/baeldung/web/controller/FooController.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java index 0162d561b4..8174480078 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java @@ -5,7 +5,6 @@ import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -42,10 +41,6 @@ public class FooController { @Autowired private IFooService service; - - - @Value("${version}") - Integer version; public FooController() { super(); @@ -86,7 +81,6 @@ public class FooController { @GetMapping public List findAll() { - System.out.println(version); return service.findAll(); } From 7895993ee4bb0f2887945285a0b2351d675b052a Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 17 Mar 2019 12:29:40 +0200 Subject: [PATCH 243/254] remove extra config --- spring-boot-rest/src/main/resources/application.properties | 2 -- 1 file changed, 2 deletions(-) diff --git a/spring-boot-rest/src/main/resources/application.properties b/spring-boot-rest/src/main/resources/application.properties index 6ac3c2ebd2..176deb4f49 100644 --- a/spring-boot-rest/src/main/resources/application.properties +++ b/spring-boot-rest/src/main/resources/application.properties @@ -3,5 +3,3 @@ server.servlet.context-path=/spring-boot-rest ### Spring Boot default error handling configurations #server.error.whitelabel.enabled=false #server.error.include-stacktrace=always - -version=1 \ No newline at end of file From acfe84689c36a7f0054624053a9d2933ffc8084c Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 17 Mar 2019 12:33:21 +0200 Subject: [PATCH 244/254] Update pom.xml --- testing-modules/rest-assured/pom.xml | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 8128cd0b3f..5d3cac4aa3 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -15,20 +15,20 @@ - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - com.google.guava - guava - ${guava.version} - + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + com.google.guava + guava + ${guava.version} + javax.servlet javax.servlet-api From 10e9cbda1ea7dc9e7f91319d0fa0178bee5a2e52 Mon Sep 17 00:00:00 2001 From: juanvaccari Date: Mon, 18 Mar 2019 01:01:40 +0000 Subject: [PATCH 245/254] BAEL-2650 - Kotlin standard functions: run, with, let, also and apply (#6553) --- .../com/baeldung/scope/ScopeFunctions.kt | 25 ++++ .../baeldung/scope/ScopeFunctionsUnitTest.kt | 119 ++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt create mode 100644 core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt new file mode 100644 index 0000000000..37ad8c65e2 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt @@ -0,0 +1,25 @@ +package com.baeldung.scope + +data class Student(var studentId: String = "", var name: String = "", var surname: String = "") { +} + +data class Teacher(var teacherId: Int = 0, var name: String = "", var surname: String = "") { + fun setId(anId: Int): Teacher = apply { teacherId = anId } + fun setName(aName: String): Teacher = apply { name = aName } + fun setSurname(aSurname: String): Teacher = apply { surname = aSurname } +} + +data class Headers(val headerInfo: String) + +data class Response(val headers: Headers) + +data class RestClient(val url: String) { + fun getResponse() = Response(Headers("some header info")) +} + +data class BankAccount(val id: Int) { + fun checkAuthorization(username: String) = Unit + fun addPayee(payee: String) = Unit + fun makePayment(paymentDetails: String) = Unit + +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt new file mode 100644 index 0000000000..ef082655eb --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt @@ -0,0 +1,119 @@ +package com.baeldung.scope + +import org.assertj.core.api.Assertions.assertThat +import org.junit.Test + +class ScopeFunctionsUnitTest { + + class Logger { + + var called : Boolean = false + + fun info(message: String) { + called = true + } + + fun wasCalled() = called + } + + @Test + fun shouldTransformWhenLetFunctionUsed() { + val stringBuider = StringBuilder() + val numberOfCharacters = stringBuider.let { + it.append("This is a transformation function.") + it.append("It takes a StringBuilder instance and returns the number of characters in the generated String") + it.length + } + assertThat(numberOfCharacters).isEqualTo(128) + } + + @Test + fun shouldHandleNullabilityWhenLetFunctionUsed() { + + val message: String? = "hello there!" + val charactersInMessage = message?.let { + "At this point is safe to reference the variable. Let's print the message: $it" + } ?: "default value" + + assertThat(charactersInMessage).isEqualTo("At this point is safe to reference the variable. Let's print the message: hello there!") + + val aNullMessage = null + val thisIsNull = aNullMessage?.let { + "At this point it would be safe to reference the variable. But it will not really happen because it is null. Let's reference: $it" + } ?: "default value" + + assertThat(thisIsNull).isEqualTo("default value") + } + + @Test + fun shouldInitializeObjectWhenUsingApply() { + val aStudent = Student().apply { + studentId = "1234567" + name = "Mary" + surname = "Smith" + } + assertThat(aStudent.name).isEqualTo("Mary") + } + + @Test + fun shouldAllowBuilderStyleObjectDesignWhenApplyUsedInClassMethods() { + val teacher = Teacher() + .setId(1000) + .setName("Martha") + .setSurname("Spector") + + assertThat(teacher.surname).isEqualTo("Spector") + } + + @Test + fun shouldAllowSideEffectWhenUsingAlso() { + val restClient = RestClient("http://www.someurl.com") + + val logger = Logger() + + val headers = restClient + .getResponse() + .also { logger.info(it.toString()) } + .headers + + assertThat(logger.wasCalled()).isTrue() + assertThat(headers.headerInfo).isEqualTo("some header info") + } + + @Test + fun shouldInitializeFieldWhenAlsoUsed() { + val aStudent = Student().also { it.name = "John"} + assertThat(aStudent.name).isEqualTo("John") + } + + @Test + fun shouldLogicallyGroupObjectCallsWhenUsingWith() { + val bankAccount = BankAccount(1000) + with (bankAccount) { + checkAuthorization("someone") + addPayee("some payee") + makePayment("payment information") + } + } + + @Test + fun shouldConvertObjectWhenRunUsed() { + val stringBuider = StringBuilder() + val numberOfCharacters = stringBuider.run { + append("This is a transformation function.") + append("It takes a StringBuilder instance and returns the number of characters in the generated String") + length + } + assertThat(numberOfCharacters).isEqualTo(128) + } + + @Test + fun shouldHandleNullabilityWhenRunIsUsed() { + val message: String? = "hello there!" + val charactersInMessage = message?.run { + "At this point is safe to reference the variable. Let's print the message: $this" + } ?: "default value" + assertThat(charactersInMessage).isEqualTo("At this point is safe to reference the variable. Let's print the message: hello there!") + } + +} \ No newline at end of file From 16fdea72679c2d52f3bb4a9d4e6ecf56a8ad8873 Mon Sep 17 00:00:00 2001 From: pcoates33 Date: Mon, 18 Mar 2019 06:56:13 +0000 Subject: [PATCH 246/254] BAEL-2721 Moved JsonAliasUnitTest into new module called jackson-2. (#6555) * BAEL-2721 Examples of @JsonAlias and Gson's alternate parameter * BAEL-2721 Update class and method names for JsonAlias and GsonAlternate * BAEL-2721 move JsonAliasUnitTest into new jackson-2 module * BAEL-2721 Removed unused dependencies from pom.xml * BAEL-2721 Tidy up logback.xml * BAEL-2721 fix url in README.md --- gson/README.md | 2 + jackson-2/.gitignore | 13 +++++ jackson-2/README.md | 9 ++++ jackson-2/pom.xml | 52 +++++++++++++++++++ .../baeldung/jackson/entities/Weather.java | 0 jackson-2/src/main/resources/logback.xml | 13 +++++ .../jsonalias/JsonAliasUnitTest.java | 0 pom.xml | 2 + 8 files changed, 91 insertions(+) create mode 100644 jackson-2/.gitignore create mode 100644 jackson-2/README.md create mode 100644 jackson-2/pom.xml rename {jackson => jackson-2}/src/main/java/com/baeldung/jackson/entities/Weather.java (100%) create mode 100644 jackson-2/src/main/resources/logback.xml rename {jackson => jackson-2}/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java (100%) diff --git a/gson/README.md b/gson/README.md index 02b06eac20..665ccb552b 100644 --- a/gson/README.md +++ b/gson/README.md @@ -11,3 +11,5 @@ - [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map) - [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives) - [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject) +- [Mapping Multiple JSON Fields to One Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) + diff --git a/jackson-2/.gitignore b/jackson-2/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/jackson-2/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/jackson-2/README.md b/jackson-2/README.md new file mode 100644 index 0000000000..7c14bcfd19 --- /dev/null +++ b/jackson-2/README.md @@ -0,0 +1,9 @@ +========= + +## Jackson Cookbooks and Examples + +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Mapping Multiple JSON Fields to One Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) \ No newline at end of file diff --git a/jackson-2/pom.xml b/jackson-2/pom.xml new file mode 100644 index 0000000000..ddbcb81dcc --- /dev/null +++ b/jackson-2/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + jackson-2 + 0.1-SNAPSHOT + jackson-2 + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + jackson-2 + + + src/main/resources + true + + + + + + + + 3.11.0 + + + diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/Weather.java b/jackson-2/src/main/java/com/baeldung/jackson/entities/Weather.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/entities/Weather.java rename to jackson-2/src/main/java/com/baeldung/jackson/entities/Weather.java diff --git a/jackson-2/src/main/resources/logback.xml b/jackson-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jackson-2/src/main/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/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java rename to jackson-2/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java diff --git a/pom.xml b/pom.xml index 5858df01e1..d29824b085 100644 --- a/pom.xml +++ b/pom.xml @@ -436,6 +436,7 @@ immutables jackson + jackson-2 java-collections-conversions java-collections-maps @@ -1078,6 +1079,7 @@ immutables jackson + jackson-2 java-collections-conversions java-collections-maps From 8005f6b3131d62d222bf2b33ba3d19aac7c6e01e Mon Sep 17 00:00:00 2001 From: Urvy Agrawal Date: Mon, 18 Mar 2019 20:54:17 +0530 Subject: [PATCH 247/254] BAEL-2590 Added files for jlink tutorial (#6552) --- .../jlinkModule/com/baeldung/jlink/HelloWorld.java | 12 ++++++++++++ .../src/modules/jlinkModule/module-info.java | 3 +++ 2 files changed, 15 insertions(+) create mode 100644 core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java create mode 100644 core-java-11/src/modules/jlinkModule/module-info.java diff --git a/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java b/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java new file mode 100644 index 0000000000..47fe62ba40 --- /dev/null +++ b/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java @@ -0,0 +1,12 @@ +package com.baeldung.jlink; + +import java.util.logging.Logger; + +public class HelloWorld { + + private static final Logger LOG = Logger.getLogger(HelloWorld.class.getName()); + + public static void main(String[] args) { + LOG.info("Hello World!"); + } +} diff --git a/core-java-11/src/modules/jlinkModule/module-info.java b/core-java-11/src/modules/jlinkModule/module-info.java new file mode 100644 index 0000000000..0587c65b53 --- /dev/null +++ b/core-java-11/src/modules/jlinkModule/module-info.java @@ -0,0 +1,3 @@ +module jlinkModule { + requires java.logging; +} \ No newline at end of file From 384dad60f19e5b4781d5ac64ac18db1a8a3c9801 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Mon, 18 Mar 2019 20:19:37 +0000 Subject: [PATCH 248/254] BAEL-2522 Kevin comments addressed --- .../XmlGregorianCalendarConverterUnitTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java b/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java index 34510a3167..b221c04199 100644 --- a/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java +++ b/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java @@ -3,6 +3,7 @@ package com.baeldung.xmlgregoriancalendar; import org.junit.Test; import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.time.LocalDate; @@ -19,6 +20,7 @@ public class XmlGregorianCalendarConverterUnitTest { assertThat(xmlGregorianCalendar.getYear()).isEqualTo(localDate.getYear()); assertThat(xmlGregorianCalendar.getMonth()).isEqualTo(localDate.getMonthValue()); assertThat(xmlGregorianCalendar.getDay()).isEqualTo(localDate.getDayOfMonth()); + assertThat(xmlGregorianCalendar.getTimezone()).isEqualTo(DatatypeConstants.FIELD_UNDEFINED); } @Test From 92b03457a154b749521e7f8a455924ae9b35bad8 Mon Sep 17 00:00:00 2001 From: juanvaccari Date: Mon, 18 Mar 2019 23:59:04 +0000 Subject: [PATCH 249/254] BAEL-2650 - Change scope functions tests to use assertTrue (#6558) * BAEL-2650 - Kotlin standard functions: run, with, let, also and apply * BAEL-2650 - Change scope functions tests to use assertTrue --- .../baeldung/scope/ScopeFunctionsUnitTest.kt | 46 ++++++++++++++----- 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt index ef082655eb..cb3ed98006 100644 --- a/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt @@ -1,7 +1,8 @@ package com.baeldung.scope -import org.assertj.core.api.Assertions.assertThat import org.junit.Test +import kotlin.test.assertTrue + class ScopeFunctionsUnitTest { @@ -24,7 +25,10 @@ class ScopeFunctionsUnitTest { it.append("It takes a StringBuilder instance and returns the number of characters in the generated String") it.length } - assertThat(numberOfCharacters).isEqualTo(128) + + assertTrue { + numberOfCharacters == 128 + } } @Test @@ -35,14 +39,18 @@ class ScopeFunctionsUnitTest { "At this point is safe to reference the variable. Let's print the message: $it" } ?: "default value" - assertThat(charactersInMessage).isEqualTo("At this point is safe to reference the variable. Let's print the message: hello there!") + assertTrue { + charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!") + } val aNullMessage = null val thisIsNull = aNullMessage?.let { "At this point it would be safe to reference the variable. But it will not really happen because it is null. Let's reference: $it" } ?: "default value" - assertThat(thisIsNull).isEqualTo("default value") + assertTrue { + thisIsNull.equals("default value") + } } @Test @@ -52,7 +60,10 @@ class ScopeFunctionsUnitTest { name = "Mary" surname = "Smith" } - assertThat(aStudent.name).isEqualTo("Mary") + + assertTrue { + aStudent.name.equals("Mary") + } } @Test @@ -62,7 +73,9 @@ class ScopeFunctionsUnitTest { .setName("Martha") .setSurname("Spector") - assertThat(teacher.surname).isEqualTo("Spector") + assertTrue { + teacher.surname.equals("Spector") + } } @Test @@ -76,14 +89,19 @@ class ScopeFunctionsUnitTest { .also { logger.info(it.toString()) } .headers - assertThat(logger.wasCalled()).isTrue() - assertThat(headers.headerInfo).isEqualTo("some header info") + assertTrue { + logger.wasCalled() && headers.headerInfo.equals("some header info") + } + } @Test fun shouldInitializeFieldWhenAlsoUsed() { val aStudent = Student().also { it.name = "John"} - assertThat(aStudent.name).isEqualTo("John") + + assertTrue { + aStudent.name.equals("John") + } } @Test @@ -104,7 +122,10 @@ class ScopeFunctionsUnitTest { append("It takes a StringBuilder instance and returns the number of characters in the generated String") length } - assertThat(numberOfCharacters).isEqualTo(128) + + assertTrue { + numberOfCharacters == 128 + } } @Test @@ -113,7 +134,10 @@ class ScopeFunctionsUnitTest { val charactersInMessage = message?.run { "At this point is safe to reference the variable. Let's print the message: $this" } ?: "default value" - assertThat(charactersInMessage).isEqualTo("At this point is safe to reference the variable. Let's print the message: hello there!") + + assertTrue { + charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!") + } } } \ No newline at end of file From aaddee0a7e81ff268746f67afd964152c2be1393 Mon Sep 17 00:00:00 2001 From: rahusriv Date: Tue, 19 Mar 2019 11:00:14 +0530 Subject: [PATCH 250/254] Rahul/socket/read/pr2 (#6398) * Making examples simple * Changing variable names * Modificatons in naming * Read all data from server * Adding seperate TestSocketRead class having live test * Adding test case * Changing test name to live tests --- .../java/com/baeldung/socket/read/Client.java | 37 ++++++++++++++ .../java/com/baeldung/socket/read/Server.java | 51 +++++++++++++++++++ .../read/SocketReadAllDataLiveTest.java | 37 ++++++++++++++ 3 files changed, 125 insertions(+) create mode 100644 core-java-networking/src/main/java/com/baeldung/socket/read/Client.java create mode 100644 core-java-networking/src/main/java/com/baeldung/socket/read/Server.java create mode 100644 core-java-networking/src/test/java/com/baeldung/socket/read/SocketReadAllDataLiveTest.java diff --git a/core-java-networking/src/main/java/com/baeldung/socket/read/Client.java b/core-java-networking/src/main/java/com/baeldung/socket/read/Client.java new file mode 100644 index 0000000000..08292237f2 --- /dev/null +++ b/core-java-networking/src/main/java/com/baeldung/socket/read/Client.java @@ -0,0 +1,37 @@ +package com.baeldung.socket.read; + +import java.net.*; +import java.io.*; + +public class Client { + + //Initialize socket, input and output stream + private Socket socket = null; + private DataInputStream in = null; + private DataOutputStream out = null; + + public void runClient(String ip, int port) { + try { + socket = new Socket(ip, port); + System.out.println("Connected to server ..."); + in = new DataInputStream(System.in); + out = new DataOutputStream(socket.getOutputStream()); + } catch(Exception e) { + e.printStackTrace(); + } + char type = 's'; // s for string + int length = 29; + String data = "This is a string of length 29"; + byte[] dataInBytes = data.getBytes(); + //Sending data in TLV format + try { + out.writeChar(type); + out.writeInt(length); + out.write(dataInBytes); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/core-java-networking/src/main/java/com/baeldung/socket/read/Server.java b/core-java-networking/src/main/java/com/baeldung/socket/read/Server.java new file mode 100644 index 0000000000..bdb3a4449f --- /dev/null +++ b/core-java-networking/src/main/java/com/baeldung/socket/read/Server.java @@ -0,0 +1,51 @@ +package com.baeldung.socket.read; + +import java.net.*; +import java.io.*; + +public class Server { + + //Socket and input stream + private Socket socket = null; + private ServerSocket server = null; + private DataInputStream in = null; + + public void runServer(int port) { + //Start the server and wait for connection + try { + server = new ServerSocket(port); + System.out.println("Server Started. Waiting for connection ..."); + socket = server.accept(); + System.out.println("Got connection from client."); + //Get input stream from socket variable and convert the same to DataInputStream + in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); + //Read type and length of data + char dataType = in.readChar(); + int length = in.readInt(); + System.out.println("Type : "+dataType); + System.out.println("Lenght :"+length); + //Read String data in bytes + byte[] messageByte = new byte[length]; + boolean end = false; + String dataString = ""; + int totalBytesRead = 0; + //We need to run while loop, to read all data in that stream + while(!end) { + int currentBytesRead = in.read(messageByte); + totalBytesRead = currentBytesRead + totalBytesRead; + if(totalBytesRead <= length) { + dataString += new String(messageByte,0,currentBytesRead); + } else { + dataString += new String(messageByte,0,length - totalBytesRead + currentBytesRead); + } + if(dataString.length()>=length) { + end = true; + } + } + System.out.println("Read "+length+" bytes of message from client. Message = "+dataString);; + } catch (Exception e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/core-java-networking/src/test/java/com/baeldung/socket/read/SocketReadAllDataLiveTest.java b/core-java-networking/src/test/java/com/baeldung/socket/read/SocketReadAllDataLiveTest.java new file mode 100644 index 0000000000..da7f5b8d3f --- /dev/null +++ b/core-java-networking/src/test/java/com/baeldung/socket/read/SocketReadAllDataLiveTest.java @@ -0,0 +1,37 @@ +package com.baeldung.socket.read; + +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +public class SocketReadAllDataLiveTest { + + @Test + public void givenServerAndClient_whenClientSendsAndServerReceivesData_thenCorrect() { + //Run server in new thread + Runnable runnable1 = () -> { runServer(); }; + Thread thread1 = new Thread(runnable1); + thread1.start(); + //Wait for 10 seconds + try { + TimeUnit.SECONDS.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //Run client in a new thread + Runnable runnable2 = () -> { runClient(); }; + Thread thread2 = new Thread(runnable2); + thread2.start(); + } + + public static void runServer() { + //Run Server + Server server = new Server(); + server.runServer(5555); + } + + public static void runClient() { + //Run Client + Client client = new Client(); + client.runClient("127.0.0.1", 5555); + } +} \ No newline at end of file From 39a0eda4379b7779ecd170ea61b48d3f49094ea6 Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Tue, 19 Mar 2019 15:45:25 +0100 Subject: [PATCH 251/254] Remove ValidationUnitTest.kt (#6562) --- .../baeldung/annotations/ValidationTest.kt | 2 +- .../annotations/ValidationUnitTest.kt | 42 ------------------- 2 files changed, 1 insertion(+), 43 deletions(-) delete mode 100644 core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationUnitTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt index 97fb3434ee..5c2b6ef47f 100644 --- a/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt @@ -4,7 +4,7 @@ import org.junit.Test import kotlin.test.assertTrue import kotlin.test.assertFalse -class ValidationUnitTest { +class ValidationTest { @Test fun whenAmountIsOneAndNameIsAlice_thenTrue() { diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationUnitTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationUnitTest.kt deleted file mode 100644 index 506b7a24b5..0000000000 --- a/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationUnitTest.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.annotations - -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Test - - -class ValidationUnitTest { - - @Test - fun whenAmountIsOneAndNameIsAlice_thenTrue() { - assertTrue(Validator().isValid(Item(1f, "Alice"))) - } - - @Test - fun whenAmountIsOneAndNameIsBob_thenTrue() { - assertTrue(Validator().isValid(Item(1f, "Bob"))) - } - - - @Test - fun whenAmountIsMinusOneAndNameIsAlice_thenFalse() { - assertFalse(Validator().isValid(Item(-1f, "Alice"))) - } - - @Test - fun whenAmountIsMinusOneAndNameIsBob_thenFalse() { - assertFalse(Validator().isValid(Item(-1f, "Bob"))) - } - - @Test - fun whenAmountIsOneAndNameIsTom_thenFalse() { - assertFalse(Validator().isValid(Item(1f, "Tom"))) - } - - @Test - fun whenAmountIsMinusOneAndNameIsTom_thenFalse() { - assertFalse(Validator().isValid(Item(-1f, "Tom"))) - } - - -} \ No newline at end of file From 88ca90327cad42fa560d283707c99cc278f9dc48 Mon Sep 17 00:00:00 2001 From: enpy Date: Wed, 20 Mar 2019 03:59:02 +0100 Subject: [PATCH 252/254] BAEL 2730 (#6524) * BAEL 2730 * jackson-dataformat-xml uncommented --- .../web/controller/students/Student.java | 53 +++++++++++++ .../students/StudentController.java | 73 ++++++++++++++++++ .../controller/students/StudentService.java | 51 +++++++++++++ .../web/StudentControllerIntegrationTest.java | 76 +++++++++++++++++++ 4 files changed, 253 insertions(+) create mode 100644 spring-boot-rest/src/main/java/com/baeldung/web/controller/students/Student.java create mode 100644 spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentController.java create mode 100644 spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentService.java create mode 100644 spring-boot-rest/src/test/java/com/baeldung/web/StudentControllerIntegrationTest.java diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/Student.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/Student.java new file mode 100644 index 0000000000..3b6a5c0298 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/Student.java @@ -0,0 +1,53 @@ +package com.baeldung.web.controller.students; + +public class Student { + + private long id; + private String firstName; + private String lastName; + + public Student() {} + + public Student(String firstName, String lastName) { + super(); + this.firstName = firstName; + this.lastName = lastName; + } + + public Student(long id, String firstName, String lastName) { + super(); + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public long getId() { + return id; + } + + public void setId(long 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; + } + + @Override + public String toString() { + return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; + } + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentController.java new file mode 100644 index 0000000000..f937e0c757 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentController.java @@ -0,0 +1,73 @@ +package com.baeldung.web.controller.students; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import com.baeldung.web.controller.students.StudentService; + +@RestController +@RequestMapping("/students") +public class StudentController { + + @Autowired + private StudentService service; + + @GetMapping("/") + public List read() { + return service.readAll(); + } + + @GetMapping("/{id}") + public ResponseEntity read(@PathVariable("id") Long id) { + Student foundStudent = service.read(id); + if (foundStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(foundStudent); + } + } + + @PostMapping("/") + public ResponseEntity create(@RequestBody Student student) throws URISyntaxException { + Student createdStudent = service.create(student); + + URI uri = ServletUriComponentsBuilder.fromCurrentRequest() + .path("/{id}") + .buildAndExpand(createdStudent.getId()) + .toUri(); + + return ResponseEntity.created(uri) + .body(createdStudent); + + } + + @PutMapping("/{id}") + public ResponseEntity update(@RequestBody Student student, @PathVariable Long id) { + Student updatedStudent = service.update(id, student); + if (updatedStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(updatedStudent); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteStudent(@PathVariable Long id) { + service.delete(id); + + return ResponseEntity.noContent().build(); + } + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentService.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentService.java new file mode 100644 index 0000000000..d923f4f14f --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentService.java @@ -0,0 +1,51 @@ +package com.baeldung.web.controller.students; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; + +@Service +public class StudentService { + + // DB repository mock + private Map repository = Arrays.asList( + new Student[]{ + new Student(1, "Alan","Turing"), + new Student(2, "Sebastian","Bach"), + new Student(3, "Pablo","Picasso"), + }).stream() + .collect(Collectors.toConcurrentMap(s -> s.getId(), Function.identity())); + + // DB id sequence mock + private AtomicLong sequence = new AtomicLong(3); + + public List readAll() { + return repository.values().stream().collect(Collectors.toList()); + } + + public Student read(Long id) { + return repository.get(id); + } + + public Student create(Student student) { + long key = sequence.incrementAndGet(); + student.setId(key); + repository.put(key, student); + return student; + } + + public Student update(Long id, Student student) { + student.setId(id); + Student oldStudent = repository.replace(id, student); + return oldStudent == null ? null : student; + } + + public void delete(Long id) { + repository.remove(id); + } +} diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/StudentControllerIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/StudentControllerIntegrationTest.java new file mode 100644 index 0000000000..54ac69ebeb --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/web/StudentControllerIntegrationTest.java @@ -0,0 +1,76 @@ +package com.baeldung.web; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.server.MediaTypeNotSupportedStatusException; + +import com.baeldung.web.controller.students.Student; +import com.fasterxml.jackson.databind.ObjectMapper; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class StudentControllerIntegrationTest { + + private static final String STUDENTS_PATH = "/students/"; + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenReadAll_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH)) + .andExpect(status().isOk()); + } + + @Test + public void whenReadOne_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH + 1)) + .andExpect(status().isOk()); + } + + @Test + public void whenCreate_thenStatusIsCreated() throws Exception { + Student student = new Student(10, "Albert", "Einstein"); + this.mockMvc.perform(post(STUDENTS_PATH).content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isCreated()); + } + + @Test + public void whenUpdate_thenStatusIsOk() throws Exception { + Student student = new Student(1, "Nikola", "Tesla"); + this.mockMvc.perform(put(STUDENTS_PATH + 1) + .content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()); + } + + @Test + public void whenDelete_thenStatusIsNoContent() throws Exception { + this.mockMvc.perform(delete(STUDENTS_PATH + 3)) + .andExpect(status().isNoContent()); + } + + private String asJsonString(final Object obj) { + try { + return new ObjectMapper().writeValueAsString(obj); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} From 1f857d5ad515859185292779fe37436e3e07fb31 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Wed, 20 Mar 2019 16:00:42 +0000 Subject: [PATCH 253/254] BAEL-2522 - Tabs problem. Identation. --- java-dates-2/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-dates-2/pom.xml b/java-dates-2/pom.xml index 93216e3ffa..c2464ed47f 100644 --- a/java-dates-2/pom.xml +++ b/java-dates-2/pom.xml @@ -49,7 +49,7 @@ 3.6.1 - 1.9 + 1.9 1.9 From 66f20f14419d1201ce39e4c86a0eca502d5f110b Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Wed, 20 Mar 2019 17:05:30 +0100 Subject: [PATCH 254/254] added example code for BAEL-2083 (#6486) * added example code for BAEL-2083 * updated example code for BAEL-2083 --- persistence-modules/hibernate5/pom.xml | 7 ++- .../com/baeldung/hibernate/HibernateUtil.java | 1 + .../com/baeldung/hibernate/pojo/Post.java | 59 +++++++++++++++++++ .../hibernate/transaction/PostService.java | 29 +++++++++ .../hibernate/CustomClassIntegrationTest.java | 2 + .../TransactionIntegrationTest.java | 57 ++++++++++++++++++ 6 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java create mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java create mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index a09669c8b5..c7f08e50d5 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -83,13 +83,18 @@ jmh-generator-annprocess ${openjdk-jmh.version} + + javax.xml.bind + jaxb-api + 2.3.0 + hibernate5 - src/main/resources + src/test/resources true diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index ea0af97d5a..48c9b9d5c2 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -113,6 +113,7 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); metadataSources.addAnnotatedClass(OfficeEmployee.class); + metadataSources.addAnnotatedClass(Post.class); Metadata metadata = metadataSources.getMetadataBuilder() .applyBasicType(LocalDateStringType.INSTANCE) diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java new file mode 100644 index 0000000000..25e51e35d0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "posts") +public class Post { + + @Id + @GeneratedValue + private int id; + + private String title; + + private String body; + + public Post() { } + + public Post(String title, String body) { + this.title = title; + this.body = body; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + @Override + public String toString() { + return "Post{" + + "id=" + id + + ", title='" + title + '\'' + + ", body='" + body + '\'' + + '}'; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java new file mode 100644 index 0000000000..5a4eb20079 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.transaction; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.query.Query; + +public class PostService { + + + private Session session; + + public PostService(Session session) { + this.session = session; + } + + + public void updatePost(String title, String body, int id) { + Transaction txn = session.beginTransaction(); + Query updateQuery = session.createQuery("UPDATE Post p SET p.title = ?1, p.body = ?2 WHERE p.id = ?3"); + updateQuery.setParameter(1, title); + updateQuery.setParameter(2, body); + updateQuery.setParameter(3, id); + updateQuery.executeUpdate(); + txn.commit(); + } + + + +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java index 29ae55b773..e64e836924 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java @@ -74,4 +74,6 @@ public class CustomClassIntegrationTest { assertEquals("John Smith", result.getEmployeeName()); assertEquals("Sales", result.getDepartmentName()); } + + } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java new file mode 100644 index 0000000000..246a7d59f9 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.transaction; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Post; +import com.baeldung.hibernate.transaction.PostService; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; + +public class TransactionIntegrationTest { + + private static PostService postService; + private static Session session; + private static Logger logger = LoggerFactory.getLogger(TransactionIntegrationTest.class); + + @BeforeClass + public static void init() throws IOException { + Properties properties = new Properties(); + properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); + properties.setProperty("hibernate.connection.url", "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); + properties.setProperty("hibernate.connection.username", "sa"); + properties.setProperty("hibernate.show_sql", "true"); + properties.setProperty("jdbc.password", ""); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); + SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties); + session = sessionFactory.openSession(); + postService = new PostService(session); + } + + @Test + public void givenTitleAndBody_whenRepositoryUpdatePost_thenUpdatePost() { + + Post post = new Post("This is a title", "This is a sample post"); + session.persist(post); + + String title = "[UPDATE] Java HowTos"; + String body = "This is an updated posts on Java how-tos"; + postService.updatePost(title, body, post.getId()); + + session.refresh(post); + + assertEquals(post.getTitle(), title); + assertEquals(post.getBody(), body); + } + + +}