From 6fb230546db624ebf906486d32fe5117691cacef Mon Sep 17 00:00:00 2001 From: Sunil Gulabani Date: Mon, 1 Aug 2016 16:44:57 +0530 Subject: [PATCH 01/31] Integration Testing with Spring MVC. --- pom.xml | 1 + spring-mvc-test/README | 5 + spring-mvc-test/pom.xml | 193 ++++++++++++++++++ .../baeldung/spring/ApplicationConfig.java | 36 ++++ .../com/baeldung/spring/bean/Greeting.java | 19 ++ .../spring/controller/GreetController.java | 64 ++++++ .../src/main/resources/logback.xml | 18 ++ .../src/main/webapp/WEB-INF/jsp/index.jsp | 5 + .../main/webapp/WEB-INF/spring-servlet.xml | 5 + .../src/main/webapp/WEB-INF/web.xml | 34 +++ .../GreetControllerIntegrationTest.java | 114 +++++++++++ .../controller/GreetControllerTest.java | 83 ++++++++ 12 files changed, 577 insertions(+) create mode 100644 spring-mvc-test/README create mode 100644 spring-mvc-test/pom.xml create mode 100644 spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java create mode 100644 spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java create mode 100644 spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java create mode 100644 spring-mvc-test/src/main/resources/logback.xml create mode 100644 spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp create mode 100644 spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml create mode 100644 spring-mvc-test/src/main/webapp/WEB-INF/web.xml create mode 100644 spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java create mode 100644 spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java diff --git a/pom.xml b/pom.xml index 62d3d03633..c32ee82ce1 100644 --- a/pom.xml +++ b/pom.xml @@ -107,6 +107,7 @@ mutation-testing spring-mvc-velocity xstream + spring-mvc-test diff --git a/spring-mvc-test/README b/spring-mvc-test/README new file mode 100644 index 0000000000..9f4a0a60d4 --- /dev/null +++ b/spring-mvc-test/README @@ -0,0 +1,5 @@ +To compile and run the project, execute following command: + + mvn clean install org.codehaus.cargo:cargo-maven2-plugin:run + +URL: http://localhost:8080/spring-mvc-test/ diff --git a/spring-mvc-test/pom.xml b/spring-mvc-test/pom.xml new file mode 100644 index 0000000000..3c4875f087 --- /dev/null +++ b/spring-mvc-test/pom.xml @@ -0,0 +1,193 @@ + + 4.0.0 + com.baeldung + spring-mvc-test + 0.1-SNAPSHOT + spring-mvc-test + war + + + + 4.3.1.RELEASE + + 1.7.21 + 1.1.7 + + 3.4 + + 1.3 + 4.12 + 1.10.19 + 4.4.5 + 4.5.2 + + + 3.5.1 + 2.6 + 2.19.1 + 2.19.1 + 3.0.1 + + + 1.5.0 + + + + + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + org.springframework + spring-websocket + ${org.springframework.version} + + + + com.fasterxml.jackson.core + jackson-core + 2.7.3 + + + com.fasterxml.jackson.core + jackson-databind + 2.7.3 + + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + javax.servlet + jstl + 1.2 + runtime + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + org.slf4j + slf4j-log4j12 + ${org.slf4j.version} + + + + junit + junit + ${junit.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.jayway.jsonpath + json-path + 2.2.0 + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + + spring-mvc-test + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + maven-resources-plugin + 2.7 + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + + **/*IntegrationTest.java + + + + + + integration-test + verify + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + + jetty8x + embedded + + + + 8080 + + + + + + + \ No newline at end of file diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java b/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java new file mode 100644 index 0000000000..1a5b590854 --- /dev/null +++ b/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java @@ -0,0 +1,36 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = {"com.baeldung.spring.controller"}) +public class ApplicationConfig extends WebMvcConfigurerAdapter { + + public ApplicationConfig() { + super(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("index"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/jsp/"); + bean.setSuffix(".jsp"); + return bean; + } +} \ No newline at end of file diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java b/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java new file mode 100644 index 0000000000..d7ddaf2fd1 --- /dev/null +++ b/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.bean; + +public class Greeting { + private int id; + private String message; + + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } +} diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java b/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java new file mode 100644 index 0000000000..0f62df2a71 --- /dev/null +++ b/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java @@ -0,0 +1,64 @@ +package com.baeldung.spring.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.spring.bean.Greeting; + +@Controller +public class GreetController { + + @RequestMapping(value = "/homePage", method = RequestMethod.GET) + public String index() { + return "index"; + } + + @RequestMapping(value = "/greet", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greet() { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPathVariable/{name}", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greetWithPathVariable(@PathVariable("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithQueryVariable", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greetWithQueryVariable(@RequestParam("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPost", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public Greeting greetWithPost() { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPostAndFormData", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public Greeting greetWithPostAndFormData(@RequestParam("id") int id, @RequestParam("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(id); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } +} \ No newline at end of file diff --git a/spring-mvc-test/src/main/resources/logback.xml b/spring-mvc-test/src/main/resources/logback.xml new file mode 100644 index 0000000000..166c369905 --- /dev/null +++ b/spring-mvc-test/src/main/resources/logback.xml @@ -0,0 +1,18 @@ + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..89c7ca6c81 --- /dev/null +++ b/spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,5 @@ + + +

Spring MVC - Integration Testing

+ + \ No newline at end of file diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml b/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml new file mode 100644 index 0000000000..40718ab3a4 --- /dev/null +++ b/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml @@ -0,0 +1,5 @@ + + + \ No newline at end of file diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/web.xml b/spring-mvc-test/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..8cf7a9a37b --- /dev/null +++ b/spring-mvc-test/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,34 @@ + + + + Spring MVC - Integration Testing + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + com.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + + spring + org.springframework.web.servlet.DispatcherServlet + 1 + + + + spring + / + + \ No newline at end of file diff --git a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java new file mode 100644 index 0000000000..d7d697dda9 --- /dev/null +++ b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java @@ -0,0 +1,114 @@ +package com.baeldung.spring.controller; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockServletContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.spring.ApplicationConfig; + +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import javax.servlet.ServletContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { ApplicationConfig.class }) +public class GreetControllerIntegrationTest { + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() throws Exception { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) +// .alwaysExpect(MockMvcResultMatchers.status().isOk()) + .build(); + } + + @Test + public void verifyWac() { + ServletContext servletContext = wac.getServletContext(); + Assert.assertNotNull(servletContext); + Assert.assertTrue(servletContext instanceof MockServletContext); + Assert.assertNotNull(wac.getBean("greetController")); + } + + @Test + public void verifyIndexJspViewName() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.get("/homePage")) + .andDo(print()) + .andExpect(MockMvcResultMatchers.view().name("index")); + } + + @Test + public void verifyGreet() throws Exception { + MvcResult mvcResult = this.mockMvc + .perform(MockMvcRequestBuilders.get("/greet")) + .andDo(print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")) + .andReturn(); + Assert.assertEquals("application/json;charset=UTF-8", mvcResult.getResponse().getContentType()); + } + + @Test + public void verifyGreetWithPathVariable() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John!!!")); + } + + @Test + public void verifyGreetWithPathVariable_2() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.get("/greetWithPathVariable/{name}", "Doe")) + .andDo(print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World Doe!!!")); + } + + @Test + public void verifyGreetWithQueryVariable() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")) + .andDo(print()) + .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + } + + @Test + public void verifyGreetWithPost() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.post("/greetWithPost")) + .andDo(print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void verifyGreetWithPostAndFormData() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")) + .andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + } +} \ No newline at end of file diff --git a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java new file mode 100644 index 0000000000..155b6b4a50 --- /dev/null +++ b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java @@ -0,0 +1,83 @@ +package com.baeldung.spring.controller; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +public class GreetControllerTest { + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new GreetController()).build(); + } + + @Test + public void verifyIndexJspViewName() throws Exception { + this.mockMvc.perform(get("/homePage")) + .andExpect(view().name("index")); + } + + @Test + public void verifyGreet() throws Exception { + this.mockMvc.perform(get("/greet")) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json;charset=UTF-8")) + .andExpect(jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void verifyGreetWithPathVariable() throws Exception { + this.mockMvc.perform(get("/greetWithPathVariable/John")) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json;charset=UTF-8")) + .andExpect(jsonPath("$.message").value("Hello World John!!!")); + } + + @Test + public void verifyGreetWithPathVariable_2() throws Exception { + this.mockMvc.perform(get("/greetWithPathVariable/{name}","Doe")) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json;charset=UTF-8")) + .andExpect(jsonPath("$.message").value("Hello World Doe!!!")); + } + + @Test + public void verifyGreetWithQueryVariable() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")) + .andDo(print()) + .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + } + + @Test + public void verifyGreetWithPost() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.post("/greetWithPost")) + .andDo(print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void verifyGreetWithPostAndFormData() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")) + .andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + } +} From 4f9d9502e24481d254781cd4336c3f1aeb371606 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Tue, 2 Aug 2016 06:33:49 +0200 Subject: [PATCH 02/31] BAEL-175 - Integrtion testing minor changes --- .../baeldung/spring/ApplicationConfig.java | 12 +- .../com/baeldung/spring/bean/Greeting.java | 33 ++--- .../spring/controller/GreetController.java | 98 +++++++------- .../controller/GreetControllerTest.java | 126 +++++++++--------- 4 files changed, 136 insertions(+), 133 deletions(-) diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java b/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java index 1a5b590854..c437dd568a 100644 --- a/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java +++ b/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java @@ -15,11 +15,11 @@ import org.springframework.web.servlet.view.JstlView; @ComponentScan(basePackages = {"com.baeldung.spring.controller"}) public class ApplicationConfig extends WebMvcConfigurerAdapter { - public ApplicationConfig() { - super(); - } - - @Override + public ApplicationConfig() { + super(); + } + + @Override public void addViewControllers(final ViewControllerRegistry registry) { super.addViewControllers(registry); registry.addViewController("/").setViewName("index"); @@ -27,7 +27,7 @@ public class ApplicationConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/jsp/"); bean.setSuffix(".jsp"); diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java b/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java index d7ddaf2fd1..11c0a79b0e 100644 --- a/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java +++ b/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java @@ -1,19 +1,22 @@ package com.baeldung.spring.bean; public class Greeting { - private int id; - private String message; - - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } + private int id; + private String message; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } } diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java b/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java index 0f62df2a71..d563f80918 100644 --- a/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java +++ b/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java @@ -11,54 +11,54 @@ import com.baeldung.spring.bean.Greeting; @Controller public class GreetController { - - @RequestMapping(value = "/homePage", method = RequestMethod.GET) - public String index() { - return "index"; - } - - @RequestMapping(value = "/greet", method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public Greeting greet() { - Greeting greeting = new Greeting(); - greeting.setId(1); - greeting.setMessage("Hello World!!!"); - return greeting; - } - - @RequestMapping(value = "/greetWithPathVariable/{name}", method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public Greeting greetWithPathVariable(@PathVariable("name") String name) { - Greeting greeting = new Greeting(); - greeting.setId(1); - greeting.setMessage("Hello World " + name + "!!!"); - return greeting; - } - - @RequestMapping(value = "/greetWithQueryVariable", method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public Greeting greetWithQueryVariable(@RequestParam("name") String name) { - Greeting greeting = new Greeting(); - greeting.setId(1); - greeting.setMessage("Hello World " + name + "!!!"); - return greeting; - } - - @RequestMapping(value = "/greetWithPost", method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public Greeting greetWithPost() { - Greeting greeting = new Greeting(); - greeting.setId(1); - greeting.setMessage("Hello World!!!"); - return greeting; - } - @RequestMapping(value = "/greetWithPostAndFormData", method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public Greeting greetWithPostAndFormData(@RequestParam("id") int id, @RequestParam("name") String name) { - Greeting greeting = new Greeting(); - greeting.setId(id); - greeting.setMessage("Hello World " + name + "!!!"); - return greeting; - } + @RequestMapping(value = "/homePage", method = RequestMethod.GET) + public String index() { + return "index"; + } + + @RequestMapping(value = "/greet", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greet() { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPathVariable/{name}", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greetWithPathVariable(@PathVariable("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithQueryVariable", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greetWithQueryVariable(@RequestParam("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPost", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public Greeting greetWithPost() { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPostAndFormData", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public Greeting greetWithPostAndFormData(@RequestParam("id") int id, @RequestParam("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(id); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } } \ No newline at end of file diff --git a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java index 155b6b4a50..b53aba75c0 100644 --- a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java +++ b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java @@ -15,69 +15,69 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; public class GreetControllerTest { - - private MockMvc mockMvc; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.standaloneSetup(new GreetController()).build(); - } - - @Test - public void verifyIndexJspViewName() throws Exception { - this.mockMvc.perform(get("/homePage")) - .andExpect(view().name("index")); - } - - @Test - public void verifyGreet() throws Exception { - this.mockMvc.perform(get("/greet")) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json;charset=UTF-8")) - .andExpect(jsonPath("$.message").value("Hello World!!!")); - } - - @Test - public void verifyGreetWithPathVariable() throws Exception { - this.mockMvc.perform(get("/greetWithPathVariable/John")) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json;charset=UTF-8")) - .andExpect(jsonPath("$.message").value("Hello World John!!!")); - } - - @Test - public void verifyGreetWithPathVariable_2() throws Exception { - this.mockMvc.perform(get("/greetWithPathVariable/{name}","Doe")) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json;charset=UTF-8")) - .andExpect(jsonPath("$.message").value("Hello World Doe!!!")); - } - - @Test - public void verifyGreetWithQueryVariable() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")) - .andDo(print()) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); - } - @Test - public void verifyGreetWithPost() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.post("/greetWithPost")) - .andDo(print()) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); - } + private MockMvc mockMvc; - @Test - public void verifyGreetWithPostAndFormData() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")) - .andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); - } + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new GreetController()).build(); + } + + @Test + public void verifyIndexJspViewName() throws Exception { + this.mockMvc.perform(get("/homePage")) + .andExpect(view().name("index")); + } + + @Test + public void verifyGreet() throws Exception { + this.mockMvc.perform(get("/greet")) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json;charset=UTF-8")) + .andExpect(jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void verifyGreetWithPathVariable() throws Exception { + this.mockMvc.perform(get("/greetWithPathVariable/John")) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json;charset=UTF-8")) + .andExpect(jsonPath("$.message").value("Hello World John!!!")); + } + + @Test + public void verifyGreetWithPathVariable_2() throws Exception { + this.mockMvc.perform(get("/greetWithPathVariable/{name}", "Doe")) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json;charset=UTF-8")) + .andExpect(jsonPath("$.message").value("Hello World Doe!!!")); + } + + @Test + public void verifyGreetWithQueryVariable() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")) + .andDo(print()) + .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + } + + @Test + public void verifyGreetWithPost() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.post("/greetWithPost")) + .andDo(print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void verifyGreetWithPostAndFormData() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")) + .andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + } } From c996f8ccd5d45f5e6e1292ac9b08ba6f7f39eff5 Mon Sep 17 00:00:00 2001 From: Sunil Gulabani Date: Wed, 3 Aug 2016 15:04:36 +0530 Subject: [PATCH 03/31] Updated formatting. --- .../baeldung/spring/ApplicationConfig.java | 14 +- .../com/baeldung/spring/bean/Greeting.java | 33 ++--- .../spring/controller/GreetController.java | 98 +++++++------- .../src/main/webapp/WEB-INF/jsp/index.jsp | 6 +- .../main/webapp/WEB-INF/spring-servlet.xml | 2 +- .../src/main/webapp/WEB-INF/web.xml | 53 ++++---- .../GreetControllerIntegrationTest.java | 121 +++++++----------- .../controller/GreetControllerTest.java | 106 +++++++-------- 8 files changed, 195 insertions(+), 238 deletions(-) diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java b/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java index 1a5b590854..09be5ee113 100644 --- a/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java +++ b/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java @@ -12,14 +12,14 @@ import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -@ComponentScan(basePackages = {"com.baeldung.spring.controller"}) +@ComponentScan(basePackages = { "com.baeldung.spring.controller" }) public class ApplicationConfig extends WebMvcConfigurerAdapter { - public ApplicationConfig() { - super(); - } - - @Override + public ApplicationConfig() { + super(); + } + + @Override public void addViewControllers(final ViewControllerRegistry registry) { super.addViewControllers(registry); registry.addViewController("/").setViewName("index"); @@ -27,7 +27,7 @@ public class ApplicationConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/jsp/"); bean.setSuffix(".jsp"); diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java b/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java index d7ddaf2fd1..11c0a79b0e 100644 --- a/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java +++ b/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java @@ -1,19 +1,22 @@ package com.baeldung.spring.bean; public class Greeting { - private int id; - private String message; - - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } + private int id; + private String message; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } } diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java b/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java index 0f62df2a71..d563f80918 100644 --- a/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java +++ b/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java @@ -11,54 +11,54 @@ import com.baeldung.spring.bean.Greeting; @Controller public class GreetController { - - @RequestMapping(value = "/homePage", method = RequestMethod.GET) - public String index() { - return "index"; - } - - @RequestMapping(value = "/greet", method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public Greeting greet() { - Greeting greeting = new Greeting(); - greeting.setId(1); - greeting.setMessage("Hello World!!!"); - return greeting; - } - - @RequestMapping(value = "/greetWithPathVariable/{name}", method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public Greeting greetWithPathVariable(@PathVariable("name") String name) { - Greeting greeting = new Greeting(); - greeting.setId(1); - greeting.setMessage("Hello World " + name + "!!!"); - return greeting; - } - - @RequestMapping(value = "/greetWithQueryVariable", method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public Greeting greetWithQueryVariable(@RequestParam("name") String name) { - Greeting greeting = new Greeting(); - greeting.setId(1); - greeting.setMessage("Hello World " + name + "!!!"); - return greeting; - } - - @RequestMapping(value = "/greetWithPost", method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public Greeting greetWithPost() { - Greeting greeting = new Greeting(); - greeting.setId(1); - greeting.setMessage("Hello World!!!"); - return greeting; - } - @RequestMapping(value = "/greetWithPostAndFormData", method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public Greeting greetWithPostAndFormData(@RequestParam("id") int id, @RequestParam("name") String name) { - Greeting greeting = new Greeting(); - greeting.setId(id); - greeting.setMessage("Hello World " + name + "!!!"); - return greeting; - } + @RequestMapping(value = "/homePage", method = RequestMethod.GET) + public String index() { + return "index"; + } + + @RequestMapping(value = "/greet", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greet() { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPathVariable/{name}", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greetWithPathVariable(@PathVariable("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithQueryVariable", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greetWithQueryVariable(@RequestParam("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPost", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public Greeting greetWithPost() { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPostAndFormData", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public Greeting greetWithPostAndFormData(@RequestParam("id") int id, @RequestParam("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(id); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } } \ No newline at end of file diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp index 89c7ca6c81..2cf02bc2d8 100644 --- a/spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp +++ b/spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp @@ -1,5 +1,5 @@ - -

Spring MVC - Integration Testing

- + +

Spring MVC - Integration Testing

+ \ No newline at end of file diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml b/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml index 40718ab3a4..2b8192e742 100644 --- a/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml +++ b/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"> \ No newline at end of file diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/web.xml b/spring-mvc-test/src/main/webapp/WEB-INF/web.xml index 8cf7a9a37b..dc0233a7fc 100644 --- a/spring-mvc-test/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-test/src/main/webapp/WEB-INF/web.xml @@ -1,34 +1,33 @@ - + - Spring MVC - Integration Testing + Spring MVC - Integration Testing - - contextClass - + + contextClass + org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - contextConfigLocation - com.baeldung.spring - - - - org.springframework.web.context.ContextLoaderListener - + + + contextConfigLocation + com.baeldung.spring + - - spring - org.springframework.web.servlet.DispatcherServlet - 1 - - - - spring - / - + + org.springframework.web.context.ContextLoaderListener + + + + spring + org.springframework.web.servlet.DispatcherServlet + 1 + + + + spring + / + \ No newline at end of file diff --git a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java index d7d697dda9..368ef6ec91 100644 --- a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java +++ b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java @@ -28,87 +28,62 @@ import javax.servlet.ServletContext; @ContextConfiguration(classes = { ApplicationConfig.class }) public class GreetControllerIntegrationTest { - @Autowired - private WebApplicationContext wac; + @Autowired + private WebApplicationContext wac; - private MockMvc mockMvc; + private MockMvc mockMvc; - @Before - public void setup() throws Exception { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) -// .alwaysExpect(MockMvcResultMatchers.status().isOk()) - .build(); - } + @Before + public void setup() throws Exception { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } - @Test - public void verifyWac() { - ServletContext servletContext = wac.getServletContext(); - Assert.assertNotNull(servletContext); - Assert.assertTrue(servletContext instanceof MockServletContext); - Assert.assertNotNull(wac.getBean("greetController")); - } + @Test + public void verifyWac() { + ServletContext servletContext = wac.getServletContext(); + Assert.assertNotNull(servletContext); + Assert.assertTrue(servletContext instanceof MockServletContext); + Assert.assertNotNull(wac.getBean("greetController")); + } - @Test - public void verifyIndexJspViewName() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.get("/homePage")) - .andDo(print()) - .andExpect(MockMvcResultMatchers.view().name("index")); - } + @Test + public void verifyIndexJspViewName() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/homePage")).andDo(print()).andExpect(MockMvcResultMatchers.view().name("index")); + } - @Test - public void verifyGreet() throws Exception { - MvcResult mvcResult = this.mockMvc - .perform(MockMvcRequestBuilders.get("/greet")) - .andDo(print()) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")) - .andReturn(); - Assert.assertEquals("application/json;charset=UTF-8", mvcResult.getResponse().getContentType()); - } + @Test + public void verifyGreet() throws Exception { + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/greet")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")).andReturn(); + Assert.assertEquals("application/json;charset=UTF-8", mvcResult.getResponse().getContentType()); + } - @Test - public void verifyGreetWithPathVariable() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John!!!")); - } + @Test + public void verifyGreetWithPathVariable() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John!!!")); + } - @Test - public void verifyGreetWithPathVariable_2() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.get("/greetWithPathVariable/{name}", "Doe")) - .andDo(print()) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World Doe!!!")); - } + @Test + public void verifyGreetWithPathVariable_2() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/{name}", "Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World Doe!!!")); + } - @Test - public void verifyGreetWithQueryVariable() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")) - .andDo(print()) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); - } + @Test + public void verifyGreetWithQueryVariable() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + } - @Test - public void verifyGreetWithPost() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.post("/greetWithPost")) - .andDo(print()) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); - } + @Test + public void verifyGreetWithPost() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); + } - @Test - public void verifyGreetWithPostAndFormData() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")) - .andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); - } + @Test + public void verifyGreetWithPostAndFormData() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + } } \ No newline at end of file diff --git a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java index 155b6b4a50..1631118981 100644 --- a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java +++ b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java @@ -15,69 +15,49 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; public class GreetControllerTest { - - private MockMvc mockMvc; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.standaloneSetup(new GreetController()).build(); - } - - @Test - public void verifyIndexJspViewName() throws Exception { - this.mockMvc.perform(get("/homePage")) - .andExpect(view().name("index")); - } - - @Test - public void verifyGreet() throws Exception { - this.mockMvc.perform(get("/greet")) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json;charset=UTF-8")) - .andExpect(jsonPath("$.message").value("Hello World!!!")); - } - - @Test - public void verifyGreetWithPathVariable() throws Exception { - this.mockMvc.perform(get("/greetWithPathVariable/John")) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json;charset=UTF-8")) - .andExpect(jsonPath("$.message").value("Hello World John!!!")); - } - - @Test - public void verifyGreetWithPathVariable_2() throws Exception { - this.mockMvc.perform(get("/greetWithPathVariable/{name}","Doe")) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json;charset=UTF-8")) - .andExpect(jsonPath("$.message").value("Hello World Doe!!!")); - } - - @Test - public void verifyGreetWithQueryVariable() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")) - .andDo(print()) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); - } - @Test - public void verifyGreetWithPost() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.post("/greetWithPost")) - .andDo(print()) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); - } + private MockMvc mockMvc; - @Test - public void verifyGreetWithPostAndFormData() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")) - .andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); - } + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new GreetController()).build(); + } + + @Test + public void verifyIndexJspViewName() throws Exception { + this.mockMvc.perform(get("/homePage")).andExpect(view().name("index")); + } + + @Test + public void verifyGreet() throws Exception { + this.mockMvc.perform(get("/greet")).andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")).andExpect(jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void verifyGreetWithPathVariable() throws Exception { + this.mockMvc.perform(get("/greetWithPathVariable/John")).andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")).andExpect(jsonPath("$.message").value("Hello World John!!!")); + } + + @Test + public void verifyGreetWithPathVariable_2() throws Exception { + this.mockMvc.perform(get("/greetWithPathVariable/{name}", "Doe")).andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")).andExpect(jsonPath("$.message").value("Hello World Doe!!!")); + } + + @Test + public void verifyGreetWithQueryVariable() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + } + + @Test + public void verifyGreetWithPost() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void verifyGreetWithPostAndFormData() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + } } From 414735b8c36fec2224a2da843ccbfc9beabf71eb Mon Sep 17 00:00:00 2001 From: k0l0ssus Date: Sat, 6 Aug 2016 00:30:19 -0400 Subject: [PATCH 04/31] EL 3.0 Page --- jsf/src/main/webapp/el3_intro.xhtml | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 jsf/src/main/webapp/el3_intro.xhtml diff --git a/jsf/src/main/webapp/el3_intro.xhtml b/jsf/src/main/webapp/el3_intro.xhtml new file mode 100644 index 0000000000..7a5d2ff7bf --- /dev/null +++ b/jsf/src/main/webapp/el3_intro.xhtml @@ -0,0 +1,35 @@ + + + + + Baeldung | Expression Language 3.0 + + + + +
+ + +
+ + +
+ + +
+ + +
+ + + + + + + + +
+ + From 34e75575137bfefedadee5d9d8f8b0a13751788e Mon Sep 17 00:00:00 2001 From: k0l0ssus Date: Sat, 6 Aug 2016 00:43:06 -0400 Subject: [PATCH 05/31] Backing bean code in support of EL 3.0 --- .../springintegration/controllers/ELSampleBean.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java index a13f0890b5..58dedb08b7 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java @@ -16,6 +16,7 @@ public class ELSampleBean { private String firstName; private String lastName; private String pageDescription = "This page demos JSF EL Basics"; + public static final String constantField = "THIS_IS_NOT_CHANGING_ANYTIME_SOON"; private int pageCounter; private Random randomIntGen = new Random(); @@ -27,11 +28,19 @@ public class ELSampleBean { public void save() { } + + public static String getConstantField() { + return constantField; + } public void saveFirstName(String firstName) { this.firstName = firstName; } + public String multiplyValue(LambdaExpression expr){ + String theResult = (String) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter); + return theResult; + } public void saveByELEvaluation() { firstName = (String) evaluateEL("#{firstName.value}", String.class); From e97cd1122fe54c5776bb3d9a59a97f91ea148bd6 Mon Sep 17 00:00:00 2001 From: k0l0ssus Date: Sat, 6 Aug 2016 00:45:22 -0400 Subject: [PATCH 06/31] Update el3_intro.xhtml --- jsf/src/main/webapp/el3_intro.xhtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jsf/src/main/webapp/el3_intro.xhtml b/jsf/src/main/webapp/el3_intro.xhtml index 7a5d2ff7bf..ebd3acad0a 100644 --- a/jsf/src/main/webapp/el3_intro.xhtml +++ b/jsf/src/main/webapp/el3_intro.xhtml @@ -23,7 +23,7 @@
- + From 709da6bcd28e55e71e010189847e662f37f963a5 Mon Sep 17 00:00:00 2001 From: Sunil Gulabani Date: Tue, 9 Aug 2016 10:14:59 +0530 Subject: [PATCH 07/31] Updated the test names and added Annotation Based Web Config. --- .../com/baeldung/web/WebAppInitializer.java | 33 +++++++++++++++++++ ...ing-servlet.xml => spring-servlet-old.xml} | 0 .../webapp/WEB-INF/{web.xml => web-old.xml} | 0 .../GreetControllerIntegrationTest.java | 16 ++++----- .../controller/GreetControllerTest.java | 14 ++++---- 5 files changed, 48 insertions(+), 15 deletions(-) create mode 100644 spring-mvc-test/src/main/java/com/baeldung/web/WebAppInitializer.java rename spring-mvc-test/src/main/webapp/WEB-INF/{spring-servlet.xml => spring-servlet-old.xml} (100%) rename spring-mvc-test/src/main/webapp/WEB-INF/{web.xml => web-old.xml} (100%) diff --git a/spring-mvc-test/src/main/java/com/baeldung/web/WebAppInitializer.java b/spring-mvc-test/src/main/java/com/baeldung/web/WebAppInitializer.java new file mode 100644 index 0000000000..23fad058d0 --- /dev/null +++ b/spring-mvc-test/src/main/java/com/baeldung/web/WebAppInitializer.java @@ -0,0 +1,33 @@ +package com.baeldung.web; + +import java.util.Set; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class WebAppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(final ServletContext sc) throws ServletException { + + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.scan("com.baeldung.spring"); + + sc.addListener(new ContextLoaderListener(root)); + + final ServletRegistration.Dynamic appServlet = sc.addServlet("spring", new DispatcherServlet(new GenericWebApplicationContext())); + appServlet.setLoadOnStartup(1); + + final Set mappingConflicts = appServlet.addMapping("/"); + if (!mappingConflicts.isEmpty()) { + throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); + } + } +} diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml b/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet-old.xml similarity index 100% rename from spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet.xml rename to spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet-old.xml diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/web.xml b/spring-mvc-test/src/main/webapp/WEB-INF/web-old.xml similarity index 100% rename from spring-mvc-test/src/main/webapp/WEB-INF/web.xml rename to spring-mvc-test/src/main/webapp/WEB-INF/web-old.xml diff --git a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java index 368ef6ec91..abed0a977e 100644 --- a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java +++ b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java @@ -39,7 +39,7 @@ public class GreetControllerIntegrationTest { } @Test - public void verifyWac() { + public void givenWAC_whenServletContext_thenItProvidesGreetController() { ServletContext servletContext = wac.getServletContext(); Assert.assertNotNull(servletContext); Assert.assertTrue(servletContext instanceof MockServletContext); @@ -47,42 +47,42 @@ public class GreetControllerIntegrationTest { } @Test - public void verifyIndexJspViewName() throws Exception { + public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/homePage")).andDo(print()).andExpect(MockMvcResultMatchers.view().name("index")); } @Test - public void verifyGreet() throws Exception { + public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception { MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/greet")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")).andReturn(); Assert.assertEquals("application/json;charset=UTF-8", mvcResult.getResponse().getContentType()); } @Test - public void verifyGreetWithPathVariable() throws Exception { + public void givenGreetURIWithPathVariable_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John!!!")); } @Test - public void verifyGreetWithPathVariable_2() throws Exception { + public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/{name}", "Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World Doe!!!")); } @Test - public void verifyGreetWithQueryVariable() throws Exception { + public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); } @Test - public void verifyGreetWithPost() throws Exception { + public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); } @Test - public void verifyGreetWithPostAndFormData() throws Exception { + public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); } diff --git a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java index 1631118981..8e624544cd 100644 --- a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java +++ b/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java @@ -24,39 +24,39 @@ public class GreetControllerTest { } @Test - public void verifyIndexJspViewName() throws Exception { + public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() throws Exception { this.mockMvc.perform(get("/homePage")).andExpect(view().name("index")); } @Test - public void verifyGreet() throws Exception { + public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(get("/greet")).andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")).andExpect(jsonPath("$.message").value("Hello World!!!")); } @Test - public void verifyGreetWithPathVariable() throws Exception { + public void givenGreetURIWithPathVariable_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(get("/greetWithPathVariable/John")).andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")).andExpect(jsonPath("$.message").value("Hello World John!!!")); } @Test - public void verifyGreetWithPathVariable_2() throws Exception { + public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(get("/greetWithPathVariable/{name}", "Doe")).andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")).andExpect(jsonPath("$.message").value("Hello World Doe!!!")); } @Test - public void verifyGreetWithQueryVariable() throws Exception { + public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); } @Test - public void verifyGreetWithPost() throws Exception { + public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); } @Test - public void verifyGreetWithPostAndFormData() throws Exception { + public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); } From a54265fff0679fdf860be9dadf5e1df01fa59fe6 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Thu, 11 Aug 2016 06:22:01 +0200 Subject: [PATCH 08/31] BAEL-197 - EL3 dependency added --- jsf/pom.xml | 4 ++-- .../baeldung/springintegration/controllers/ELSampleBean.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/jsf/pom.xml b/jsf/pom.xml index b80bcfb416..99ce38145c 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -27,7 +27,7 @@ javax.el - el-api + javax.el-api ${javax.el.version} @@ -127,7 +127,7 @@ 2.1.7 - 2.2 + 3.0.0 1.7.13 diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java index 58dedb08b7..035146ecf8 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java @@ -1,13 +1,13 @@ package com.baeldung.springintegration.controllers; -import java.util.Random; import javax.annotation.PostConstruct; +import javax.el.LambdaExpression; import javax.faces.application.Application; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; -import javax.faces.component.html.HtmlInputText; import javax.faces.context.FacesContext; +import java.util.Random; @ManagedBean(name = "ELBean") @ViewScoped From 24b753c0a617f7ba964d28efb7a1dd55120bd9c8 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Thu, 11 Aug 2016 06:31:58 +0200 Subject: [PATCH 09/31] BAEL-197 - JSF deps incremented --- jsf/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jsf/pom.xml b/jsf/pom.xml index 99ce38145c..6a4b358252 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -126,7 +126,7 @@ 4.2.5.RELEASE - 2.1.7 + 2.2.13 3.0.0 From e5c5b89755100c43991b2014c955c40a82a04088 Mon Sep 17 00:00:00 2001 From: PRITAM BANERJEE Date: Fri, 12 Aug 2016 00:06:19 -0700 Subject: [PATCH 10/31] Eager Loading vs Lazy Loading (#600) * BAEL-212 Contains: 1. Hibernate Criteria Query Classes 2. Hibernate Criteria Query Test * Updating the config file and the HibernateUtil class * Hibernate Criteria Queries Example * Hibernate Fetching : Eager Loading vs Lazy Loading * Hibernate Criteria Query files * Hibernate Eager Loading and Lazy Loading Changes --- .../fetching/util/HibernateUtil.java | 2 -- .../fetching/view/FetchingAppView.java | 2 -- .../src/main/resources/fetching.cfg.xml | 1 + .../src/main/resources/fetchingLazy.cfg.xml | 1 + .../criteria/HibernateCriteriaTestRunner.java | 15 ++++++++++++ .../criteria/HibernateCriteriaTestSuite.java | 11 +++++++++ .../fetching/HibernateFetchingTest.java | 24 +++++++++++++++++++ .../fetching/model/OrderDetail.hbm.xml | 0 .../hibernate/fetching/model/User.hbm.xml | 0 .../hibernate/fetching/model/UserLazy.hbm.xml | 0 .../src/test/resources/fetching.cfg.xml | 17 +++++++++++++ .../src/test/resources/fetchingLazy.cfg.xml | 17 +++++++++++++ 12 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java create mode 100644 spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java create mode 100644 spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java rename spring-hibernate4/src/{main/java => test/resources}/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml (100%) rename spring-hibernate4/src/{main/java => test/resources}/com/baeldung/hibernate/fetching/model/User.hbm.xml (100%) rename spring-hibernate4/src/{main/java => test/resources}/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml (100%) create mode 100644 spring-hibernate4/src/test/resources/fetching.cfg.xml create mode 100644 spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index c6b095dde2..be877fcaba 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -16,7 +16,6 @@ public class HibernateUtil { if ("lazy".equals(fetchMethod)) { sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); } else { - sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); } // fetching.cfg.xml is used for this example @@ -25,7 +24,6 @@ public class HibernateUtil { } public static Session getHibernateSession() { - System.out.println("Loading eager"); SessionFactory sf = null; sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); final Session session = sf.openSession(); diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java index 5e4ab32d03..729acde019 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -51,9 +51,7 @@ public class FetchingAppView { public void createTestData() { final Session session = HibernateUtil.getHibernateSession(); - Transaction tx = null; - tx = session.beginTransaction(); final User user1 = new User(); final User user2 = new User(); diff --git a/spring-hibernate4/src/main/resources/fetching.cfg.xml b/spring-hibernate4/src/main/resources/fetching.cfg.xml index 1595c829cd..4a7e574dda 100644 --- a/spring-hibernate4/src/main/resources/fetching.cfg.xml +++ b/spring-hibernate4/src/main/resources/fetching.cfg.xml @@ -10,6 +10,7 @@ root iamtheking org.hibernate.dialect.MySQLDialect + true diff --git a/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml index 4c64b4deb6..1f9a7df94e 100644 --- a/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml +++ b/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml @@ -10,6 +10,7 @@ root iamtheking org.hibernate.dialect.MySQLDialect + true diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java new file mode 100644 index 0000000000..8341df9fcb --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java @@ -0,0 +1,15 @@ +package com.baeldung.hibernate.criteria; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +public class HibernateCriteriaTestRunner { + + public static void main(final String[] args) { + Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); + for (Failure failure : result.getFailures()) { + + } + } +} diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java new file mode 100644 index 0000000000..ab27a6ba82 --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java @@ -0,0 +1,11 @@ +package com.baeldung.hibernate.criteria; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ HibernateCriteriaTest.class }) + +public class HibernateCriteriaTestSuite { + +} diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java new file mode 100644 index 0000000000..94ee8a3c79 --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -0,0 +1,24 @@ +package com.baeldung.hibernate.fetching; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.hibernate.fetching.view.FetchingAppView; + +public class HibernateFetchingTest { + + @Test + public void testLazyFetching() { + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + assertFalse(fav.lazyLoaded()); + } + + @Test + public void testEagerFetching() { + FetchingAppView fav = new FetchingAppView(); + assertTrue(fav.eagerLoaded()); + } + +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml similarity index 100% rename from spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml rename to spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml similarity index 100% rename from spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.hbm.xml rename to spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml similarity index 100% rename from spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml rename to spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml diff --git a/spring-hibernate4/src/test/resources/fetching.cfg.xml b/spring-hibernate4/src/test/resources/fetching.cfg.xml new file mode 100644 index 0000000000..4a7e574dda --- /dev/null +++ b/spring-hibernate4/src/test/resources/fetching.cfg.xml @@ -0,0 +1,17 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml new file mode 100644 index 0000000000..1f9a7df94e --- /dev/null +++ b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml @@ -0,0 +1,17 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + + + + \ No newline at end of file From 414821e5baf744ac28c80e69636943800d1bcf91 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Fri, 12 Aug 2016 09:29:31 +0200 Subject: [PATCH 11/31] Refactor Eager Loading vs Lazy Loading --- .../baeldung/main/SpringBootApplication.java | 28 +-- .../hibernate/fetching/model/OrderDetail.java | 141 ++++++++------- .../hibernate/fetching/model/User.java | 80 ++++---- .../fetching/util/HibernateUtil.java | 43 ++--- .../fetching/view/FetchingAppView.java | 171 +++++++++--------- .../web/interceptor/LoggerInterceptor.java | 118 ++++++------ 6 files changed, 282 insertions(+), 299 deletions(-) diff --git a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java index 59955cc990..582d2d9e9c 100644 --- a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java @@ -1,8 +1,5 @@ package org.baeldung.main; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import org.baeldung.common.error.SpringHelloServletRegistrationBean; import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; import org.baeldung.controller.servlet.HelloWorldServlet; @@ -17,6 +14,9 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + @RestController @EnableAutoConfiguration @ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" }) @@ -55,28 +55,6 @@ public class SpringBootApplication { return bean; } - /* @Bean - public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() { - JettyEmbeddedServletContainerFactory jettyContainer = new JettyEmbeddedServletContainerFactory(); - jettyContainer.setPort(9000); - jettyContainer.setContextPath("/springbootapp"); - return jettyContainer; - } - - @Bean - public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() { - UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory(); - factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { - - @Override - public void customize(io.undertow.Undertow.Builde builder) { - builder.addHttpListener(8080, "0.0.0.0"); - } - - }); - return factory; - }*/ - @Bean @Autowired public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) { diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index 19ed36eceb..91388b107b 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -3,71 +3,80 @@ package com.baeldung.hibernate.fetching.model; import java.io.Serializable; import java.sql.Date; -public class OrderDetail implements Serializable{ +public class OrderDetail implements Serializable { + + private static final long serialVersionUID = 1L; + private Long orderId; + private Date orderDate; + private String orderDesc; + private User user; + + public OrderDetail() { + + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + this.orderDate = orderDate; + this.orderDesc = orderDesc; + } + + public Date getOrderDate() { + return orderDate; + } + + public void setOrderDate(Date orderDate) { + this.orderDate = orderDate; + } + + public String getOrderDesc() { + return orderDesc; + } + + public void setOrderDesc(String orderDesc) { + this.orderDesc = orderDesc; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.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; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } - private static final long serialVersionUID = 1L; - private Long orderId; - private Date orderDate; - private String orderDesc; - private User user; - - public OrderDetail(){ - - } - - public OrderDetail(Date orderDate, String orderDesc) { - super(); - this.orderDate = orderDate; - this.orderDesc = orderDesc; - } - - public Date getOrderDate() { - return orderDate; - } - public void setOrderDate(Date orderDate) { - this.orderDate = orderDate; - } - public String getOrderDesc() { - return orderDesc; - } - public void setOrderDesc(String orderDesc) { - this.orderDesc = orderDesc; - } - public User getUser() { - return user; - } - public void setUser(User user) { - this.user = user; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((orderId == null) ? 0 : orderId.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; - OrderDetail other = (OrderDetail) obj; - if (orderId == null) { - if (other.orderId != null) - return false; - } else if (!orderId.equals(other.orderId)) - return false; - - return true; - } - public Long getOrderId() { - return orderId; - } - public void setOrderId(Long orderId) { - this.orderId = orderId; - } - } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java index eb98b7d0f9..158855f93e 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java @@ -5,92 +5,90 @@ import java.util.HashSet; import java.util.Set; public class User implements Serializable { - - private static final long serialVersionUID = 1L; - private Long userId; + + private static final long serialVersionUID = 1L; + private Long userId; private String userName; private String firstName; private String lastName; private Set orderDetail = new HashSet(); public User() { - } public User(final Long userId, final String userName, final String firstName, final String lastName) { - super(); - this.userId = userId; - this.userName = userName; - this.firstName = firstName; - this.lastName = lastName; + super(); + this.userId = userId; + this.userName = userName; + this.firstName = firstName; + this.lastName = lastName; } @Override public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; } @Override public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final User other = (User) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final User other = (User) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; } public Long getUserId() { - return userId; + return userId; } public void setUserId(final Long userId) { - this.userId = userId; + this.userId = userId; } public String getUserName() { - return userName; + return userName; } public void setUserName(final String userName) { - this.userName = userName; + this.userName = userName; } public String getFirstName() { - return firstName; + return firstName; } public void setFirstName(final String firstName) { - this.firstName = firstName; + this.firstName = firstName; } public String getLastName() { - return lastName; + return lastName; } public void setLastName(final String lastName) { - this.lastName = lastName; + this.lastName = lastName; } - public Set getOrderDetail() { - return orderDetail; - } + public Set getOrderDetail() { + return orderDetail; + } - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } - } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index be877fcaba..65ecea2fa4 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -1,33 +1,30 @@ package com.baeldung.hibernate.fetching.util; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { - private static SessionFactory factory; - @SuppressWarnings("deprecation") - public static Session getHibernateSession(String fetchMethod) { - //two config files are there - //one with lazy loading enabled - //another lazy = false - SessionFactory sf = null; - if ("lazy".equals(fetchMethod)) { - sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); - } else { - sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); - } - // fetching.cfg.xml is used for this example - final Session session = sf.openSession(); - return session; - } + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + //two config files are there + //one with lazy loading enabled + //another lazy = false - public static Session getHibernateSession() { - SessionFactory sf = null; - sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); - final Session session = sf.openSession(); - return session; - } + final String configFileName = "lazy".equals(fetchMethod) ? + "fetchingLazy.cfg.xml" : + "fetching.cfg.xml"; + + return new Configuration() + .configure(configFileName) + .buildSessionFactory().openSession(); + } + + public static Session getHibernateSession() { + return new Configuration() + .configure("fetching.cfg.xml") + .buildSessionFactory() + .openSession(); + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java index 729acde019..90fd302968 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -17,97 +17,94 @@ import com.baeldung.hibernate.fetching.model.User; public class FetchingAppView { - - public FetchingAppView(){ - - } - //lazily loaded - public boolean lazyLoaded(){ - final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); - List users = sessionLazy.createQuery("From User").list(); - User userLazyLoaded = new User(); - userLazyLoaded = users.get(3); - //since data is lazyloaded so data won't be initialized - Set orderDetailSet = userLazyLoaded.getOrderDetail(); - return (Hibernate.isInitialized(orderDetailSet)); - } - - //eagerly loaded - public boolean eagerLoaded(){ - final Session sessionEager = HibernateUtil.getHibernateSession(); - //data should be loaded in the following line - //also note the queries generated - List users =sessionEager.createQuery("From User").list(); - User userEagerLoaded = new User(); - userEagerLoaded = users.get(3); - Set orderDetailSet = userEagerLoaded.getOrderDetail(); - return (Hibernate.isInitialized(orderDetailSet)); - } - - - //creates test data - //call this method to create the data in the database - public void createTestData() { + public FetchingAppView() { - final Session session = HibernateUtil.getHibernateSession(); - Transaction tx = null; - tx = session.beginTransaction(); - final User user1 = new User(); - final User user2 = new User(); - final User user3 = new User(); - - user1.setFirstName("Priyam"); - user1.setLastName("Banerjee"); - user1.setUserName("priyambanerjee"); - session.save(user1); - - user2.setFirstName("Navneeta"); - user2.setLastName("Mukherjee"); - user2.setUserName("nmukh"); - session.save(user2); - - user3.setFirstName("Molly"); - user3.setLastName("Banerjee"); - user3.setUserName("mollyb"); - session.save(user3); + } - final OrderDetail order1 = new OrderDetail(); - final OrderDetail order2 = new OrderDetail(); - final OrderDetail order3 = new OrderDetail(); - final OrderDetail order4 = new OrderDetail(); - final OrderDetail order5 = new OrderDetail(); + public boolean lazyLoaded() { + final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); + List users = sessionLazy.createQuery("From User").list(); + User userLazyLoaded = users.get(3); + //since data is lazyloaded so data won't be initialized + Set orderDetailSet = userLazyLoaded.getOrderDetail(); - order1.setOrderDesc("First Order"); - order1.setOrderDate(new Date(2014, 10, 12)); - order1.setUser(user1); - - order2.setOrderDesc("Second Order"); - order2.setOrderDate(new Date(2016, 10, 25)); - order2.setUser(user1); - - order3.setOrderDesc("Third Order"); - order3.setOrderDate(new Date(2015, 2, 17)); - order3.setUser(user2); - - order4.setOrderDesc("Fourth Order"); - order4.setOrderDate(new Date(2014, 10, 1)); - order4.setUser(user2); - - order5.setOrderDesc("Fifth Order"); - order5.setOrderDate(new Date(2014, 9, 11)); - order5.setUser(user3); - - - session.saveOrUpdate(order1); - session.saveOrUpdate(order2); - session.saveOrUpdate(order3); - session.saveOrUpdate(order4); - session.saveOrUpdate(order5); + return (Hibernate.isInitialized(orderDetailSet)); + } - // session.saveOrUpdate(user1); - tx.commit(); - session.close(); + public boolean eagerLoaded() { + final Session sessionEager = HibernateUtil.getHibernateSession(); + //data should be loaded in the following line + //also note the queries generated + List users = sessionEager.createQuery("From User").list(); + User userEagerLoaded = users.get(3); + Set orderDetailSet = userEagerLoaded.getOrderDetail(); - } + return (Hibernate.isInitialized(orderDetailSet)); + } + + + //creates test data + //call this method to create the data in the database + public void createTestData() { + + final Session session = HibernateUtil.getHibernateSession(); + Transaction tx = session.beginTransaction(); + + final User user1 = new User(); + final User user2 = new User(); + final User user3 = new User(); + + user1.setFirstName("Priyam"); + user1.setLastName("Banerjee"); + user1.setUserName("priyambanerjee"); + session.save(user1); + + user2.setFirstName("Navneeta"); + user2.setLastName("Mukherjee"); + user2.setUserName("nmukh"); + session.save(user2); + + user3.setFirstName("Molly"); + user3.setLastName("Banerjee"); + user3.setUserName("mollyb"); + session.save(user3); + + final OrderDetail order1 = new OrderDetail(); + final OrderDetail order2 = new OrderDetail(); + final OrderDetail order3 = new OrderDetail(); + final OrderDetail order4 = new OrderDetail(); + final OrderDetail order5 = new OrderDetail(); + + order1.setOrderDesc("First Order"); + order1.setOrderDate(new Date(2014, 10, 12)); + order1.setUser(user1); + + order2.setOrderDesc("Second Order"); + order2.setOrderDate(new Date(2016, 10, 25)); + order2.setUser(user1); + + order3.setOrderDesc("Third Order"); + order3.setOrderDate(new Date(2015, 2, 17)); + order3.setUser(user2); + + order4.setOrderDesc("Fourth Order"); + order4.setOrderDate(new Date(2014, 10, 1)); + order4.setUser(user2); + + order5.setOrderDesc("Fifth Order"); + order5.setOrderDate(new Date(2014, 9, 11)); + order5.setUser(user3); + + + session.saveOrUpdate(order1); + session.saveOrUpdate(order2); + session.saveOrUpdate(order3); + session.saveOrUpdate(order4); + session.saveOrUpdate(order5); + + // session.saveOrUpdate(user1); + tx.commit(); + session.close(); + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java index f4aa2ff4f5..6afbd921ec 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java @@ -1,74 +1,78 @@ package org.baeldung.web.interceptor; -import java.util.Enumeration; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - +import com.google.common.base.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; -import com.google.common.base.Strings; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Enumeration; public class LoggerInterceptor extends HandlerInterceptorAdapter { - private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class); + private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class); - /** Executed before actual handler is executed **/ - @Override - public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { - log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request)); - return true; - } + /** + * Executed before actual handler is executed + **/ + @Override + public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { + log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request)); + return true; + } - /** Executed before after handler is executed **/ - @Override - public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, - final ModelAndView modelAndView) throws Exception { - log.info("[postHandle][" + request + "]"); - } + /** + * Executed before after handler is executed + **/ + @Override + public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, + final ModelAndView modelAndView) throws Exception { + log.info("[postHandle][" + request + "]"); + } - /** Executed after complete request is finished **/ - @Override - public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) - throws Exception { - if (ex != null) - ex.printStackTrace(); - log.info("[afterCompletion][" + request + "][exception: " + ex + "]"); - } + /** + * Executed after complete request is finished + **/ + @Override + public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) + throws Exception { + if (ex != null) + ex.printStackTrace(); + log.info("[afterCompletion][" + request + "][exception: " + ex + "]"); + } - private String getParameters(final HttpServletRequest request) { - final StringBuffer posted = new StringBuffer(); - final Enumeration e = request.getParameterNames(); - if (e != null) - posted.append("?"); - while (e.hasMoreElements()) { - if (posted.length() > 1) - posted.append("&"); - final String curr = (String) e.nextElement(); - posted.append(curr + "="); - if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) { - posted.append("*****"); - } else { - posted.append(request.getParameter(curr)); - } - } + private String getParameters(final HttpServletRequest request) { + final StringBuffer posted = new StringBuffer(); + final Enumeration e = request.getParameterNames(); + if (e != null) + posted.append("?"); + while (e != null && e.hasMoreElements()) { + if (posted.length() > 1) + posted.append("&"); + final String curr = (String) e.nextElement(); + posted.append(curr).append("="); + if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) { + posted.append("*****"); + } else { + posted.append(request.getParameter(curr)); + } + } - final String ip = request.getHeader("X-FORWARDED-FOR"); - final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip; - if (!Strings.isNullOrEmpty(ipAddr)) - posted.append("&_psip=" + ipAddr); - return posted.toString(); - } + final String ip = request.getHeader("X-FORWARDED-FOR"); + final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip; + if (!Strings.isNullOrEmpty(ipAddr)) + posted.append("&_psip=" + ipAddr); + return posted.toString(); + } - private String getRemoteAddr(final HttpServletRequest request) { - final String ipFromHeader = request.getHeader("X-FORWARDED-FOR"); - if (ipFromHeader != null && ipFromHeader.length() > 0) { - log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader); - return ipFromHeader; - } - return request.getRemoteAddr(); - } + private String getRemoteAddr(final HttpServletRequest request) { + final String ipFromHeader = request.getHeader("X-FORWARDED-FOR"); + if (ipFromHeader != null && ipFromHeader.length() > 0) { + log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader); + return ipFromHeader; + } + return request.getRemoteAddr(); + } } From feb53db0e6d0a0ad240c21bffa8cec728185db4b Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Fri, 12 Aug 2016 11:18:15 +0200 Subject: [PATCH 12/31] Fix formatting --- .../deserialization/GsonDeserializeTest.java | 6 ++-- .../gson/serialization/GsonSerializeTest.java | 33 +++++++++---------- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java index 61197546b0..d87f0f4bd9 100644 --- a/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java +++ b/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java @@ -1,14 +1,14 @@ package org.baeldung.gson.deserialization; -import java.text.ParseException; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.baeldung.gson.entities.ActorGson; import org.baeldung.gson.entities.Movie; import org.baeldung.gson.serialization.ActorGsonDeserializer; import org.junit.Assert; import org.junit.Test; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.text.ParseException; public class GsonDeserializeTest { diff --git a/gson/src/test/java/org/baeldung/gson/serialization/GsonSerializeTest.java b/gson/src/test/java/org/baeldung/gson/serialization/GsonSerializeTest.java index 0d44b6c9d3..7d5502b72f 100644 --- a/gson/src/test/java/org/baeldung/gson/serialization/GsonSerializeTest.java +++ b/gson/src/test/java/org/baeldung/gson/serialization/GsonSerializeTest.java @@ -1,20 +1,17 @@ package org.baeldung.gson.serialization; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; - -import org.baeldung.gson.entities.ActorGson; -import org.baeldung.gson.entities.Movie; -import org.baeldung.gson.entities.MovieWithNullValue; -import org.baeldung.gson.serialization.ActorGsonDeserializer; -import org.baeldung.gson.serialization.ActorGsonSerializer; -import org.junit.Assert; -import org.junit.Test; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParser; +import org.baeldung.gson.entities.ActorGson; +import org.baeldung.gson.entities.Movie; +import org.baeldung.gson.entities.MovieWithNullValue; +import org.junit.Assert; +import org.junit.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; public class GsonSerializeTest { @@ -40,12 +37,12 @@ public class GsonSerializeTest { MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); String expectedOutput = new GsonBuilder() - .setPrettyPrinting() - .serializeNulls() - .disableHtmlEscaping() - .create() - .toJson(new JsonParser() - .parse("{\"imdbId\":null,\"actors\":[{\"IMDB Code\":\"nm2199632\",\"Date Of Birth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}")); + .setPrettyPrinting() + .serializeNulls() + .disableHtmlEscaping() + .create() + .toJson(new JsonParser() + .parse("{\"imdbId\":null,\"actors\":[{\"IMDB Code\":\"nm2199632\",\"Date Of Birth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}")); Assert.assertEquals(gson.toJson(movieWithNullValue), expectedOutput); } } From 0d2137f19ee04e77bbd3ee6fa285a64a023748e7 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Fri, 12 Aug 2016 11:18:47 +0200 Subject: [PATCH 13/31] Remove unnecessary throws clauses --- .../deserialization/JacksonDeserializeTest.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java b/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java index a21762d24a..71d5ad3d81 100644 --- a/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java +++ b/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java @@ -1,20 +1,18 @@ package org.baeldung.jackson.deserialization; -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; +import com.fasterxml.jackson.databind.ObjectMapper; import org.baeldung.jackson.entities.Movie; import org.junit.Assert; import org.junit.Test; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; public class JacksonDeserializeTest { @Test - public void whenSimpleDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { + public void whenSimpleDeserialize_thenCorrect() throws IOException { String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; ObjectMapper mapper = new ObjectMapper(); @@ -25,7 +23,7 @@ public class JacksonDeserializeTest { } @Test - public void whenCustomDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { + public void whenCustomDeserialize_thenCorrect() throws IOException { String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; From 1297da235982d6cb1b88dfc2df95efa708c13ed0 Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 16:51:15 +0300 Subject: [PATCH 14/31] Updated LSS campaign link --- spring-security-basic-auth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-basic-auth/README.md b/spring-security-basic-auth/README.md index f3c29e1777..37ea545a9b 100644 --- a/spring-security-basic-auth/README.md +++ b/spring-security-basic-auth/README.md @@ -3,7 +3,7 @@ ## Spring Security with Basic Authentication Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Article: - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) From 8b62e9bd2fc4b750d7d2edaa6079301fb030cc41 Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 16:52:19 +0300 Subject: [PATCH 15/31] Updated LSS campaign link --- spring-security-client/README.MD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-client/README.MD b/spring-security-client/README.MD index 2a87b46021..5ac974203b 100644 --- a/spring-security-client/README.MD +++ b/spring-security-client/README.MD @@ -1,2 +1,2 @@ ###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring +The "REST With Spring" Classes: http://github.learnspringsecurity.com From 0b7eafcea859a5a5271e3284fd704016d43cd4fc Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 16:55:09 +0300 Subject: [PATCH 16/31] Updated LSS campaign link --- spring-security-custom-permission/README.MD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-custom-permission/README.MD b/spring-security-custom-permission/README.MD index 2a87b46021..5ac974203b 100644 --- a/spring-security-custom-permission/README.MD +++ b/spring-security-custom-permission/README.MD @@ -1,2 +1,2 @@ ###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring +The "REST With Spring" Classes: http://github.learnspringsecurity.com From 3c8f262d2f1959927051bcb7864200f6f0b55316 Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 16:55:56 +0300 Subject: [PATCH 17/31] Updated LSS campaign link --- spring-security-mvc-custom/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-custom/README.md b/spring-security-mvc-custom/README.md index cbf5fc6a97..14bac6c454 100644 --- a/spring-security-mvc-custom/README.md +++ b/spring-security-mvc-custom/README.md @@ -3,7 +3,7 @@ ## Spring Security Login Example Project ###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring +The "REST With Spring" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me) From bf262e579b0537a7576398c9325700208d5a6e7e Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 16:56:42 +0300 Subject: [PATCH 18/31] Updated LSS campaign link --- spring-security-mvc-digest-auth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-digest-auth/README.md b/spring-security-mvc-digest-auth/README.md index 21835266bf..8b79b6b113 100644 --- a/spring-security-mvc-digest-auth/README.md +++ b/spring-security-mvc-digest-auth/README.md @@ -3,7 +3,7 @@ ## Spring Security with Digest Authentication Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Article: - [Spring Security Digest Authentication](http://www.baeldung.com/spring-security-digest-authentication) From e4320c4d015660ec0aeec45bbfb2e8fbd529cc73 Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 16:58:48 +0300 Subject: [PATCH 19/31] Updated LSS campaign link --- spring-security-mvc-ldap/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-ldap/README.md b/spring-security-mvc-ldap/README.md index 1eb3b75405..fe6a667c40 100644 --- a/spring-security-mvc-ldap/README.md +++ b/spring-security-mvc-ldap/README.md @@ -2,7 +2,7 @@ ## Spring Security with LDAP Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Article: - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) From c22ca4d60191611ac2bedc449ed921ac4a1affee Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 16:59:44 +0300 Subject: [PATCH 20/31] Updated LSS campaign link --- spring-security-mvc-login/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-login/README.md b/spring-security-mvc-login/README.md index 448c25d27b..7cddc42e1d 100644 --- a/spring-security-mvc-login/README.md +++ b/spring-security-mvc-login/README.md @@ -3,7 +3,7 @@ ## Spring Security Login Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Form Login](http://www.baeldung.com/spring-security-login) From e28b59c68a0cdf4a8220993bc0478ba650f3870f Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 17:00:17 +0300 Subject: [PATCH 21/31] Updated LSS campaign link --- spring-security-mvc-persisted-remember-me/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-persisted-remember-me/README.md b/spring-security-mvc-persisted-remember-me/README.md index 0d5f4f5f0e..f910c3f62b 100644 --- a/spring-security-mvc-persisted-remember-me/README.md +++ b/spring-security-mvc-persisted-remember-me/README.md @@ -3,7 +3,7 @@ ## Spring Security Persisted Remember Me Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Persisted Remember Me](http://www.baeldung.com/spring-security-persistent-remember-me) From e3adaa2dc9e0d6c3c96db68d149b3509600fadbd Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 17:00:37 +0300 Subject: [PATCH 22/31] Updated LSS campaign link --- spring-security-mvc-session/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-session/README.md b/spring-security-mvc-session/README.md index 28f216c130..fc44209640 100644 --- a/spring-security-mvc-session/README.md +++ b/spring-security-mvc-session/README.md @@ -3,7 +3,7 @@ ## Spring Security Login Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [HttpSessionListener Example – Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics) From 8801442efc40a70be9198557016f9d433dbcfee4 Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 17:00:58 +0300 Subject: [PATCH 23/31] Updated LSS campaign link --- spring-security-rest-basic-auth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-rest-basic-auth/README.md b/spring-security-rest-basic-auth/README.md index 9621773d91..3bd46bdd2a 100644 --- a/spring-security-rest-basic-auth/README.md +++ b/spring-security-rest-basic-auth/README.md @@ -3,7 +3,7 @@ ## REST API with Basic Authentication - Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1) From d1285d2c0c7596b938472f522b57a29046ebb000 Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 17:01:54 +0300 Subject: [PATCH 24/31] Updated LSS campaign link --- spring-security-rest-custom/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-rest-custom/README.md b/spring-security-rest-custom/README.md index 38dc638e8d..85f2b7532c 100644 --- a/spring-security-rest-custom/README.md +++ b/spring-security-rest-custom/README.md @@ -3,7 +3,7 @@ ## Spring Security for REST Example Project ###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring +The "REST With Spring" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Authentication Provider](http://www.baeldung.com/spring-security-authentication-provider) From bf5ec1fc513dbd1ab7e3c403a9cf19d6e838db9c Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 17:02:13 +0300 Subject: [PATCH 25/31] Updated LSS campaign link --- spring-security-rest-digest-auth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-rest-digest-auth/README.md b/spring-security-rest-digest-auth/README.md index 4fdc934fe5..3328bcb2e3 100644 --- a/spring-security-rest-digest-auth/README.md +++ b/spring-security-rest-digest-auth/README.md @@ -3,7 +3,7 @@ ## REST API with Digest Authentication - Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [RestTemplate with Digest Authentication](http://www.baeldung.com/resttemplate-digest-authentication) From 9729c9e1924d39427617e6fe3c6a36b4e4114b1b Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 17:02:35 +0300 Subject: [PATCH 26/31] Updated LSS campaign link --- spring-security-rest-full/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index 947d32e87c..1cbe1191a8 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -5,7 +5,7 @@ ### Courses The "REST With Spring" Classes: http://bit.ly/restwithspring -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) From 4146a619a9ac89d99b28b20583cccaf933d85657 Mon Sep 17 00:00:00 2001 From: Catalin Date: Fri, 12 Aug 2016 17:03:09 +0300 Subject: [PATCH 27/31] Updated LSS campaign link --- spring-security-rest/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index 87f14a9047..bea417a800 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -5,7 +5,7 @@ ### Courses The "REST With Spring" Classes: http://bit.ly/restwithspring -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring REST Service Security](http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/) From bea75a0746248a4fc585b23aed310832e88f4f2c Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 13 Aug 2016 13:27:28 +0200 Subject: [PATCH 28/31] BAEL-124 - renaming modules --- spring-security-x509/pom.xml | 4 ++-- .../pom.xml | 0 .../spring/security/x509/UserController.java | 0 .../security/x509/X509AuthenticationServer.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/templates/user.html | 0 .../x509/X509AuthenticationServerTests.java | 0 .../pom.xml | 0 .../spring/security/x509/UserController.java | 0 .../security/x509/X509AuthenticationServer.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/keystore.jks | Bin .../src/main/resources/templates/user.html | 0 .../x509/X509AuthenticationServerTests.java | 0 14 files changed, 2 insertions(+), 2 deletions(-) rename spring-security-x509/{basic-secured-server => spring-security-x509-basic-auth}/pom.xml (100%) rename spring-security-x509/{basic-secured-server => spring-security-x509-basic-auth}/src/main/java/com/baeldung/spring/security/x509/UserController.java (100%) rename spring-security-x509/{basic-secured-server => spring-security-x509-basic-auth}/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java (100%) rename spring-security-x509/{basic-secured-server => spring-security-x509-basic-auth}/src/main/resources/application.properties (100%) rename spring-security-x509/{basic-secured-server => spring-security-x509-basic-auth}/src/main/resources/templates/user.html (100%) rename spring-security-x509/{basic-secured-server => spring-security-x509-basic-auth}/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java (100%) rename spring-security-x509/{client-auth-server => spring-security-x509-client-auth}/pom.xml (100%) rename spring-security-x509/{client-auth-server => spring-security-x509-client-auth}/src/main/java/com/baeldung/spring/security/x509/UserController.java (100%) rename spring-security-x509/{client-auth-server => spring-security-x509-client-auth}/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java (100%) rename spring-security-x509/{client-auth-server => spring-security-x509-client-auth}/src/main/resources/application.properties (100%) rename spring-security-x509/{client-auth-server => spring-security-x509-client-auth}/src/main/resources/keystore.jks (100%) rename spring-security-x509/{client-auth-server => spring-security-x509-client-auth}/src/main/resources/templates/user.html (100%) rename spring-security-x509/{client-auth-server => spring-security-x509-client-auth}/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java (100%) diff --git a/spring-security-x509/pom.xml b/spring-security-x509/pom.xml index 8a9fd200a8..953af761b5 100644 --- a/spring-security-x509/pom.xml +++ b/spring-security-x509/pom.xml @@ -9,8 +9,8 @@ pom - basic-secured-server - client-auth-server + spring-security-x509-basic-auth + spring-security-x509-client-auth diff --git a/spring-security-x509/basic-secured-server/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml similarity index 100% rename from spring-security-x509/basic-secured-server/pom.xml rename to spring-security-x509/spring-security-x509-basic-auth/pom.xml diff --git a/spring-security-x509/basic-secured-server/src/main/java/com/baeldung/spring/security/x509/UserController.java b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java similarity index 100% rename from spring-security-x509/basic-secured-server/src/main/java/com/baeldung/spring/security/x509/UserController.java rename to spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java diff --git a/spring-security-x509/basic-secured-server/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java similarity index 100% rename from spring-security-x509/basic-secured-server/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java rename to spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java diff --git a/spring-security-x509/basic-secured-server/src/main/resources/application.properties b/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties similarity index 100% rename from spring-security-x509/basic-secured-server/src/main/resources/application.properties rename to spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties diff --git a/spring-security-x509/basic-secured-server/src/main/resources/templates/user.html b/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/templates/user.html similarity index 100% rename from spring-security-x509/basic-secured-server/src/main/resources/templates/user.html rename to spring-security-x509/spring-security-x509-basic-auth/src/main/resources/templates/user.html diff --git a/spring-security-x509/basic-secured-server/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java similarity index 100% rename from spring-security-x509/basic-secured-server/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java rename to spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java diff --git a/spring-security-x509/client-auth-server/pom.xml b/spring-security-x509/spring-security-x509-client-auth/pom.xml similarity index 100% rename from spring-security-x509/client-auth-server/pom.xml rename to spring-security-x509/spring-security-x509-client-auth/pom.xml diff --git a/spring-security-x509/client-auth-server/src/main/java/com/baeldung/spring/security/x509/UserController.java b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java similarity index 100% rename from spring-security-x509/client-auth-server/src/main/java/com/baeldung/spring/security/x509/UserController.java rename to spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java diff --git a/spring-security-x509/client-auth-server/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java similarity index 100% rename from spring-security-x509/client-auth-server/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java rename to spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java diff --git a/spring-security-x509/client-auth-server/src/main/resources/application.properties b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties similarity index 100% rename from spring-security-x509/client-auth-server/src/main/resources/application.properties rename to spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties diff --git a/spring-security-x509/client-auth-server/src/main/resources/keystore.jks b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks similarity index 100% rename from spring-security-x509/client-auth-server/src/main/resources/keystore.jks rename to spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks diff --git a/spring-security-x509/client-auth-server/src/main/resources/templates/user.html b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/templates/user.html similarity index 100% rename from spring-security-x509/client-auth-server/src/main/resources/templates/user.html rename to spring-security-x509/spring-security-x509-client-auth/src/main/resources/templates/user.html diff --git a/spring-security-x509/client-auth-server/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java b/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java similarity index 100% rename from spring-security-x509/client-auth-server/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java rename to spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java From 2c0960b57dec251ea9c71d4970356caaeb9d9e3c Mon Sep 17 00:00:00 2001 From: k0l0ssus Date: Sat, 13 Aug 2016 11:18:09 -0400 Subject: [PATCH 29/31] Adding LambdaExpression class import --- .../baeldung/springintegration/controllers/ELSampleBean.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java index 58dedb08b7..a7ca7d3ede 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java @@ -4,6 +4,7 @@ import java.util.Random; import javax.annotation.PostConstruct; import javax.faces.application.Application; import javax.faces.application.FacesMessage; +import javax.el.LambdaExpression; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.component.html.HtmlInputText; @@ -15,6 +16,7 @@ public class ELSampleBean { private String firstName; private String lastName; + private Collection numberList; private String pageDescription = "This page demos JSF EL Basics"; public static final String constantField = "THIS_IS_NOT_CHANGING_ANYTIME_SOON"; private int pageCounter; From 171cf1f3b459afb6ac9642c61f7913accb615d39 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sun, 14 Aug 2016 08:46:06 +0200 Subject: [PATCH 30/31] BAEL-197 - minor changes --- .../controllers/ELSampleBean.java | 16 ++++++++++++---- jsf/src/main/webapp/el3_intro.xhtml | 4 ++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java index 4d194193e6..16d9f80d89 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java @@ -1,6 +1,8 @@ package com.baeldung.springintegration.controllers; import javax.annotation.PostConstruct; +import javax.el.ELContextEvent; +import javax.el.ELContextListener; import javax.el.LambdaExpression; import javax.faces.application.Application; import javax.faces.application.FacesMessage; @@ -8,6 +10,7 @@ import javax.el.LambdaExpression; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; +import java.util.Collection; import java.util.Random; @ManagedBean(name = "ELBean") @@ -16,7 +19,6 @@ public class ELSampleBean { private String firstName; private String lastName; - private Collection numberList; private String pageDescription = "This page demos JSF EL Basics"; public static final String constantField = "THIS_IS_NOT_CHANGING_ANYTIME_SOON"; private int pageCounter; @@ -25,13 +27,19 @@ public class ELSampleBean { @PostConstruct public void init() { pageCounter = randomIntGen.nextInt(); + FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() { + @Override + public void contextCreated(ELContextEvent evt) { + evt.getELContext().getImportHandler().importClass("com.baeldung.springintegration.controllers.ELSampleBean"); + } + }); } public void save() { } - public static String getConstantField() { + public static String constantField() { return constantField; } @@ -39,8 +47,8 @@ public class ELSampleBean { this.firstName = firstName; } - public String multiplyValue(LambdaExpression expr){ - String theResult = (String) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter); + public Long multiplyValue(LambdaExpression expr) { + Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter); return theResult; } diff --git a/jsf/src/main/webapp/el3_intro.xhtml b/jsf/src/main/webapp/el3_intro.xhtml index ebd3acad0a..3f1f407a08 100644 --- a/jsf/src/main/webapp/el3_intro.xhtml +++ b/jsf/src/main/webapp/el3_intro.xhtml @@ -11,7 +11,7 @@
- +
@@ -19,6 +19,7 @@
+
@@ -29,7 +30,6 @@
- From aed7a46324bf4ae596c7f5f0d00332e497f26afd Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sun, 14 Aug 2016 09:45:23 +0200 Subject: [PATCH 31/31] BAEL-175 - moving to mvc java module --- spring-mvc-java/pom.xml | 5 + .../java/com/baeldung/model}/Greeting.java | 2 +- .../spring/web/config}/ApplicationConfig.java | 4 +- .../web}/controller/GreetController.java | 11 +- .../src/main/webapp/WEB-INF/jsp/index.jsp | 0 .../GreetControllerIntegrationTest.java | 30 +-- .../web}/controller/GreetControllerTest.java | 26 ++- spring-mvc-test/README | 5 - spring-mvc-test/pom.xml | 193 ------------------ .../com/baeldung/web/WebAppInitializer.java | 33 --- .../src/main/resources/logback.xml | 18 -- .../webapp/WEB-INF/spring-servlet-old.xml | 5 - .../src/main/webapp/WEB-INF/web-old.xml | 33 --- 13 files changed, 39 insertions(+), 326 deletions(-) rename {spring-mvc-test/src/main/java/com/baeldung/spring/bean => spring-mvc-java/src/main/java/com/baeldung/model}/Greeting.java (90%) rename {spring-mvc-test/src/main/java/com/baeldung/spring => spring-mvc-java/src/main/java/com/baeldung/spring/web/config}/ApplicationConfig.java (92%) rename {spring-mvc-test/src/main/java/com/baeldung/spring => spring-mvc-java/src/main/java/com/baeldung/web}/controller/GreetController.java (83%) rename {spring-mvc-test => spring-mvc-java}/src/main/webapp/WEB-INF/jsp/index.jsp (100%) rename {spring-mvc-test/src/test/java/com/baeldung/spring => spring-mvc-java/src/test/java/com/baeldung/web}/controller/GreetControllerIntegrationTest.java (85%) rename {spring-mvc-test/src/test/java/com/baeldung/spring => spring-mvc-java/src/test/java/com/baeldung/web}/controller/GreetControllerTest.java (55%) delete mode 100644 spring-mvc-test/README delete mode 100644 spring-mvc-test/pom.xml delete mode 100644 spring-mvc-test/src/main/java/com/baeldung/web/WebAppInitializer.java delete mode 100644 spring-mvc-test/src/main/resources/logback.xml delete mode 100644 spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet-old.xml delete mode 100644 spring-mvc-test/src/main/webapp/WEB-INF/web-old.xml diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 33d6306c5a..4d3432d47b 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -111,6 +111,11 @@ ${mockito.version} test + + com.jayway.jsonpath + json-path + 2.2.0 + org.springframework spring-test diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java b/spring-mvc-java/src/main/java/com/baeldung/model/Greeting.java similarity index 90% rename from spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java rename to spring-mvc-java/src/main/java/com/baeldung/model/Greeting.java index 11c0a79b0e..db021b8e8c 100644 --- a/spring-mvc-test/src/main/java/com/baeldung/spring/bean/Greeting.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Greeting.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.bean; +package com.baeldung.model; public class Greeting { private int id; diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java similarity index 92% rename from spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java rename to spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java index 09be5ee113..261d5793dc 100644 --- a/spring-mvc-test/src/main/java/com/baeldung/spring/ApplicationConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring; +package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -12,7 +12,7 @@ import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -@ComponentScan(basePackages = { "com.baeldung.spring.controller" }) +@ComponentScan(basePackages = { "com.baeldung.web.controller" }) public class ApplicationConfig extends WebMvcConfigurerAdapter { public ApplicationConfig() { diff --git a/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/GreetController.java similarity index 83% rename from spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/GreetController.java index d563f80918..6f764fedfb 100644 --- a/spring-mvc-test/src/main/java/com/baeldung/spring/controller/GreetController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/GreetController.java @@ -1,13 +1,8 @@ -package com.baeldung.spring.controller; +package com.baeldung.web.controller; +import com.baeldung.model.Greeting; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.baeldung.spring.bean.Greeting; +import org.springframework.web.bind.annotation.*; @Controller public class GreetController { diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/jsp/index.jsp similarity index 100% rename from spring-mvc-test/src/main/webapp/WEB-INF/jsp/index.jsp rename to spring-mvc-java/src/main/webapp/WEB-INF/jsp/index.jsp diff --git a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java similarity index 85% rename from spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java index abed0a977e..61e0f632f1 100644 --- a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java @@ -1,5 +1,7 @@ -package com.baeldung.spring.controller; +package com.baeldung.web.controller; + +import com.baeldung.spring.web.config.ApplicationConfig; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -11,21 +13,18 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.spring.ApplicationConfig; - -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - import javax.servlet.ServletContext; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; + @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = { ApplicationConfig.class }) +@ContextConfiguration(classes = {ApplicationConfig.class}) public class GreetControllerIntegrationTest { @Autowired @@ -33,6 +32,9 @@ public class GreetControllerIntegrationTest { private MockMvc mockMvc; + private static final String CONTENT_TYPE = "application/json"; + + @Before public void setup() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); @@ -54,36 +56,36 @@ public class GreetControllerIntegrationTest { @Test public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception { MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/greet")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")).andReturn(); - Assert.assertEquals("application/json;charset=UTF-8", mvcResult.getResponse().getContentType()); + Assert.assertEquals(CONTENT_TYPE, mvcResult.getResponse().getContentType()); } @Test public void givenGreetURIWithPathVariable_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John!!!")); } @Test public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/{name}", "Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/{name}", "Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World Doe!!!")); } @Test public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + .andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); } @Test public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); } @Test public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + .andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); } } \ No newline at end of file diff --git a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java similarity index 55% rename from spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java index 8e624544cd..0fd71a46dd 100644 --- a/spring-mvc-test/src/test/java/com/baeldung/spring/controller/GreetControllerTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.controller; +package com.baeldung.web.controller; import org.junit.Before; import org.junit.Test; @@ -9,14 +9,12 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; public class GreetControllerTest { private MockMvc mockMvc; + private static final String CONTENT_TYPE = "application/json"; @Before public void setup() { @@ -30,34 +28,34 @@ public class GreetControllerTest { @Test public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(get("/greet")).andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")).andExpect(jsonPath("$.message").value("Hello World!!!")); + this.mockMvc.perform(get("/greet")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World!!!")); } @Test public void givenGreetURIWithPathVariable_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(get("/greetWithPathVariable/John")).andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")).andExpect(jsonPath("$.message").value("Hello World John!!!")); + this.mockMvc.perform(get("/greetWithPathVariable/John")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John!!!")); } @Test public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(get("/greetWithPathVariable/{name}", "Doe")).andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")).andExpect(jsonPath("$.message").value("Hello World Doe!!!")); + this.mockMvc.perform(get("/greetWithPathVariable/{name}", "Doe")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World Doe!!!")); } @Test public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) + .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")); } @Test public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")) - .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)) + .andExpect(jsonPath("$.message").value("Hello World!!!")); } @Test public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) + .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1)); } } diff --git a/spring-mvc-test/README b/spring-mvc-test/README deleted file mode 100644 index 9f4a0a60d4..0000000000 --- a/spring-mvc-test/README +++ /dev/null @@ -1,5 +0,0 @@ -To compile and run the project, execute following command: - - mvn clean install org.codehaus.cargo:cargo-maven2-plugin:run - -URL: http://localhost:8080/spring-mvc-test/ diff --git a/spring-mvc-test/pom.xml b/spring-mvc-test/pom.xml deleted file mode 100644 index 3c4875f087..0000000000 --- a/spring-mvc-test/pom.xml +++ /dev/null @@ -1,193 +0,0 @@ - - 4.0.0 - com.baeldung - spring-mvc-test - 0.1-SNAPSHOT - spring-mvc-test - war - - - - 4.3.1.RELEASE - - 1.7.21 - 1.1.7 - - 3.4 - - 1.3 - 4.12 - 1.10.19 - 4.4.5 - 4.5.2 - - - 3.5.1 - 2.6 - 2.19.1 - 2.19.1 - 3.0.1 - - - 1.5.0 - - - - - - - org.springframework - spring-web - ${org.springframework.version} - - - org.springframework - spring-webmvc - ${org.springframework.version} - - - org.springframework - spring-websocket - ${org.springframework.version} - - - - com.fasterxml.jackson.core - jackson-core - 2.7.3 - - - com.fasterxml.jackson.core - jackson-databind - 2.7.3 - - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - - - javax.servlet - jstl - 1.2 - runtime - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - org.slf4j - slf4j-log4j12 - ${org.slf4j.version} - - - - junit - junit - ${junit.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.jayway.jsonpath - json-path - 2.2.0 - - - org.springframework - spring-test - ${org.springframework.version} - test - - - - - spring-mvc-test - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - - maven-resources-plugin - 2.7 - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${maven-failsafe-plugin.version} - - - **/*IntegrationTest.java - - - - - - integration-test - verify - - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - - jetty8x - embedded - - - - 8080 - - - - - - - \ No newline at end of file diff --git a/spring-mvc-test/src/main/java/com/baeldung/web/WebAppInitializer.java b/spring-mvc-test/src/main/java/com/baeldung/web/WebAppInitializer.java deleted file mode 100644 index 23fad058d0..0000000000 --- a/spring-mvc-test/src/main/java/com/baeldung/web/WebAppInitializer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.web; - -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -public class WebAppInitializer implements WebApplicationInitializer { - - @Override - public void onStartup(final ServletContext sc) throws ServletException { - - final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.scan("com.baeldung.spring"); - - sc.addListener(new ContextLoaderListener(root)); - - final ServletRegistration.Dynamic appServlet = sc.addServlet("spring", new DispatcherServlet(new GenericWebApplicationContext())); - appServlet.setLoadOnStartup(1); - - final Set mappingConflicts = appServlet.addMapping("/"); - if (!mappingConflicts.isEmpty()) { - throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); - } - } -} diff --git a/spring-mvc-test/src/main/resources/logback.xml b/spring-mvc-test/src/main/resources/logback.xml deleted file mode 100644 index 166c369905..0000000000 --- a/spring-mvc-test/src/main/resources/logback.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet-old.xml b/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet-old.xml deleted file mode 100644 index 2b8192e742..0000000000 --- a/spring-mvc-test/src/main/webapp/WEB-INF/spring-servlet-old.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - \ No newline at end of file diff --git a/spring-mvc-test/src/main/webapp/WEB-INF/web-old.xml b/spring-mvc-test/src/main/webapp/WEB-INF/web-old.xml deleted file mode 100644 index dc0233a7fc..0000000000 --- a/spring-mvc-test/src/main/webapp/WEB-INF/web-old.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - Spring MVC - Integration Testing - - - contextClass - - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - - contextConfigLocation - com.baeldung.spring - - - - org.springframework.web.context.ContextLoaderListener - - - - spring - org.springframework.web.servlet.DispatcherServlet - 1 - - - - spring - / - - \ No newline at end of file