From bf78a04b6893264bac9b2c2204e466864a3520e4 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 26 Jul 2016 09:22:36 +0300 Subject: [PATCH] Refactor Velocity example --- .../velocity/controller/MainController.java | 17 ++-- .../mvc/velocity/domain/Tutorial.java | 27 +++--- .../spring/config/MainWebAppInitializer.java | 51 +++++------ .../velocity/spring/config/SpringConfig.java | 8 +- .../mvc/velocity/spring/config/WebConfig.java | 21 ++--- .../test/DataContentControllerTest.java | 91 ++++++++++--------- .../test/NavigationControllerTest.java | 79 ++++++++-------- 7 files changed, 134 insertions(+), 160 deletions(-) diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java index 1362bf99b3..2c8f224f8c 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java @@ -1,29 +1,24 @@ package com.baeldung.mvc.velocity.controller; -import java.util.List; - +import com.baeldung.mvc.velocity.domain.Tutorial; +import com.baeldung.mvc.velocity.service.ITutorialsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import com.baeldung.mvc.velocity.domain.Tutorial; -import com.baeldung.mvc.velocity.service.ITutorialsService; +import java.util.List; -@Controller -@RequestMapping("/") -public class MainController { +@Controller @RequestMapping("/") public class MainController { private final ITutorialsService tutService; - @Autowired - public MainController(ITutorialsService tutService) { + @Autowired public MainController(ITutorialsService tutService) { this.tutService = tutService; } - @RequestMapping(method = RequestMethod.GET) - public String listTutorialsPage(Model model) { + @RequestMapping(method = RequestMethod.GET) public String listTutorialsPage(Model model) { List list = tutService.listTutorials(); model.addAttribute("tutorials", list); return "index"; diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java index 47265aa98c..ccbaa0e905 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java @@ -14,21 +14,20 @@ public class Tutorial { this.author = author; } - public Integer getTutId() { - return tutId; - } + public Integer getTutId() { + return tutId; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } + + public String getAuthor() { + return author; + } - public String getAuthor() { - return author; - } - - } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/MainWebAppInitializer.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/MainWebAppInitializer.java index 3cc1251e88..4987ca1ada 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/MainWebAppInitializer.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/MainWebAppInitializer.java @@ -1,44 +1,39 @@ package com.baeldung.mvc.velocity.spring.config; -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; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; +import java.util.Set; + public class MainWebAppInitializer implements WebApplicationInitializer { - /** - * Register and configure all Servlet container components necessary to - * power the web application. - */ - @Override - public void onStartup(final ServletContext sc) throws ServletException { + /** + * Register and configure all Servlet container components necessary to + * power the web application. + */ + @Override public void onStartup(final ServletContext sc) throws ServletException { - // Create the 'root' Spring application context - final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.register(WebConfig.class, SpringConfig.class); + // Create the 'root' Spring application context + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.register(WebConfig.class, SpringConfig.class); - // Manages the lifecycle of the root application context - sc.addListener(new ContextLoaderListener(root)); + // Manages the lifecycle of the root application context + sc.addListener(new ContextLoaderListener(root)); - // Handles requests into the application - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", - new DispatcherServlet(new GenericWebApplicationContext())); - appServlet.setLoadOnStartup(1); + // Handles requests into the application + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", 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"); - } - } + 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-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/SpringConfig.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/SpringConfig.java index a024db543d..99fc99be80 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/SpringConfig.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/SpringConfig.java @@ -5,11 +5,9 @@ import org.springframework.context.annotation.Configuration; import com.baeldung.mvc.velocity.service.TutorialsService; -@Configuration -public class SpringConfig { +@Configuration public class SpringConfig { - @Bean - public TutorialsService tutService(){ - return new TutorialsService(); + @Bean public TutorialsService tutService() { + return new TutorialsService(); } } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java index 4cc8e0dca1..1a0f5742e4 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java @@ -11,27 +11,21 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter import org.springframework.web.servlet.view.velocity.VelocityConfigurer; import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; -@Configuration -@EnableWebMvc -@ComponentScan(basePackages={"com.baeldung.mvc.velocity.controller"}) -public class WebConfig extends WebMvcConfigurerAdapter { +@Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller" }) public class WebConfig extends WebMvcConfigurerAdapter { public WebConfig() { super(); } - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { + @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } - - @Override - public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + + @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } - @Bean - public ViewResolver viewResolver() { + @Bean public ViewResolver viewResolver() { final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver(); bean.setCache(true); bean.setPrefix("/WEB-INF/views/"); @@ -39,9 +33,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { bean.setSuffix(".vm"); return bean; } - - @Bean - public VelocityConfigurer velocityConfig() { + + @Bean public VelocityConfigurer velocityConfig() { VelocityConfigurer velocityConfigurer = new VelocityConfigurer(); velocityConfigurer.setResourceLoaderPath("/"); return velocityConfigurer; diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java index 6c62a3fa07..b766075f8a 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java @@ -1,18 +1,9 @@ package com.baeldung.mvc.velocity.test; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -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.xpath; - -import java.util.Arrays; - +import com.baeldung.mvc.velocity.domain.Tutorial; +import com.baeldung.mvc.velocity.service.ITutorialsService; +import com.baeldung.mvc.velocity.spring.config.WebConfig; +import com.baeldung.mvc.velocity.test.config.TestConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,48 +16,58 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.mvc.velocity.domain.Tutorial; -import com.baeldung.mvc.velocity.service.ITutorialsService; -import com.baeldung.mvc.velocity.spring.config.WebConfig; -import com.baeldung.mvc.velocity.test.config.TestConfig; +import java.util.Arrays; + +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +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.xpath; @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = {"classpath:mvc-servlet.xml"}) -@ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) -@WebAppConfiguration -public class DataContentControllerTest { +@ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) @WebAppConfiguration public class DataContentControllerTest { - private MockMvc mockMvc; + private MockMvc mockMvc; - @Autowired - private ITutorialsService tutServiceMock; + @Autowired private ITutorialsService tutServiceMock; - @Autowired - private WebApplicationContext webApplicationContext; + @Autowired private WebApplicationContext webApplicationContext; - @Before - public void setUp() { - Mockito.reset(tutServiceMock); + @Before public void setUp() { + Mockito.reset(tutServiceMock); - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - } + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + } - @Test - public void testModel() throws Exception { + @Test public void testModel() throws Exception { - Mockito.when(tutServiceMock.listTutorials()) - .thenReturn(Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), - new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor"))); + Mockito.when(tutServiceMock.listTutorials()) + .thenReturn(Arrays.asList( + new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), + new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor"))); - mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")) - .andExpect(model().attribute("tutorials", hasSize(2))) - .andExpect(model().attribute("tutorials", - hasItem(allOf(hasProperty("tutId", is(1)), hasProperty("author", is("GuavaAuthor")), - hasProperty("title", is("Guava")))))) - .andExpect(model().attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(2)), - hasProperty("author", is("AndroidAuthor")), hasProperty("title", is("Android")))))); + mockMvc.perform(get("/")) + .andExpect(status().isOk()).andExpect(view().name("index")) + .andExpect(model().attribute("tutorials", hasSize(2))) + .andExpect(model() + .attribute("tutorials", + hasItem(allOf(hasProperty("tutId", is(1)), + hasProperty("author", is("GuavaAuthor")), + hasProperty("title", is("Guava")))))) + .andExpect(model() + .attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(2)), + hasProperty("author", is("AndroidAuthor")), + hasProperty("title", is("Android")))))); - mockMvc.perform(get("/")).andExpect(xpath("//table").exists()); - mockMvc.perform(get("/")).andExpect(xpath("//td[@id='tutId_1']").exists()); - } + mockMvc.perform(get("/")) + .andExpect(xpath("//table").exists()); + mockMvc.perform(get("/")) + .andExpect(xpath("//td[@id='tutId_1']").exists()); + } } diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java index f9b2cdc76b..0189086153 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java @@ -1,15 +1,9 @@ package com.baeldung.mvc.velocity.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import java.util.Arrays; -import java.util.List; - +import com.baeldung.mvc.velocity.controller.MainController; +import com.baeldung.mvc.velocity.domain.Tutorial; +import com.baeldung.mvc.velocity.service.TutorialsService; +import com.baeldung.mvc.velocity.test.config.TestConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -19,54 +13,53 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; -import com.baeldung.mvc.velocity.controller.MainController; -import com.baeldung.mvc.velocity.domain.Tutorial; -import com.baeldung.mvc.velocity.service.TutorialsService; -import com.baeldung.mvc.velocity.test.config.TestConfig; +import java.util.Arrays; +import java.util.List; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -//@ContextConfiguration(locations = {"classpath:mvc-servlet.xml"}) -@ContextConfiguration(classes = {TestConfig.class}) +@ContextConfiguration(classes = { TestConfig.class }) public class NavigationControllerTest { - private MainController mainController = new MainController(Mockito.mock(TutorialsService.class)); - - private final Model model = new ExtendedModelMap(); + private MainController mainController = new MainController(Mockito.mock(TutorialsService.class)); - - @Test - public void shouldGoToTutorialListView() { - Mockito.when(mainController.getTutService().listTutorials()) - .thenReturn(createTutorialList()); + private final Model model = new ExtendedModelMap(); - final String view = mainController.listTutorialsPage(model); - final List tutorialListAttribute = (List) model.asMap().get("tutorials"); - - assertEquals("index", view); - assertNotNull(tutorialListAttribute); - } - - @Test - public void testContent() throws Exception{ + @Test public void shouldGoToTutorialListView() { + Mockito.when(mainController.getTutService().listTutorials()).thenReturn(createTutorialList()); + + final String view = mainController.listTutorialsPage(model); + final List tutorialListAttribute = (List) model.asMap().get("tutorials"); + + assertEquals("index", view); + assertNotNull(tutorialListAttribute); + } + + @Test public void testContent() throws Exception { List tutorials = Arrays.asList( - new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), - new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor") - ); - Mockito.when(mainController.getTutService().listTutorials()).thenReturn(tutorials); + new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), + new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")); + + Mockito.when(mainController.getTutService().listTutorials()) + .thenReturn(tutorials); String view = mainController.listTutorialsPage(model); verify(mainController.getTutService(), times(1)).listTutorials(); verifyNoMoreInteractions(mainController.getTutService()); - - assertEquals("index", view); - assertEquals(tutorials, model.asMap().get("tutorials")); - } - private static List createTutorialList() { - return Arrays.asList(new Tutorial(1, "TestAuthor", "Test Title", "Test Description")); + assertEquals("index", view); + assertEquals(tutorials, model.asMap().get("tutorials")); + } + + private static List createTutorialList() { + return Arrays.asList(new Tutorial(1, "TestAuthor", "Test Title", "Test Description")); } }