From 445fee41b3925c4bd8272068e432263ec06d378c Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Sun, 30 Dec 2018 23:38:13 +0100 Subject: [PATCH 01/54] 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 fc88c99537ce2f4bb3b08b9e3da1da82e5bc9ee6 Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Fri, 15 Feb 2019 22:53:52 +0100 Subject: [PATCH 02/54] 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 c636b0d4b73ba3954c973766ec8d1dc63357733f Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Thu, 21 Feb 2019 23:56:32 +0100 Subject: [PATCH 03/54] 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 04/54] 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 4376424e512d9296cc2914049f3dcf8d00d55231 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Wed, 6 Mar 2019 07:14:23 +0000 Subject: [PATCH 05/54] 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 9fae5f5a50f3cca4738b8ef0fd1346c8dc2be781 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Sun, 10 Mar 2019 17:40:04 +0000 Subject: [PATCH 06/54] 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 1131705393d1cc04cb1c8166b7fdbd19f29128f7 Mon Sep 17 00:00:00 2001 From: Dhananjay Singh Date: Mon, 11 Mar 2019 00:30:33 +0100 Subject: [PATCH 07/54] 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 08/54] 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 b7cc946a3297e188de0fb0e77d8bc3ba33cf57da Mon Sep 17 00:00:00 2001 From: isaolmez Date: Tue, 12 Mar 2019 22:35:27 +0300 Subject: [PATCH 09/54] BAEL-2715: Added code samples for Netty server configuration --- pom.xml | 1 + spring-5-reactive-netty/.gitignore | 11 ++++ spring-5-reactive-netty/README.md | 3 ++ spring-5-reactive-netty/pom.xml | 51 ++++++++++++++++++ .../serverconfig/ServerConfigApplication.java | 16 ++++++ .../client/GreetingWebClient.java | 37 +++++++++++++ .../server/GreetingController.java | 23 ++++++++ .../serverconfig/server/GreetingService.java | 12 +++++ .../NettyWebServerFactoryPortCustomizer.java | 31 +++++++++++ .../NettyWebServerFactorySslCustomizer.java | 23 ++++++++ .../src/main/resources/logback.xml | 31 +++++++++++ .../src/main/resources/sample.jks | Bin 0 -> 2264 bytes .../GreetingControllerIntegrationTest.java | 41 ++++++++++++++ .../src/test/resources/logback-test.xml | 13 +++++ 14 files changed, 293 insertions(+) create mode 100644 spring-5-reactive-netty/.gitignore create mode 100644 spring-5-reactive-netty/README.md create mode 100644 spring-5-reactive-netty/pom.xml create mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/ServerConfigApplication.java create mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java create mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingController.java create mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingService.java create mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java create mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java create mode 100644 spring-5-reactive-netty/src/main/resources/logback.xml create mode 100644 spring-5-reactive-netty/src/main/resources/sample.jks create mode 100644 spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java create mode 100644 spring-5-reactive-netty/src/test/resources/logback-test.xml diff --git a/pom.xml b/pom.xml index 18e3ace31b..2c173346ee 100644 --- a/pom.xml +++ b/pom.xml @@ -575,6 +575,7 @@ spring-5-reactive-client spring-5-reactive-oauth spring-5-reactive-security + spring-5-reactive-netty spring-5-security spring-5-security-oauth diff --git a/spring-5-reactive-netty/.gitignore b/spring-5-reactive-netty/.gitignore new file mode 100644 index 0000000000..70ed41e73a --- /dev/null +++ b/spring-5-reactive-netty/.gitignore @@ -0,0 +1,11 @@ +# Folders # +**/.idea +**/target + +# Files # +*.log + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-5-reactive-netty/README.md b/spring-5-reactive-netty/README.md new file mode 100644 index 0000000000..09f7cc0e24 --- /dev/null +++ b/spring-5-reactive-netty/README.md @@ -0,0 +1,3 @@ +## Spring 5 Reactive Project With Netty Server + +Includes configuration options for Netty server. diff --git a/spring-5-reactive-netty/pom.xml b/spring-5-reactive-netty/pom.xml new file mode 100644 index 0000000000..48fc0b201f --- /dev/null +++ b/spring-5-reactive-netty/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + com.baeldung + spring-5-reactive-netty + 0.0.1-SNAPSHOT + spring-5-reactive-netty + jar + Spring 5 sample project about reactive web with Netty server + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.projectlombok + lombok + + + + org.springframework.boot + spring-boot-devtools + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/ServerConfigApplication.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/ServerConfigApplication.java new file mode 100644 index 0000000000..c4ff9c3930 --- /dev/null +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/ServerConfigApplication.java @@ -0,0 +1,16 @@ +package com.baeldung.serverconfig; + +import com.baeldung.serverconfig.client.GreetingWebClient; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerConfigApplication { + + public static void main(String[] args) { + SpringApplication.run(ServerConfigApplication.class, args); + + GreetingWebClient webClient = new GreetingWebClient(); + webClient.getResult(); + } +} diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java new file mode 100644 index 0000000000..d9bea649c1 --- /dev/null +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java @@ -0,0 +1,37 @@ +package com.baeldung.serverconfig.client; + +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import lombok.SneakyThrows; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; +import reactor.netty.http.client.HttpClient; + +public class GreetingWebClient { + + private WebClient client = getWebClient(); + + public void getResult() { + System.out.println("Mono"); + Mono greetingMono = client.get() + .uri("/greet/{name}", "baeldung") + .retrieve() + .bodyToMono(String.class); + + greetingMono.subscribe(System.out::println); + } + + @SneakyThrows + private WebClient getWebClient() { + SslContext sslContext = SslContextBuilder + .forClient() + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .build(); + HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext)); + return WebClient.builder() + .baseUrl("https://localhost:8443") + .clientConnector(new ReactorClientHttpConnector(httpClient)).build(); + } +} \ No newline at end of file diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingController.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingController.java new file mode 100644 index 0000000000..275439a66f --- /dev/null +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingController.java @@ -0,0 +1,23 @@ +package com.baeldung.serverconfig.server; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/greet") +public class GreetingController { + + private final GreetingService greetingService; + + public GreetingController(GreetingService greetingService) { + this.greetingService = greetingService; + } + + @GetMapping("/{name}") + private Mono greet(@PathVariable String name) { + return greetingService.greet(name); + } +} diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingService.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingService.java new file mode 100644 index 0000000000..5b2b246531 --- /dev/null +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingService.java @@ -0,0 +1,12 @@ +package com.baeldung.serverconfig.server; + +import org.springframework.stereotype.Service; +import reactor.core.publisher.Mono; + +@Service +public class GreetingService { + + public Mono greet(String name) { + return Mono.just("Greeting " + name); + } +} diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java new file mode 100644 index 0000000000..be7e442afe --- /dev/null +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java @@ -0,0 +1,31 @@ +package com.baeldung.serverconfig.server; + +import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.stereotype.Component; +import reactor.netty.http.server.HttpServer; + +@Component +public class NettyWebServerFactoryPortCustomizer implements WebServerFactoryCustomizer { + + @Override + public void customize(NettyReactiveWebServerFactory serverFactory) { + serverFactory.addServerCustomizers(new PortCustomizer(8443)); + } + + private static class PortCustomizer implements NettyServerCustomizer { + + private final int port; + + private PortCustomizer(int port) { + this.port = port; + } + + @Override + public HttpServer apply(HttpServer httpServer) { + return httpServer.port(port); + } + } +} + diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java new file mode 100644 index 0000000000..f84e8d143a --- /dev/null +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java @@ -0,0 +1,23 @@ +package com.baeldung.serverconfig.server; + +import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.server.Ssl; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.stereotype.Component; + +@Component +public class NettyWebServerFactorySslCustomizer implements WebServerFactoryCustomizer { + + @Override + public void customize(NettyReactiveWebServerFactory serverFactory) { + Ssl ssl = new Ssl(); + ssl.setEnabled(true); + ssl.setKeyStore("classpath:sample.jks"); + ssl.setKeyAlias("alias"); + ssl.setKeyPassword("password"); + ssl.setKeyStorePassword("secret"); + serverFactory.setSsl(ssl); + serverFactory.setPort(8443); + } +} + diff --git a/spring-5-reactive-netty/src/main/resources/logback.xml b/spring-5-reactive-netty/src/main/resources/logback.xml new file mode 100644 index 0000000000..fc026694b1 --- /dev/null +++ b/spring-5-reactive-netty/src/main/resources/logback.xml @@ -0,0 +1,31 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + netty-access.log + + %msg%n + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-5-reactive-netty/src/main/resources/sample.jks b/spring-5-reactive-netty/src/main/resources/sample.jks new file mode 100644 index 0000000000000000000000000000000000000000..6aa9a28053a591e41453e665e5024e8a8cb78b3d GIT binary patch literal 2264 zcmchYX*3iJ7sqE|hQS!q5Mv)4GM2$i#uAFqC`%7x7baWA*i&dRX>3`uq(XS?3XSYp z%38`&ib7E$8j~$cF^}gt?|I+noW8#w?uYxk=iGD8|K9Vzd#pVc0002(2k@T|2@MMI zqxqr2AhQO*TVi`j@((S;e;g;l$#dAA{>vf0kX$R(Qn4oKgGEYjZ5zti2dw?Z6A zh%LuFCNI?9o+Z1duJL-++e#cjO`zlK?u9s030=k_*wD1#-$FbIDRDnA^vo@fm( zzjt(3VJrGOr0iHXSTM|rYN#>RZ@Dp`PwB2zrDQffLvuoR2~V3ReYa0&vU^dXd8isV zsAf*@!8s%xBvHLseXn6f?1kefe(8uAmAbaF$x{Ykzb6c6jdUwY1$y4tFzsj7 zIghr!T#ODfu@Po!a29@kXQ8kY#(LE<0o7?7PQ|eMeY@Equ?R-6*f@Na3o&stDQ=6( zQzDSQhCnS(9Bu9W_~giknP0vECqUsr4_9y_}nEU`cy z4}dApnAip92wMwgzciAFpc3i}+-#Zlq+iF7d1y}d4Qsp8=%l1N8NIs161I`HmkcpQ zY4*CUCFJJf(2!M{`&qQ}3($KeTQ=)mMrBs`DOb;%Of0tC)9he_p~w&CO#DfCgx(%s z{@|D(brX_Gb}ZDLmGej*JgEl0Et>q~kgTXuJg-PwvRjNx8sBbIShxD=xOySzw{;^X zAvrh5HTg>Xq@<{#^!Kg}B?qz@b<{ebD)yaSf&RChBIJQo-?Ahzw@qopSe^e&>^IuU zydM4Y1_C&>k7u|}=; z63R7$H6zat=hNExxEwXu1fQ*ytuEkP!{w{|#6TIEq1#*ck=6_NM*ILF65tmD-O5&R zMI!-MT<3U~t@}(CN4@RlZ~1I>C=!ywF)dNI{VvH;5Y3(Z4jY^%_c&fsm4Q`<1g|qX z&!h29jXjVE3nJnet*L)XL?-8<>qDbVGP%i^NwOZfwWO7?Mr!X7 zl}sG@9S_5}}td}$xrWIYY=e(VVBiv%A+M-{M z!3_^Tc=pV?niT!{D`!{e@W;MvrZ(OER{x7itVAtwE~spPtPtma|J=5dv&_oE!5H#` zdgXJ;+gJ4hI}*9QX9jpL`Gb)yCe%1}t!&O-^sihyZys%%5uF~WhsR_w(q7;vV5d4P zr%ZUA2}kO+L^2ePTgGT9Ua71w<+)poSyjTdLq&xbUn`<6&SpwFp(HRHUyU6J3WZ_! zfztko79+94Tq%mTYj53(RYcL&1~5`I#+w3`(Q|r+P(aT z%?r(^?IWw~19CB&uvXf(f7&BnEE{zwK4piVU`I4j1j?v5d4N<7VUJ8nM`$7S*mfKR z#9-JzPRZ?{M!@L+0N^V)IyeeP2T|^UK|m0QD+Ibs!wEoml^N!YO#vW~j~jraX(0A3 z6Kux?IRLez`O^X;{!4g%BhcRn>^H*qKZ3*|{_YGuz)KCJcu;)DSES5D2tDE`C02YR0R%Vy1T7k|RQ;3g<0icA$AuP0pOvc~jGl zz+NeKv_FT_;GWK&8XlDUv&hv9kxg?@c!bu?83i=YQ$S!K09Y)Glg3Hz?@|)ZCBlVz zP8i}#XZkMoje3I=h&I!!s_m?Qi@1MR`yv7X*yEs47qOs^t^?&=;*IQ!q&)gq_Sx5* z?fhU8Q*PSe*w7y)FH#P!9R^Xw!lTT+zI39L<&8cViaj$A(Z2Cg7!{V?uuyi#vlNCg z40i}2ivw&y&1-&Nh&WMG`&aIt>)(#tKTJ}^@696Kw1-{IzSOTnFF+0@k$o3%ZHS;Q#;t literal 0 HcmV?d00001 diff --git a/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java new file mode 100644 index 0000000000..8bd4e41f1f --- /dev/null +++ b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.serverconfig.server; + +import static org.mockito.Mockito.when; + +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.web.reactive.WebFluxTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@WebFluxTest +public class GreetingControllerIntegrationTest { + + @Autowired + private WebTestClient webClient; + + @MockBean + private GreetingService greetingService; + + private final String name = "baeldung"; + + @Before + public void setUp() { + when(greetingService.greet(name)).thenReturn(Mono.just("Hello baeldung")); + } + + @Test + public void shouldGreet() { + webClient.get().uri("/greet/{name}", name) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Hello baeldung"); + } +} \ No newline at end of file diff --git a/spring-5-reactive-netty/src/test/resources/logback-test.xml b/spring-5-reactive-netty/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..39534b2c41 --- /dev/null +++ b/spring-5-reactive-netty/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + + \ No newline at end of file From 24c5be0e4f2dcfabf60a3ef8accef00eb79f4c6d Mon Sep 17 00:00:00 2001 From: isaolmez Date: Tue, 12 Mar 2019 22:37:51 +0300 Subject: [PATCH 10/54] BAEL-2715: Added code samples for Netty server configuration --- .../com/baeldung/serverconfig/client/GreetingWebClient.java | 2 +- .../server/NettyWebServerFactoryPortCustomizer.java | 1 - .../serverconfig/server/NettyWebServerFactorySslCustomizer.java | 1 - spring-5-reactive-netty/src/main/resources/logback.xml | 2 +- .../serverconfig/server/GreetingControllerIntegrationTest.java | 2 +- spring-5-reactive-netty/src/test/resources/logback-test.xml | 2 +- 6 files changed, 4 insertions(+), 6 deletions(-) diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java index d9bea649c1..77dc98398b 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java @@ -34,4 +34,4 @@ public class GreetingWebClient { .baseUrl("https://localhost:8443") .clientConnector(new ReactorClientHttpConnector(httpClient)).build(); } -} \ No newline at end of file +} diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java index be7e442afe..1dda58baa4 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java @@ -28,4 +28,3 @@ public class NettyWebServerFactoryPortCustomizer implements WebServerFactoryCust } } } - diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java index f84e8d143a..0aceae39dc 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java @@ -20,4 +20,3 @@ public class NettyWebServerFactorySslCustomizer implements WebServerFactoryCusto serverFactory.setPort(8443); } } - diff --git a/spring-5-reactive-netty/src/main/resources/logback.xml b/spring-5-reactive-netty/src/main/resources/logback.xml index fc026694b1..48b68c6bf1 100644 --- a/spring-5-reactive-netty/src/main/resources/logback.xml +++ b/spring-5-reactive-netty/src/main/resources/logback.xml @@ -28,4 +28,4 @@ - \ No newline at end of file + diff --git a/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java index 8bd4e41f1f..f8e384fb6e 100644 --- a/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java +++ b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java @@ -38,4 +38,4 @@ public class GreetingControllerIntegrationTest { .expectBody(String.class) .isEqualTo("Hello baeldung"); } -} \ No newline at end of file +} diff --git a/spring-5-reactive-netty/src/test/resources/logback-test.xml b/spring-5-reactive-netty/src/test/resources/logback-test.xml index 39534b2c41..12cedf5952 100644 --- a/spring-5-reactive-netty/src/test/resources/logback-test.xml +++ b/spring-5-reactive-netty/src/test/resources/logback-test.xml @@ -10,4 +10,4 @@ - \ No newline at end of file + From 6869885cf415e7268adca1ff1426cb8dd2d47993 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Wed, 13 Mar 2019 19:45:09 +0000 Subject: [PATCH 11/54] 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 f90dd073cb63e823d6563826d4d5b12aadaed49c Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Thu, 14 Mar 2019 09:32:06 +0000 Subject: [PATCH 12/54] 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 bac1103dccb43872ff84e7b3598bfc7916b927a9 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Fri, 15 Mar 2019 14:38:26 +0000 Subject: [PATCH 13/54] 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 7b5d3a20e19d9f9b046a3d4acadf7bb2553ecbde Mon Sep 17 00:00:00 2001 From: "anilkivilcim.eray" Date: Sat, 16 Mar 2019 10:43:29 +0300 Subject: [PATCH 14/54] BAEL-2762 init --- spring-boot-security/pom.xml | 17 +++++++++++++++-- .../WebSecurityConfigurer.java | 2 +- .../SpringBootSecurityApplication.java | 3 ++- .../SpringBootOAuth2SsoApplication.java | 1 + .../main/resources/application-authz.properties | 2 +- .../resources/application-taglibs.properties | 4 ++-- .../BasicAuthConfigurationIntegrationTest.java | 3 +-- 7 files changed, 23 insertions(+), 9 deletions(-) diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index aaa0fbf4c7..73d08c4485 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -22,6 +22,7 @@ org.springframework.security.oauth spring-security-oauth2 + ${spring-security-oauth2.version} org.springframework.boot @@ -55,6 +56,17 @@ spring-security-test test + + org.springframework.boot + spring-boot-autoconfigure + 2.1.1.RELEASE + + + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + 2.1.0.RELEASE + + @@ -68,6 +80,7 @@ com.baeldung.springbootsecurity.basic_auth.SpringBootSecurityApplication + 2.2.1.RELEASE diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java index 32a48ce612..16ce8e6fc6 100644 --- a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java @@ -12,7 +12,7 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("spring") - .password("secret") + .password("{noop}secret") .roles("USER"); } 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..7da9fbad06 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,8 @@ 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/oauth2sso/SpringBootOAuth2SsoApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java index b1cd580f08..342c246e66 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java @@ -1,6 +1,7 @@ package com.baeldung.springbootsecurity.oauth2sso; import org.springframework.boot.autoconfigure.SpringBootApplication; + import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.boot.builder.SpringApplicationBuilder; diff --git a/spring-boot-security/src/main/resources/application-authz.properties b/spring-boot-security/src/main/resources/application-authz.properties index d29b0cdd3c..0c53999bb3 100644 --- a/spring-boot-security/src/main/resources/application-authz.properties +++ b/spring-boot-security/src/main/resources/application-authz.properties @@ -1,3 +1,3 @@ -security.user.password=password +spring.security.user.password=password security.oauth2.client.client-id=client security.oauth2.client.client-secret=secret diff --git a/spring-boot-security/src/main/resources/application-taglibs.properties b/spring-boot-security/src/main/resources/application-taglibs.properties index 218868405f..3e482ed92a 100644 --- a/spring-boot-security/src/main/resources/application-taglibs.properties +++ b/spring-boot-security/src/main/resources/application-taglibs.properties @@ -1,3 +1,3 @@ #jsp config -spring.mvc.view.prefix: /WEB-INF/views/ -spring.mvc.view.suffix: .jsp +spring.mvc.view.prefix= /WEB-INF/views/ +spring.mvc.view.suffix= .jsp 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..98e76e7bab 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,10 +1,9 @@ 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.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; From 4ef58c00667058c2cd6ebd7d64285b4e0ee5d84a Mon Sep 17 00:00:00 2001 From: Dhananjay Singh Date: Sat, 16 Mar 2019 12:45:16 +0100 Subject: [PATCH 15/54] 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 4d05dd1d9e7a72bf2903286725463d0b04e8d678 Mon Sep 17 00:00:00 2001 From: isaolmez Date: Sat, 16 Mar 2019 17:01:42 +0300 Subject: [PATCH 16/54] BAEL-2715: Modified customizers --- ...tyWebServerFactoryBootstrapCustomizer.java | 49 +++++++++++++++++++ .../NettyWebServerFactoryPortCustomizer.java | 30 ------------ .../NettyWebServerFactorySslCustomizer.java | 6 ++- 3 files changed, 54 insertions(+), 31 deletions(-) create mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryBootstrapCustomizer.java delete mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryBootstrapCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryBootstrapCustomizer.java new file mode 100644 index 0000000000..05b2fbb7f7 --- /dev/null +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryBootstrapCustomizer.java @@ -0,0 +1,49 @@ +package com.baeldung.serverconfig.server; + +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.stereotype.Component; +import reactor.netty.http.server.HttpServer; + +@Component +public class NettyWebServerFactoryBootstrapCustomizer implements WebServerFactoryCustomizer { + + @Override + public void customize(NettyReactiveWebServerFactory serverFactory) { + serverFactory.addServerCustomizers(new PortCustomizer(8443)); + serverFactory.addServerCustomizers(new EventLoopNettyCustomizer()); + } + + private static class PortCustomizer implements NettyServerCustomizer { + + private final int port; + + private PortCustomizer(int port) { + this.port = port; + } + + @Override + public HttpServer apply(HttpServer httpServer) { + return httpServer.port(port); + } + } + + private static class EventLoopNettyCustomizer implements NettyServerCustomizer { + + @Override + public HttpServer apply(HttpServer httpServer) { + EventLoopGroup parentGroup = new NioEventLoopGroup(); + EventLoopGroup childGroup = new NioEventLoopGroup(); + return httpServer + .tcpConfiguration(tcpServer -> tcpServer.bootstrap( + serverBootstrap -> serverBootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class) + )); + + } + + } +} diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java deleted file mode 100644 index 1dda58baa4..0000000000 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryPortCustomizer.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.serverconfig.server; - -import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; -import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; -import org.springframework.boot.web.server.WebServerFactoryCustomizer; -import org.springframework.stereotype.Component; -import reactor.netty.http.server.HttpServer; - -@Component -public class NettyWebServerFactoryPortCustomizer implements WebServerFactoryCustomizer { - - @Override - public void customize(NettyReactiveWebServerFactory serverFactory) { - serverFactory.addServerCustomizers(new PortCustomizer(8443)); - } - - private static class PortCustomizer implements NettyServerCustomizer { - - private final int port; - - private PortCustomizer(int port) { - this.port = port; - } - - @Override - public HttpServer apply(HttpServer httpServer) { - return httpServer.port(port); - } - } -} diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java index 0aceae39dc..d03c3a7f40 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java @@ -1,6 +1,8 @@ package com.baeldung.serverconfig.server; import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.embedded.netty.SslServerCustomizer; +import org.springframework.boot.web.server.Http2; import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.stereotype.Component; @@ -16,7 +18,9 @@ public class NettyWebServerFactorySslCustomizer implements WebServerFactoryCusto ssl.setKeyAlias("alias"); ssl.setKeyPassword("password"); ssl.setKeyStorePassword("secret"); - serverFactory.setSsl(ssl); + Http2 http2 = new Http2(); + http2.setEnabled(false); + serverFactory.addServerCustomizers(new SslServerCustomizer(ssl, http2, null)); serverFactory.setPort(8443); } } From d5e91a8d341ee6e937061c20db9e17d0b8594a8c Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Sat, 16 Mar 2019 22:15:22 +0000 Subject: [PATCH 17/54] 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 18/54] 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 19/54] 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 20/54] 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 21/54] 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 22/54] 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 23/54] 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 24/54] 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 25/54] 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 26/54] 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 27/54] 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 28/54] 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 29/54] 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 30/54] 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 31/54] 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 e813a0e64d9828f00643185d5232dacfdf452dc9 Mon Sep 17 00:00:00 2001 From: isaolmez Date: Tue, 19 Mar 2019 22:29:12 +0300 Subject: [PATCH 32/54] BAEL-2715: Modified tests and configurations --- ....java => CustomNettyWebServerFactory.java} | 35 ++++-------- .../{server => }/GreetingController.java | 2 +- .../{server => }/GreetingService.java | 2 +- .../NettyWebServerFactoryPortCustomizer.java | 30 ++++++++++ .../NettyWebServerFactorySslCustomizer.java | 2 +- .../serverconfig/ServerConfigApplication.java | 4 -- .../client/GreetingWebClient.java | 37 ------------ .../GreetingControllerIntegrationTest.java | 8 +-- .../serverconfig/GreetingLiveTest.java | 56 +++++++++++++++++++ .../GreetingSkipAutoConfigLiveTest.java | 8 +++ 10 files changed, 113 insertions(+), 71 deletions(-) rename spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/{server/NettyWebServerFactoryBootstrapCustomizer.java => CustomNettyWebServerFactory.java} (51%) rename spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/{server => }/GreetingController.java (94%) rename spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/{server => }/GreetingService.java (84%) create mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/NettyWebServerFactoryPortCustomizer.java rename spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/{server => }/NettyWebServerFactorySslCustomizer.java (96%) delete mode 100644 spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java rename spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/{server => }/GreetingControllerIntegrationTest.java (87%) create mode 100644 spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingLiveTest.java create mode 100644 spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingSkipAutoConfigLiveTest.java diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryBootstrapCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/CustomNettyWebServerFactory.java similarity index 51% rename from spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryBootstrapCustomizer.java rename to spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/CustomNettyWebServerFactory.java index 05b2fbb7f7..32e57d2d98 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactoryBootstrapCustomizer.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/CustomNettyWebServerFactory.java @@ -1,35 +1,24 @@ -package com.baeldung.serverconfig.server; +package com.baeldung.serverconfig; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; -import org.springframework.boot.web.server.WebServerFactoryCustomizer; -import org.springframework.stereotype.Component; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; import reactor.netty.http.server.HttpServer; -@Component -public class NettyWebServerFactoryBootstrapCustomizer implements WebServerFactoryCustomizer { +@Configuration +@Profile("skipAutoConfig") +public class CustomNettyWebServerFactory { - @Override - public void customize(NettyReactiveWebServerFactory serverFactory) { - serverFactory.addServerCustomizers(new PortCustomizer(8443)); - serverFactory.addServerCustomizers(new EventLoopNettyCustomizer()); - } - - private static class PortCustomizer implements NettyServerCustomizer { - - private final int port; - - private PortCustomizer(int port) { - this.port = port; - } - - @Override - public HttpServer apply(HttpServer httpServer) { - return httpServer.port(port); - } + @Bean + public NettyReactiveWebServerFactory nettyReactiveWebServerFactory() { + NettyReactiveWebServerFactory webServerFactory = new NettyReactiveWebServerFactory(); + webServerFactory.addServerCustomizers(new EventLoopNettyCustomizer()); + return webServerFactory; } private static class EventLoopNettyCustomizer implements NettyServerCustomizer { diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingController.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/GreetingController.java similarity index 94% rename from spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingController.java rename to spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/GreetingController.java index 275439a66f..9cb5b27ac5 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingController.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/GreetingController.java @@ -1,4 +1,4 @@ -package com.baeldung.serverconfig.server; +package com.baeldung.serverconfig; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingService.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/GreetingService.java similarity index 84% rename from spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingService.java rename to spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/GreetingService.java index 5b2b246531..5440f526aa 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/GreetingService.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/GreetingService.java @@ -1,4 +1,4 @@ -package com.baeldung.serverconfig.server; +package com.baeldung.serverconfig; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/NettyWebServerFactoryPortCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/NettyWebServerFactoryPortCustomizer.java new file mode 100644 index 0000000000..152e1285aa --- /dev/null +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/NettyWebServerFactoryPortCustomizer.java @@ -0,0 +1,30 @@ +package com.baeldung.serverconfig; + +import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.stereotype.Component; +import reactor.netty.http.server.HttpServer; + +@Component +public class NettyWebServerFactoryPortCustomizer implements WebServerFactoryCustomizer { + + @Override + public void customize(NettyReactiveWebServerFactory serverFactory) { + serverFactory.addServerCustomizers(new PortCustomizer(8443)); + } + + private static class PortCustomizer implements NettyServerCustomizer { + + private final int port; + + private PortCustomizer(int port) { + this.port = port; + } + + @Override + public HttpServer apply(HttpServer httpServer) { + return httpServer.port(port); + } + } +} diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/NettyWebServerFactorySslCustomizer.java similarity index 96% rename from spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java rename to spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/NettyWebServerFactorySslCustomizer.java index d03c3a7f40..d0ad0dcac5 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/server/NettyWebServerFactorySslCustomizer.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/NettyWebServerFactorySslCustomizer.java @@ -1,4 +1,4 @@ -package com.baeldung.serverconfig.server; +package com.baeldung.serverconfig; import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; import org.springframework.boot.web.embedded.netty.SslServerCustomizer; diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/ServerConfigApplication.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/ServerConfigApplication.java index c4ff9c3930..9d420cc7da 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/ServerConfigApplication.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/ServerConfigApplication.java @@ -1,6 +1,5 @@ package com.baeldung.serverconfig; -import com.baeldung.serverconfig.client.GreetingWebClient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -9,8 +8,5 @@ public class ServerConfigApplication { public static void main(String[] args) { SpringApplication.run(ServerConfigApplication.class, args); - - GreetingWebClient webClient = new GreetingWebClient(); - webClient.getResult(); } } diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java deleted file mode 100644 index 77dc98398b..0000000000 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/client/GreetingWebClient.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.serverconfig.client; - -import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslContextBuilder; -import io.netty.handler.ssl.util.InsecureTrustManagerFactory; -import lombok.SneakyThrows; -import org.springframework.http.client.reactive.ReactorClientHttpConnector; -import org.springframework.web.reactive.function.client.WebClient; -import reactor.core.publisher.Mono; -import reactor.netty.http.client.HttpClient; - -public class GreetingWebClient { - - private WebClient client = getWebClient(); - - public void getResult() { - System.out.println("Mono"); - Mono greetingMono = client.get() - .uri("/greet/{name}", "baeldung") - .retrieve() - .bodyToMono(String.class); - - greetingMono.subscribe(System.out::println); - } - - @SneakyThrows - private WebClient getWebClient() { - SslContext sslContext = SslContextBuilder - .forClient() - .trustManager(InsecureTrustManagerFactory.INSTANCE) - .build(); - HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext)); - return WebClient.builder() - .baseUrl("https://localhost:8443") - .clientConnector(new ReactorClientHttpConnector(httpClient)).build(); - } -} diff --git a/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingControllerIntegrationTest.java similarity index 87% rename from spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java rename to spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingControllerIntegrationTest.java index f8e384fb6e..3c2c08321a 100644 --- a/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/server/GreetingControllerIntegrationTest.java +++ b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.serverconfig.server; +package com.baeldung.serverconfig; import static org.mockito.Mockito.when; @@ -22,11 +22,11 @@ public class GreetingControllerIntegrationTest { @MockBean private GreetingService greetingService; - private final String name = "baeldung"; + private final String name = "Baeldung"; @Before public void setUp() { - when(greetingService.greet(name)).thenReturn(Mono.just("Hello baeldung")); + when(greetingService.greet(name)).thenReturn(Mono.just("Greeting Baeldung")); } @Test @@ -36,6 +36,6 @@ public class GreetingControllerIntegrationTest { .expectStatus() .isOk() .expectBody(String.class) - .isEqualTo("Hello baeldung"); + .isEqualTo("Greeting Baeldung"); } } diff --git a/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingLiveTest.java b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingLiveTest.java new file mode 100644 index 0000000000..7c4a37c890 --- /dev/null +++ b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingLiveTest.java @@ -0,0 +1,56 @@ +package com.baeldung.serverconfig; + +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import javax.net.ssl.SSLException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; +import reactor.netty.http.client.HttpClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) +public class GreetingLiveTest { + + private static final String BASE_URL = "https://localhost:8443"; + + private WebTestClient webTestClient; + + @Before + public void setup() throws SSLException { + webTestClient = WebTestClient.bindToServer(getConnector()) + .baseUrl(BASE_URL) + .build(); + } + + @Test + public void shouldGreet() { + final String name = "Baeldung"; + + ResponseSpec response = webTestClient.get() + .uri("/greet/{name}", name) + .exchange(); + + response.expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Greeting Baeldung"); + } + + private ReactorClientHttpConnector getConnector() throws SSLException { + SslContext sslContext = SslContextBuilder + .forClient() + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .build(); + HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext)); + return new ReactorClientHttpConnector(httpClient); + } +} diff --git a/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingSkipAutoConfigLiveTest.java b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingSkipAutoConfigLiveTest.java new file mode 100644 index 0000000000..646742b3d7 --- /dev/null +++ b/spring-5-reactive-netty/src/test/java/com/baeldung/serverconfig/GreetingSkipAutoConfigLiveTest.java @@ -0,0 +1,8 @@ +package com.baeldung.serverconfig; + +import org.springframework.test.context.ActiveProfiles; + +@ActiveProfiles("skipAutoConfig") +public class GreetingSkipAutoConfigLiveTest extends GreetingLiveTest { + +} From ddcc4964688a1a2a21119c85dfb02cdb237d571b Mon Sep 17 00:00:00 2001 From: isaolmez Date: Tue, 19 Mar 2019 22:44:07 +0300 Subject: [PATCH 33/54] BAEL-2715: Modified tests and configurations --- .../com/baeldung/serverconfig/CustomNettyWebServerFactory.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/CustomNettyWebServerFactory.java b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/CustomNettyWebServerFactory.java index 32e57d2d98..8a1cdbba97 100644 --- a/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/CustomNettyWebServerFactory.java +++ b/spring-5-reactive-netty/src/main/java/com/baeldung/serverconfig/CustomNettyWebServerFactory.java @@ -31,8 +31,6 @@ public class CustomNettyWebServerFactory { .tcpConfiguration(tcpServer -> tcpServer.bootstrap( serverBootstrap -> serverBootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class) )); - } - } } From 88ca90327cad42fa560d283707c99cc278f9dc48 Mon Sep 17 00:00:00 2001 From: enpy Date: Wed, 20 Mar 2019 03:59:02 +0100 Subject: [PATCH 34/54] 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 35/54] 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 36/54] 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); + } + + +} From 284542701f10101e660198c74477158d1e7b5a53 Mon Sep 17 00:00:00 2001 From: "anilkivilcim.eray" Date: Wed, 20 Mar 2019 23:21:11 +0300 Subject: [PATCH 37/54] BAEL-2762 Fix tests in spring-boot-security module --- .../basic_auth/config/BasicAuthConfiguration.java | 9 +++++++-- .../config/AuthorizationServerConfig.java | 4 ++-- .../config/WebSecurityConfiguration.java | 15 +++++++++++++++ .../config/SpringBootSecurityTagLibsConfig.java | 2 +- .../BasicAuthConfigurationIntegrationTest.java | 5 ++--- 5 files changed, 27 insertions(+), 8 deletions(-) create mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java 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..a8a561a567 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,17 @@ public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { + PasswordEncoder encoder = + PasswordEncoderFactories.createDelegatingPasswordEncoder(); + auth .inMemoryAuthentication() .withUser("user") - .password("password") + .password(encoder.encode("password")) .roles("USER") .and() .withUser("admin") - .password("admin") + .password("{noop}admin") .roles("USER", "ADMIN"); } diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java index b403feb5c1..4686100638 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java @@ -25,13 +25,13 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap clients .inMemory() .withClient("baeldung") - .secret("baeldung") + .secret("{noop}baeldung") .authorizedGrantTypes("client_credentials", "password", "authorization_code") .scopes("openid", "read") .autoApprove(true) .and() .withClient("baeldung-admin") - .secret("baeldung") + .secret("{noop}baeldung") .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token") .scopes("read", "write") .autoApprove(true); diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java new file mode 100644 index 0000000000..f2540c01b8 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.springbootsecurity.oauth2server.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Bean + public AuthenticationManager customAuthenticationManager() throws Exception { + return authenticationManager(); + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java index 665dd0bce9..59ae2885ad 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java @@ -14,7 +14,7 @@ public class SpringBootSecurityTagLibsConfig extends WebSecurityConfigurerAdapte protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("testUser") - .password("password") + .password("{noop}password") .roles("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 98e76e7bab..a5c2d11a01 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,5 +1,6 @@ package com.baeldung.springbootsecurity.basic_auth; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -49,8 +50,6 @@ public class BasicAuthConfigurationIntegrationTest { ResponseEntity response = restTemplate.getForEntity(base.toString(), String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); - assertTrue(response - .getBody() - .contains("Unauthorized")); + Assert.assertNull(response.getBody()); } } From 117e4038b9a4503b600fa4ef5b2b618c1b756867 Mon Sep 17 00:00:00 2001 From: "sumit.sg34" Date: Thu, 21 Mar 2019 10:24:37 +0530 Subject: [PATCH 38/54] BAEL-2827 code added for deleteby methods --- .../spring-data-jpa-2/README.md | 34 ++++++++++ persistence-modules/spring-data-jpa-2/pom.xml | 30 +++++++++ .../main/java/com/baeldung/Application.java | 13 ++++ .../main/java/com/baeldung/entity/Fruit.java | 38 +++++++++++ .../baeldung/repository/FruitRepository.java | 20 ++++++ .../src/main/resources/application.properties | 1 + .../FruitRepositoryIntegrationTest.java | 65 +++++++++++++++++++ .../src/test/resources/test-fruit-data.sql | 4 ++ 8 files changed, 205 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-2/README.md create mode 100644 persistence-modules/spring-data-jpa-2/pom.xml create mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java create mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java create mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java create mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/application.properties create mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md new file mode 100644 index 0000000000..8dff49640e --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -0,0 +1,34 @@ +========= + +## Spring Data JPA Example Project + +### Relevant Articles: +- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) +- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) +- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) +- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) +- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) +- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) +- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) +- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) +- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) +- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) +- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) +- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) +- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) +- [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting) +- [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) +- [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: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/persistence-modules/spring-data-jpa-2/pom.xml b/persistence-modules/spring-data-jpa-2/pom.xml new file mode 100644 index 0000000000..8e46112659 --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + com.baeldung + spring-data-jpa-2 + spring-data-jpa + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..3ea3d113da --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +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/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java new file mode 100644 index 0000000000..f82022e67e --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java @@ -0,0 +1,38 @@ +package com.baeldung.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Fruit { + + @Id + private long id; + private String name; + private String color; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java new file mode 100644 index 0000000000..b3dcc0542b --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java @@ -0,0 +1,20 @@ +package com.baeldung.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.entity.Fruit; + +@Repository +public interface FruitRepository extends JpaRepository { + + Long deleteByName(String name); + + List deleteByColor(String color); + + Long removeByName(String name); + + List removeByColor(String color); +} diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties new file mode 100644 index 0000000000..72fc330767 --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.jpa.show-sql=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java new file mode 100644 index 0000000000..45c106337f --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java @@ -0,0 +1,65 @@ +package com.baeldung.repository; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.junit.jupiter.api.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.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.entity.Fruit; + +@RunWith(SpringRunner.class) +@SpringBootTest +class FruitRepositoryIntegrationTest { + + @Autowired + private FruitRepository fruitRepository; + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenDeletedByColor_DeletedFruitShouldReturn() { + + List fruits = fruitRepository.deleteByColor("green"); + + assertEquals("number of fruits are not matching", 2, fruits.size()); + fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenDeletedByName_DeletedFruitCountShouldReturn() { + + Long deletedFruitCount = fruitRepository.deleteByName("apple"); + + assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenRemovedByColor_DeletedFruitShouldReturn() { + + List fruits = fruitRepository.removeByColor("green"); + + assertEquals("number of fruits are not matching", 2, fruits.size()); + fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenRemovedByName_DeletedFruitCountShouldReturn() { + + Long deletedFruitCount = fruitRepository.removeByName("apple"); + + assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql new file mode 100644 index 0000000000..ce2189121f --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql @@ -0,0 +1,4 @@ +insert into fruit(id,name,color) values (1,'apple','red'); +insert into fruit(id,name,color) values (2,'custard apple','green'); +insert into fruit(id,name,color) values (3,'mango','yellow'); +insert into fruit(id,name,color) values (4,'guava','green'); \ No newline at end of file From 26f8de58348f41d1a8c668edd70cf83def25bffd Mon Sep 17 00:00:00 2001 From: "anilkivilcim.eray" Date: Thu, 21 Mar 2019 09:54:15 +0300 Subject: [PATCH 39/54] BAEL-2762 renaming HomeControllerIntegrationTest to HomeControllerUnitTest --- ...ntrollerIntegrationTest.java => HomeControllerUnitTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/{HomeControllerIntegrationTest.java => HomeControllerUnitTest.java} (98%) diff --git a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java similarity index 98% rename from spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerIntegrationTest.java rename to spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java index 654e7925b9..0585c06a59 100644 --- a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerIntegrationTest.java +++ b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class) -public class HomeControllerIntegrationTest { +public class HomeControllerUnitTest { @Autowired private TestRestTemplate restTemplate; From e4725557a2b49991d37f31245c4e00835d7906c1 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 21 Mar 2019 16:43:08 +0100 Subject: [PATCH 40/54] BAEL-2777 Add a new section in Sorting with Lambda article (#6546) --- .../com/baeldung/java8/Java8SortUnitTest.java | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index 71ec5b147f..57d9d8347b 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -124,11 +124,44 @@ public class Java8SortUnitTest { @Test public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { - final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); final Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName()); final List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList()); Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); } + + @Test + public final void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { + final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); + + final List sortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName)).collect(Collectors.toList()); + Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); + } + + @Test + public final void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { + final List letters = Lists.newArrayList("B", "A", "C"); + + final List reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); + Assert.assertThat(reverseSortedLetters.get(0), equalTo("C")); + } + + @Test + public final void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { + final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); + final Comparator reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName()); + + final List reverseSortedHumans = humans.stream().sorted(reverseNameComparator).collect(Collectors.toList()); + Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10))); + } + + @Test + public final void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { + final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); + + final List reverseSortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())).collect(Collectors.toList()); + Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10))); + } + } From 18eb32a7dbf2405b30c59cd0ce36b171b6c74b6f Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Fri, 22 Mar 2019 03:46:02 +0430 Subject: [PATCH 41/54] Introducing the core-java-12 module. It's ignored just like other 9+ versions. --- core-java-12/pom.xml | 48 ++++++++++++ .../collectors/CollectorsUnitTest.java | 77 +++++++++++++++++++ pom.xml | 1 + 3 files changed, 126 insertions(+) create mode 100644 core-java-12/pom.xml create mode 100644 core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java diff --git a/core-java-12/pom.xml b/core-java-12/pom.xml new file mode 100644 index 0000000000..729b29381b --- /dev/null +++ b/core-java-12/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + com.baeldung + core-java-12 + 0.1.0-SNAPSHOT + core-java-12 + jar + http://maven.apache.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + + + + 12 + 12 + 3.6.1 + + + \ No newline at end of file diff --git a/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java b/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java new file mode 100644 index 0000000000..68915b504d --- /dev/null +++ b/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.collectors; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +import org.junit.Test; + +import static java.util.stream.Collectors.maxBy; +import static java.util.stream.Collectors.minBy; +import static java.util.stream.Collectors.teeing; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit tests for collectors additions in Java 12. + */ +public class CollectorsUnitTest { + + @Test + public void whenTeeing_ItShouldCombineTheResultsAsExpected() { + List numbers = Arrays.asList(42, 4, 2, 24); + Range range = numbers.stream() + .collect(teeing( + minBy(Integer::compareTo), + maxBy(Integer::compareTo), + (min, max) -> new Range(min.orElse(null), max.orElse(null)) + )); + + assertThat(range).isEqualTo(new Range(2, 42)); + } + + /** + * Represents a closed range of numbers between {@link #min} and + * {@link #max}, both inclusive. + */ + private static class Range { + + private final Integer min; + + private final Integer max; + + Range(Integer min, Integer max) { + this.min = min; + this.max = max; + } + + Integer getMin() { + return min; + } + + Integer getMax() { + return max; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Range range = (Range) o; + return Objects.equals(getMin(), range.getMin()) && + Objects.equals(getMax(), range.getMax()); + } + + @Override + public int hashCode() { + return Objects.hash(getMin(), getMax()); + } + + @Override + public String toString() { + return "Range{" + + "min=" + min + + ", max=" + max + + '}'; + } + } +} diff --git a/pom.xml b/pom.xml index bf225d82f0..d97c30ad64 100644 --- a/pom.xml +++ b/pom.xml @@ -377,6 +377,7 @@ core-groovy + core-java-8 From 4b962b45e823386c02f835e01bb165587c4188cc Mon Sep 17 00:00:00 2001 From: eelhazati <35301254+eelhazati@users.noreply.github.com> Date: Fri, 22 Mar 2019 11:44:17 +0000 Subject: [PATCH 42/54] Update application.properties --- .../src/main/resources/application.properties | 21 ++++--------------- 1 file changed, 4 insertions(+), 17 deletions(-) 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 index de8e1a7b9f..4b9d8106eb 100644 --- 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 @@ -1,23 +1,10 @@ -# 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.client-id=webappclient +spring.security.oauth2.client.registration.uaa.client-secret=webappclientsecret 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 +spring.security.oauth2.client.provider.uaa.issuer-uri=http://localhost:8080/uaa/oauth/token + From c6a54656f22df47565b5cc8130435738383ca534 Mon Sep 17 00:00:00 2001 From: eelhazati <35301254+eelhazati@users.noreply.github.com> Date: Fri, 22 Mar 2019 11:45:49 +0000 Subject: [PATCH 43/54] Update application.properties --- .../src/main/resources/application.properties | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) 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 index ba9b95e0d4..a6e846a00f 100644 --- 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 @@ -1,16 +1,3 @@ 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 +spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/uaa/oauth/token From 700a9530d78cb33eb8e475a7968a5ee7e7882ad2 Mon Sep 17 00:00:00 2001 From: eelhazati <35301254+eelhazati@users.noreply.github.com> Date: Fri, 22 Mar 2019 11:57:45 +0000 Subject: [PATCH 44/54] Update uaa.yml --- cloud-foundry-uaa/cf-uaa-config/uaa.yml | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/cloud-foundry-uaa/cf-uaa-config/uaa.yml b/cloud-foundry-uaa/cf-uaa-config/uaa.yml index b782c2b681..ebaa99fb6c 100644 --- a/cloud-foundry-uaa/cf-uaa-config/uaa.yml +++ b/cloud-foundry-uaa/cf-uaa-config/uaa.yml @@ -1,12 +1,7 @@ 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 +spring_profiles: default,hsqldb encryption: active_key_label: CHANGE-THIS-KEY From 640af4ccbea16195e1cc8b0620392c328d2e2c83 Mon Sep 17 00:00:00 2001 From: eelhazati <35301254+eelhazati@users.noreply.github.com> Date: Fri, 22 Mar 2019 12:49:37 +0000 Subject: [PATCH 45/54] Update application.properties --- .../src/main/resources/application.properties | 1 + 1 file changed, 1 insertion(+) 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 index 4b9d8106eb..8e8797ce54 100644 --- 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 @@ -2,6 +2,7 @@ server.port=8081 resource.server.url=http://localhost:8082 +spring.security.oauth2.client.registration.uaa.client-name=Web App Client spring.security.oauth2.client.registration.uaa.client-id=webappclient spring.security.oauth2.client.registration.uaa.client-secret=webappclientsecret spring.security.oauth2.client.registration.uaa.scope=resource.read,resource.write,openid,profile From 4151e55d3b32e963dbf67b489a2d827fe8587d1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Frankowski?= Date: Mon, 11 Mar 2019 18:17:36 +0100 Subject: [PATCH 46/54] [BAEL-2664] Groovy collections find --- .../main/groovy/com/baeldung/Person.groovy | 37 ++++++++++ .../groovy/com/baeldung/lists/ListTest.groovy | 8 +- .../com/baeldung/lists/ListUnitTest.groovy | 58 +++++++++++++++ .../com/baeldung/map/MapUnitTest.groovy | 73 ++++++++++++++++++- .../com/baeldung/set/SetUnitTest.groovy | 16 ++++ 5 files changed, 186 insertions(+), 6 deletions(-) create mode 100644 core-groovy/src/main/groovy/com/baeldung/Person.groovy create mode 100644 core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy create mode 100644 core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy diff --git a/core-groovy/src/main/groovy/com/baeldung/Person.groovy b/core-groovy/src/main/groovy/com/baeldung/Person.groovy new file mode 100644 index 0000000000..6a009aeee0 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/Person.groovy @@ -0,0 +1,37 @@ +package com.baeldung + +class Person { + private String firstname + private String lastname + private Integer age + + Person(String firstname, String lastname, Integer age) { + this.firstname = firstname + this.lastname = lastname + this.age = age + } + + String getFirstname() { + return firstname + } + + void setFirstname(String firstname) { + this.firstname = firstname + } + + String getLastname() { + return lastname + } + + void setLastname(String lastname) { + this.lastname = lastname + } + + Integer getAge() { + return age + } + + void setAge(Integer age) { + this.age = age + } +} 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 f682503ed4..7771028132 100644 --- a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy @@ -129,13 +129,13 @@ class ListTest{ assertTrue(filterList.findAll{it > 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]) def conditionList = [2, 1, 3, 4, 5, 6, 76] - + assertFalse(conditionList.every{ it < 6}) assertTrue(conditionList.any{ it%2 == 0}) @@ -165,7 +165,7 @@ class ListTest{ def strList = ["na", "ppp", "as"] assertTrue(strList.max() == "ppp") - + Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1} def numberList = [3, 2, 0, 7] assertTrue(numberList.min(minc) == 0) diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy new file mode 100644 index 0000000000..9617c099ce --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy @@ -0,0 +1,58 @@ +package com.baeldung.lists + +import com.baeldung.Person +import org.junit.Test + +import static org.junit.Assert.* + +class ListUnitTest { + + private final personList = [ + new Person("Regina", "Fitzpatrick", 25), + new Person("Abagail", "Ballard", 26), + new Person("Lucian", "Walter", 30), + ] + + @Test + void whenListContainsElement_thenCheckReturnsTrue() { + def list = ['a', 'b', 'c'] + + assertTrue(list.indexOf('a') > -1) + assertTrue(list.contains('a')) + } + + @Test + void whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue() { + def list = ['a', 'b', 'c'] + + assertTrue('a' in list) + } + + @Test + void givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList() { + assertTrue(personList.stream().anyMatch {it.age > 20}) + assertFalse(personList.stream().allMatch {it.age < 30}) + } + + @Test + void givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList() { + assertTrue(personList.any {it.age > 20}) + assertFalse(personList.every {it.age < 30}) + } + + @Test + void givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements() { + assertTrue(personList.stream().filter {it.age > 20}.findAny().isPresent()) + assertFalse(personList.stream().filter {it.age > 30}.findAny().isPresent()) + assertTrue(personList.stream().filter {it.age > 20}.findAll().size() == 3) + assertTrue(personList.stream().filter {it.age > 30}.findAll().isEmpty()) + } + + @Test + void givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements() { + assertNotNull(personList.find {it.age > 20}) + assertNull(personList.find {it.age > 30}) + assertTrue(personList.findAll {it.age > 20}.size() == 3) + assertTrue(personList.findAll {it.age > 30}.isEmpty()) + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy index 97ffc50c76..0d6bbed04b 100644 --- a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy @@ -1,10 +1,18 @@ package com.baeldung.map -import static org.junit.Assert.* +import com.baeldung.Person import org.junit.Test +import static org.junit.Assert.* + class MapUnitTest { + private final personMap = [ + Regina : new Person("Regina", "Fitzpatrick", 25), + Abagail: new Person("Abagail", "Ballard", 26), + Lucian : new Person("Lucian", "Walter", 30) + ] + @Test void whenUsingEach_thenMapIsIterated() { def map = [ @@ -63,7 +71,7 @@ class MapUnitTest { 'FF6347' : 'Tomato', 'FF4500' : 'Orange Red' ] - + map.eachWithIndex { key, val, index -> def indent = ((index == 0 || index % 2 == 0) ? " " : "") println "$indent Hex Code: $key = Color Name: $val" @@ -82,4 +90,65 @@ class MapUnitTest { println "Hex Code: $entry.key = Color Name: $entry.value" } } + + @Test + void whenMapContainsKeyElement_thenCheckReturnsTrue() { + def map = [a: 'd', b: 'e', c: 'f'] + + assertTrue(map.containsKey('a')) + assertFalse(map.containsKey('e')) + assertTrue(map.containsValue('e')) + } + + @Test + void whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue() { + def map = [a: 'd', b: 'e', c: 'f'] + + assertTrue('a' in map) + assertFalse('f' in map) + } + + @Test + void whenMapContainsFalseBooleanValues_thenCheckReturnsFalse() { + def map = [a: true, b: false, c: null] + + assertTrue(map.containsKey('b')) + assertTrue('a' in map) + assertFalse('b' in map) + assertFalse('c' in map) + } + + @Test + void givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap() { + assertTrue(personMap.keySet().stream().anyMatch {it == "Regina"}) + assertFalse(personMap.keySet().stream().allMatch {it == "Albert"}) + assertFalse(personMap.values().stream().allMatch {it.age < 30}) + assertTrue(personMap.entrySet().stream().anyMatch {it.key == "Abagail" && it.value.lastname == "Ballard"}) + } + + @Test + void givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap() { + assertTrue(personMap.keySet().any {it == "Regina"}) + assertFalse(personMap.keySet().every {it == "Albert"}) + assertFalse(personMap.values().every {it.age < 30}) + assertTrue(personMap.any {firstname, person -> firstname == "Abagail" && person.lastname == "Ballard"}) + } + + @Test + void givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements() { + assertNotNull(personMap.find {it.key == "Abagail" && it.value.lastname == "Ballard"}) + assertTrue(personMap.findAll {it.value.age > 20}.size() == 3) + } + + @Test + void givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements() { + assertTrue( + personMap.entrySet().stream() + .filter {it.key == "Abagail" && it.value.lastname == "Ballard"} + .findAny().isPresent()) + assertTrue( + personMap.entrySet().stream() + .filter {it.value.age > 20} + .findAll().size() == 3) + } } diff --git a/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy new file mode 100644 index 0000000000..1248c9ac91 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy @@ -0,0 +1,16 @@ +package com.baeldung.set + +import org.junit.Test + +import static org.junit.Assert.assertTrue + +class SetUnitTest { + + @Test + void whenSetContainsElement_thenCheckReturnsTrue() { + def set = ['a', 'b', 'c'] as Set + + assertTrue(set.contains('a')) + assertTrue('a' in set) + } +} \ No newline at end of file From 2b8c73c3767691b7e226de82f931cf3a57449a90 Mon Sep 17 00:00:00 2001 From: "sumit.sg34" Date: Fri, 22 Mar 2019 23:20:12 +0530 Subject: [PATCH 47/54] BAEL-2827 added one example for @query --- .../com/baeldung/repository/FruitRepository.java | 7 +++++++ .../repository/FruitRepositoryIntegrationTest.java | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java index b3dcc0542b..9f92909b66 100644 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java @@ -3,6 +3,9 @@ package com.baeldung.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.baeldung.entity.Fruit; @@ -17,4 +20,8 @@ public interface FruitRepository extends JpaRepository { Long removeByName(String name); List removeByColor(String color); + + @Modifying + @Query("delete from Fruit f where f.name=:name or f.color=:color") + List deleteFruits(@Param("name") String name, @Param("color") String color); } diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java index 45c106337f..74188497ee 100644 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java @@ -1,6 +1,7 @@ package com.baeldung.repository; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.List; @@ -62,4 +63,15 @@ class FruitRepositoryIntegrationTest { assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenDeletedByColorOrName_DeletedFruitShouldReturn() { + + List fruits = fruitRepository.deleteFruits("apple", "green"); + + assertEquals("number of fruits are not matching", 3, fruits.size()); + fruits.forEach(fruit -> assertTrue("Its not a green fruit or apple", ("green".equals(fruit.getColor())) || "apple".equals(fruit.getColor()))); + } } \ No newline at end of file From cc73a3051b80af57351cf072b9d61c6c6db0924e Mon Sep 17 00:00:00 2001 From: rahusriv Date: Sat, 23 Mar 2019 05:17:23 +0530 Subject: [PATCH 48/54] Rahul/socket/read/pr4 (#6575) * Making examples simple * Changing variable names * Modificatons in naming * Review changes --- .../java/com/baeldung/socket/read/Client.java | 30 ++++------- .../java/com/baeldung/socket/read/Server.java | 50 +++++++++---------- 2 files changed, 35 insertions(+), 45 deletions(-) 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 index 08292237f2..5e2a84a767 100644 --- 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 @@ -1,35 +1,27 @@ package com.baeldung.socket.read; -import java.net.*; +import java.net.*; +import java.nio.charset.StandardCharsets; 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); + Socket 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 { + DataInputStream in = new DataInputStream(System.in); + DataOutputStream out = new DataOutputStream(socket.getOutputStream()); + + char type = 's'; // s for string + int length = 29; + String data = "This is a string of length 29"; + byte[] dataInBytes = data.getBytes(StandardCharsets.UTF_8); + //Sending data in TLV format out.writeChar(type); out.writeInt(length); out.write(dataInBytes); } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } } 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 index bdb3a4449f..2ab91c6cdc 100644 --- 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 @@ -1,48 +1,46 @@ package com.baeldung.socket.read; -import java.net.*; +import java.net.*; +import java.nio.charset.StandardCharsets; 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); + ServerSocket server = new ServerSocket(port); System.out.println("Server Started. Waiting for connection ..."); - socket = server.accept(); + Socket 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())); + 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; + if(dataType == 's') { + //Read String data in bytes + byte[] messageByte = new byte[length]; + boolean end = false; + StringBuilder dataString = new StringBuilder(length); + 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.append(new String(messageByte,0,currentBytesRead,StandardCharsets.UTF_8)); + } else { + dataString.append(new String(messageByte,0,length - totalBytesRead + currentBytesRead,StandardCharsets.UTF_8)); + } + if(dataString.length()>=length) { + end = true; + } } + System.out.println("Read "+length+" bytes of message from client. Message = "+dataString); } - System.out.println("Read "+length+" bytes of message from client. Message = "+dataString);; } catch (Exception e) { e.printStackTrace(); } From 5575383a0dd671ee20587ae049d23d89938454bd Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 23 Mar 2019 12:15:58 +0200 Subject: [PATCH 49/54] Update README.md --- .../spring-data-jpa-2/README.md | 29 ------------------- 1 file changed, 29 deletions(-) diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 8dff49640e..295a434d17 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -3,32 +3,3 @@ ## Spring Data JPA Example Project ### Relevant Articles: -- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) -- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) -- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) -- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) -- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) -- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) -- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) -- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) -- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) -- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) -- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) -- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) -- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) -- [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting) -- [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) -- [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: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator - From 683fc563a6e2f999e49ea4410b1994d384c630c3 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 23 Mar 2019 12:30:06 +0200 Subject: [PATCH 50/54] formatting --- core-java-12/pom.xml | 80 ++++++++--------- .../collectors/CollectorsUnitTest.java | 90 +++++++++---------- 2 files changed, 82 insertions(+), 88 deletions(-) diff --git a/core-java-12/pom.xml b/core-java-12/pom.xml index 729b29381b..defef5e9d3 100644 --- a/core-java-12/pom.xml +++ b/core-java-12/pom.xml @@ -1,48 +1,48 @@ - 4.0.0 - com.baeldung - core-java-12 - 0.1.0-SNAPSHOT - core-java-12 - jar - http://maven.apache.org + 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 + core-java-12 + 0.1.0-SNAPSHOT + core-java-12 + jar + http://maven.apache.org - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - org.assertj - assertj-core - ${assertj.version} - test - - + + + org.assertj + assertj-core + ${assertj.version} + test + + - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source.version} - ${maven.compiler.target.version} - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + - - 12 - 12 - 3.6.1 - + + 12 + 12 + 3.6.1 + \ No newline at end of file diff --git a/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java b/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java index 68915b504d..7c4cb9e8f0 100644 --- a/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java +++ b/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java @@ -16,62 +16,56 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class CollectorsUnitTest { - @Test - public void whenTeeing_ItShouldCombineTheResultsAsExpected() { - List numbers = Arrays.asList(42, 4, 2, 24); - Range range = numbers.stream() - .collect(teeing( - minBy(Integer::compareTo), - maxBy(Integer::compareTo), - (min, max) -> new Range(min.orElse(null), max.orElse(null)) - )); + @Test + public void whenTeeing_ItShouldCombineTheResultsAsExpected() { + List numbers = Arrays.asList(42, 4, 2, 24); + Range range = numbers.stream() + .collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (min, max) -> new Range(min.orElse(null), max.orElse(null)))); - assertThat(range).isEqualTo(new Range(2, 42)); - } + assertThat(range).isEqualTo(new Range(2, 42)); + } - /** - * Represents a closed range of numbers between {@link #min} and - * {@link #max}, both inclusive. - */ - private static class Range { + /** + * Represents a closed range of numbers between {@link #min} and + * {@link #max}, both inclusive. + */ + private static class Range { - private final Integer min; + private final Integer min; - private final Integer max; + private final Integer max; - Range(Integer min, Integer max) { - this.min = min; - this.max = max; - } + Range(Integer min, Integer max) { + this.min = min; + this.max = max; + } - Integer getMin() { - return min; - } + Integer getMin() { + return min; + } - Integer getMax() { - return max; - } + Integer getMax() { + return max; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Range range = (Range) o; - return Objects.equals(getMin(), range.getMin()) && - Objects.equals(getMax(), range.getMax()); - } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Range range = (Range) o; + return Objects.equals(getMin(), range.getMin()) && Objects.equals(getMax(), range.getMax()); + } - @Override - public int hashCode() { - return Objects.hash(getMin(), getMax()); - } + @Override + public int hashCode() { + return Objects.hash(getMin(), getMax()); + } - @Override - public String toString() { - return "Range{" + - "min=" + min + - ", max=" + max + - '}'; - } - } + @Override + public String toString() { + return "Range{" + "min=" + min + ", max=" + max + '}'; + } + } } From 4372c6fa1cc44ab74053d532d599903a6786ae31 Mon Sep 17 00:00:00 2001 From: Sam Millington Date: Sat, 23 Mar 2019 11:51:30 +0000 Subject: [PATCH 51/54] [BAEL-2653] Added kotlin immutable collections code (#6563) * Added kotlin immutable collections code * corrected wrong junit version --- kotlin-libraries/pom.xml | 29 ++++++++ .../immutable/KotlinxImmutablesUnitTest.kt | 27 +++++++ .../kotlin/immutable/ReadOnlyUnitTest.kt | 73 +++++++++++++++++++ 3 files changed, 129 insertions(+) create mode 100644 kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt create mode 100644 kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index 507e5820d4..e3f69b4ea9 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -19,6 +19,14 @@ exposed https://dl.bintray.com/kotlin/exposed + + + false + + kotlinx + bintray + https://dl.bintray.com/kotlin/kotlinx + @@ -112,9 +120,30 @@ 3.3.0 pom + + + + junit + junit + ${junit.version} + test + + + + com.google.guava + guava + 27.1-jre + + + + org.jetbrains.kotlinx + kotlinx-collections-immutable + 0.1 + + 4.12 1.5.0 4.1.0 3.0.4 diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt new file mode 100644 index 0000000000..971f2de4c2 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt @@ -0,0 +1,27 @@ +package com.baeldung.kotlin.immutable + +import junit.framework.Assert.assertEquals +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.immutableListOf +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException + +class KotlinxImmutablesUnitTest{ + + + @Rule + @JvmField + var ee : ExpectedException = ExpectedException.none() + + @Test + fun givenKICLList_whenAddTried_checkExceptionThrown(){ + + val list: ImmutableList = immutableListOf("I", "am", "immutable") + + list.add("My new item") + + assertEquals(listOf("I", "am", "immutable"), list) + + } +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt new file mode 100644 index 0000000000..62c4a4eb88 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt @@ -0,0 +1,73 @@ +package com.baeldung.kotlin.immutable + +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableSet +import junit.framework.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException + +class ReadOnlyUnitTest{ + + @Test + fun givenReadOnlyList_whenCastToMutableList_checkNewElementsAdded(){ + + val list: List = listOf("This", "Is", "Totally", "Immutable") + + (list as MutableList)[2] = "Not" + + assertEquals(listOf("This", "Is", "Not", "Immutable"), list) + + } + + @Rule + @JvmField + var ee : ExpectedException = ExpectedException.none() + + @Test + fun givenImmutableList_whenAddTried_checkExceptionThrown(){ + + val list: List = ImmutableList.of("I", "am", "actually", "immutable") + + ee.expect(UnsupportedOperationException::class.java) + + (list as MutableList).add("Oops") + + } + + @Test + fun givenMutableList_whenCopiedAndAddTried_checkExceptionThrown(){ + + val mutableList : List = listOf("I", "Am", "Definitely", "Immutable") + + (mutableList as MutableList)[2] = "100% Not" + + assertEquals(listOf("I", "Am", "100% Not", "Immutable"), mutableList) + + val list: List = ImmutableList.copyOf(mutableList) + + ee.expect(UnsupportedOperationException::class.java) + + (list as MutableList)[2] = "Really?" + + } + + @Test + fun givenImmutableSetBuilder_whenAddTried_checkExceptionThrown(){ + + val mutableList : List = listOf("Hello", "Baeldung") + val set: ImmutableSet = ImmutableSet.builder() + .add("I","am","immutable") + .addAll(mutableList) + .build() + + assertEquals(setOf("Hello", "Baeldung", "I", "am", "immutable"), set) + + ee.expect(UnsupportedOperationException::class.java) + + (set as MutableSet).add("Oops") + + } + + +} \ No newline at end of file From c03044e3efb56879dbd4266ef30a122a71ffa9f0 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Sat, 23 Mar 2019 07:45:04 -0500 Subject: [PATCH 52/54] BAEL-2724_Closures_in_groovy (#6439) * BAEL-2724_Closures_in_groovy * BAEL-2724_Closures_in_groovy * BAEL-2724_Closures_in_groovy * BAEL-2724_Closures_in_groovy * BAEL-2724_Closures_in_groovy * BAEL-2724_Closures_in_groovy * BAEL-2724_Closures_in_groovy * BAEL-2724_Closures_in_groovy * BAEL-2724_Closures_in_groovy --- .../com/baeldung/closures/Closures.groovy | 87 +++++++++++++++++++ .../com/baeldung/closures/Employee.groovy | 6 ++ .../baeldung/closures/ClosuresUnitTest.groovy | 80 +++++++++++++++++ 3 files changed, 173 insertions(+) create mode 100644 core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy create mode 100644 core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy create mode 100644 core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy diff --git a/core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy b/core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy new file mode 100644 index 0000000000..607329ce88 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy @@ -0,0 +1,87 @@ +package com.baeldung.closures + +class Closures { + + def printWelcome = { + println "Welcome to Closures!" + } + + def print = { name -> + println name + } + + def formatToLowerCase(name) { + return name.toLowerCase() + } + def formatToLowerCaseClosure = { name -> + return name.toLowerCase() + } + + def count=0 + + def increaseCount = { + count++ + } + + def greet = { + return "Hello! ${it}" + } + + def multiply = { x, y -> + return x*y + } + + def calculate = {int x, int y, String operation -> + + //log closure + def log = { + println "Performing $it" + } + + def result = 0 + switch(operation) { + case "ADD": + log("Addition") + result = x+y + break + case "SUB": + log("Subtraction") + result = x-y + break + case "MUL": + log("Multiplication") + result = x*y + break + case "DIV": + log("Division") + result = x/y + break + } + return result + } + + def addAll = { int... args -> + return args.sum() + } + + def volume(Closure areaCalculator, int... dimensions) { + if(dimensions.size() == 3) { + + //consider dimension[0] = length, dimension[1] = breadth, dimension[2] = height + //for cube and cuboid + return areaCalculator(dimensions[0], dimensions[1]) * dimensions[2] + } else if(dimensions.size() == 2) { + + //consider dimension[0] = radius, dimension[1] = height + //for cylinder and cone + return areaCalculator(dimensions[0]) * dimensions[1] + } else if(dimensions.size() == 1) { + + //consider dimension[0] = radius + //for sphere + return areaCalculator(dimensions[0]) * dimensions[0] + } + + } + +} \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy b/core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy new file mode 100644 index 0000000000..78eb5aadeb --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy @@ -0,0 +1,6 @@ +package com.baeldung.closures + +class Employee { + + String fullName +} \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy new file mode 100644 index 0000000000..32c67e99bc --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy @@ -0,0 +1,80 @@ +package com.baeldung.closures + +import spock.lang.Specification + +class ClosuresUnitTest extends GroovyTestCase { + + Closures closures = new Closures() + + void testDeclaration() { + + closures.print("Hello! Closure") + closures.formatToLowerCaseClosure("Hello! Closure") + + closures.print.call("Hello! Closure") + closures.formatToLowerCaseClosure.call("Hello! Closure") + + } + + void testClosureVsMethods() { + assert closures.formatToLowerCase("TONY STARK") == closures.formatToLowerCaseClosure("Tony STark") + } + + void testParameters() { + //implicit parameter + assert closures.greet("Alex") == "Hello! Alex" + + //multiple parameters + assert closures.multiply(2, 4) == 8 + + assert closures.calculate(12, 4, "ADD") == 16 + assert closures.calculate(12, 4, "SUB") == 8 + assert closures.calculate(43, 8, "DIV") == 5.375 + + //varags + assert closures.addAll(12, 10, 14) == 36 + + } + + void testClosureAsAnArgument() { + assert closures.volume({ l, b -> return l*b }, 12, 6, 10) == 720 + + assert closures.volume({ radius -> return Math.PI*radius*radius/3 }, 5, 10) == Math.PI * 250/3 + } + + void testGStringsLazyEvaluation() { + def name = "Samwell" + def welcomeMsg = "Welcome! $name" + + assert welcomeMsg == "Welcome! Samwell" + + // changing the name does not affect original interpolated value + name = "Tarly" + assert welcomeMsg != "Welcome! Tarly" + + def fullName = "Tarly Samson" + def greetStr = "Hello! ${-> fullName}" + + assert greetStr == "Hello! Tarly Samson" + + // this time changing the variable affects the interpolated String's value + fullName = "Jon Smith" + assert greetStr == "Hello! Jon Smith" + } + + void testClosureInLists() { + def list = [10, 11, 12, 13, 14, true, false, "BUNTHER"] + list.each { + println it + } + + assert [13, 14] == list.findAll{ it instanceof Integer && it >= 13} + } + + void testClosureInMaps() { + def map = [1:10, 2:30, 4:5] + + assert [10, 60, 20] == map.collect{it.key * it.value} + } + +} \ No newline at end of file From 7bb1a28235e1c81538e1526823233b31f7eb1615 Mon Sep 17 00:00:00 2001 From: "anilkivilcim.eray" Date: Sat, 23 Mar 2019 22:07:24 +0300 Subject: [PATCH 53/54] BAEL-2762 formating done for 2 space indenting --- .../config/BasicAuthConfiguration.java | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) 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 6d769017bd..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 @@ -14,27 +14,25 @@ public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - PasswordEncoder encoder = - PasswordEncoderFactories.createDelegatingPasswordEncoder(); - - auth - .inMemoryAuthentication() - .withUser("user") - .password(encoder.encode("password")) - .roles("USER") - .and() - .withUser("admin") - .password(encoder.encode("admin")) - .roles("USER", "ADMIN"); + PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); + auth + .inMemoryAuthentication() + .withUser("user") + .password(encoder.encode("password")) + .roles("USER") + .and() + .withUser("admin") + .password(encoder.encode("admin")) + .roles("USER", "ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http - .authorizeRequests() - .anyRequest() - .authenticated() - .and() - .httpBasic(); + .authorizeRequests() + .anyRequest() + .authenticated() + .and() + .httpBasic(); } } From 8a2e671a11a6f704ae3dc95834bbd85a44b1b411 Mon Sep 17 00:00:00 2001 From: "sumit.sg34" Date: Sun, 24 Mar 2019 09:14:39 +0530 Subject: [PATCH 54/54] Fixed test case names --- .../repository/FruitRepositoryIntegrationTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java index 74188497ee..866cf1157b 100644 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java @@ -25,7 +25,7 @@ class FruitRepositoryIntegrationTest { @Transactional @Test @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenDeletedByColor_DeletedFruitShouldReturn() { + public void givenFruits_WhenDeletedByColor_ThenDeletedFruitsShouldReturn() { List fruits = fruitRepository.deleteByColor("green"); @@ -36,7 +36,7 @@ class FruitRepositoryIntegrationTest { @Transactional @Test @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenDeletedByName_DeletedFruitCountShouldReturn() { + public void givenFruits_WhenDeletedByName_ThenDeletedFruitCountShouldReturn() { Long deletedFruitCount = fruitRepository.deleteByName("apple"); @@ -46,7 +46,7 @@ class FruitRepositoryIntegrationTest { @Transactional @Test @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenRemovedByColor_DeletedFruitShouldReturn() { + public void givenFruits_WhenRemovedByColor_ThenDeletedFruitsShouldReturn() { List fruits = fruitRepository.removeByColor("green"); @@ -57,7 +57,7 @@ class FruitRepositoryIntegrationTest { @Transactional @Test @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenRemovedByName_DeletedFruitCountShouldReturn() { + public void givenFruits_WhenRemovedByName_ThenDeletedFruitCountShouldReturn() { Long deletedFruitCount = fruitRepository.removeByName("apple"); @@ -67,7 +67,7 @@ class FruitRepositoryIntegrationTest { @Transactional @Test @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenDeletedByColorOrName_DeletedFruitShouldReturn() { + public void givenFruits_WhenDeletedByColorOrName_ThenDeletedFruitsShouldReturn() { List fruits = fruitRepository.deleteFruits("apple", "green");