formatting cleanup

This commit is contained in:
Eugen Paraschiv 2018-05-14 14:30:26 +03:00
parent dec95f5c25
commit 30552c8d0a
26 changed files with 93 additions and 127 deletions

View File

@ -9,9 +9,7 @@ public class AttrListener implements ServletContextListener {
@Override @Override
public void contextInitialized(ServletContextEvent servletContextEvent) { public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContextEvent servletContextEvent.getServletContext().setAttribute("servlet-context-attr", "test");
.getServletContext()
.setAttribute("servlet-context-attr", "test");
System.out.println("context init"); System.out.println("context init");
} }

View File

@ -16,9 +16,7 @@ public class EchoServlet extends HttpServlet {
@Override @Override
public void doPost(HttpServletRequest request, HttpServletResponse response) { public void doPost(HttpServletRequest request, HttpServletResponse response) {
try { try {
Path path = File Path path = File.createTempFile("echo", "tmp").toPath();
.createTempFile("echo", "tmp")
.toPath();
Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
Files.copy(path, response.getOutputStream()); Files.copy(path, response.getOutputStream());
Files.delete(path); Files.delete(path);

View File

@ -18,9 +18,7 @@ public class HelloFilter implements Filter {
@Override @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse servletResponse.getOutputStream().print(filterConfig.getInitParameter("msg"));
.getOutputStream()
.print(filterConfig.getInitParameter("msg"));
filterChain.doFilter(servletRequest, servletResponse); filterChain.doFilter(servletRequest, servletResponse);
} }

View File

@ -8,22 +8,20 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")}) @WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello") })
public class HelloServlet extends HttpServlet { public class HelloServlet extends HttpServlet {
private ServletConfig servletConfig; private ServletConfig servletConfig;
@Override @Override
public void init(ServletConfig servletConfig){ public void init(ServletConfig servletConfig) {
this.servletConfig = servletConfig; this.servletConfig = servletConfig;
} }
@Override @Override
public void doGet(HttpServletRequest request, HttpServletResponse response) { public void doGet(HttpServletRequest request, HttpServletResponse response) {
try { try {
response response.getOutputStream().write(servletConfig.getInitParameter("msg").getBytes());
.getOutputStream()
.write(servletConfig.getInitParameter("msg").getBytes());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -4,10 +4,8 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class App public class App {
{ public static void main(String[] args) {
public static void main( String[] args )
{
SpringApplication.run(App.class, args); SpringApplication.run(App.class, args);
} }
} }

View File

@ -7,12 +7,12 @@ import org.springframework.web.bind.annotation.RestController;
public class HomeController { public class HomeController {
@RequestMapping("/") @RequestMapping("/")
public String root(){ public String root() {
return "Index Page"; return "Index Page";
} }
@RequestMapping("/local") @RequestMapping("/local")
public String local(){ public String local() {
return "/local"; return "/local";
} }
} }

View File

@ -26,7 +26,6 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter {
configurer.enable(); configurer.enable();
} }
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver());

View File

@ -10,7 +10,8 @@ import org.springframework.core.env.ConfigurableEnvironment;
@Configuration @Configuration
@ComponentScan(basePackages = { "com.baeldung.*" }) @ComponentScan(basePackages = { "com.baeldung.*" })
@PropertySource("classpath:custom.properties") public class PropertySourcesLoader { @PropertySource("classpath:custom.properties")
public class PropertySourcesLoader {
private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class); private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class);

View File

@ -7,9 +7,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
@WebServlet(name = "AnnotationServlet", @WebServlet(name = "AnnotationServlet", description = "Example Servlet Using Annotations", urlPatterns = { "/annotationservlet" })
description = "Example Servlet Using Annotations",
urlPatterns = { "/annotationservlet" })
public class AnnotationServlet extends HttpServlet { public class AnnotationServlet extends HttpServlet {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -7,12 +7,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication @SpringBootApplication
@ComponentScan(basePackages="com.baeldung.utils") @ComponentScan(basePackages = "com.baeldung.utils")
public class Application { public class Application {
@RolesAllowed("*") @RolesAllowed("*")
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
} }
} }

View File

@ -4,7 +4,6 @@ import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@ -13,37 +12,37 @@ import org.springframework.web.util.WebUtils;
@Controller @Controller
public class UtilsController { public class UtilsController {
@GetMapping("/utils") @GetMapping("/utils")
public String webUtils(Model model) { public String webUtils(Model model) {
return "utils"; return "utils";
} }
@PostMapping("/setParam") @PostMapping("/setParam")
public String post(HttpServletRequest request, Model model) { public String post(HttpServletRequest request, Model model) {
String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT");
// Long param = ServletRequestUtils.getLongParameter(request, "param",1L); // Long param = ServletRequestUtils.getLongParameter(request, "param",1L);
// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); // boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true);
// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); // double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000);
// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); // float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00);
// int param = ServletRequestUtils.getIntParameter(request, "param", 100); // int param = ServletRequestUtils.getIntParameter(request, "param", 100);
// try { // try {
// ServletRequestUtils.getRequiredStringParameter(request, "param"); // ServletRequestUtils.getRequiredStringParameter(request, "param");
// } catch (ServletRequestBindingException e) { // } catch (ServletRequestBindingException e) {
// e.printStackTrace(); // e.printStackTrace();
// } // }
WebUtils.setSessionAttribute(request, "parameter", param); WebUtils.setSessionAttribute(request, "parameter", param);
model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter")); model.addAttribute("parameter", "You set: " + (String) WebUtils.getSessionAttribute(request, "parameter"));
return "utils"; return "utils";
} }
@GetMapping("/other") @GetMapping("/other")
public String other(HttpServletRequest request, Model model) { public String other(HttpServletRequest request, Model model) {
String param = (String) WebUtils.getSessionAttribute(request, "parameter"); String param = (String) WebUtils.getSessionAttribute(request, "parameter");
model.addAttribute("parameter", param); model.addAttribute("parameter", param);
return "other"; return "other";
} }
} }

View File

@ -2,7 +2,6 @@ package com.baeldung.webjar;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication @SpringBootApplication
public class WebjarsdemoApplication { public class WebjarsdemoApplication {

View File

@ -10,11 +10,11 @@ public class FooService {
@Autowired @Autowired
private FooRepository fooRepository; private FooRepository fooRepository;
public Foo getFooWithId(Integer id) throws Exception { public Foo getFooWithId(Integer id) throws Exception {
return fooRepository.findOne(id); return fooRepository.findOne(id);
} }
public Foo getFooWithName(String name) { public Foo getFooWithName(String name) {
return fooRepository.findByName(name); return fooRepository.findByName(name);
} }

View File

@ -1,13 +1,13 @@
package org.baeldung.boot.exceptions; package org.baeldung.boot.exceptions;
public class CommonException extends RuntimeException{ public class CommonException extends RuntimeException {
/** /**
* *
*/ */
private static final long serialVersionUID = 3080004140659213332L; private static final long serialVersionUID = 3080004140659213332L;
public CommonException(String message){ public CommonException(String message) {
super(message); super(message);
} }
} }

View File

@ -1,13 +1,13 @@
package org.baeldung.boot.exceptions; package org.baeldung.boot.exceptions;
public class FooNotFoundException extends RuntimeException{ public class FooNotFoundException extends RuntimeException {
/** /**
* *
*/ */
private static final long serialVersionUID = 9042200028456133589L; private static final long serialVersionUID = 9042200028456133589L;
public FooNotFoundException(String message){ public FooNotFoundException(String message) {
super(message); super(message);
} }
} }

View File

@ -21,7 +21,6 @@ public class Foo implements Serializable {
this.name = name; this.name = name;
} }
public Foo(Integer id, String name) { public Foo(Integer id, String name) {
super(); super();
this.id = id; this.id = id;

View File

@ -18,7 +18,7 @@ public class FooController {
public Foo getFooWithId(@PathVariable Integer id) throws Exception { public Foo getFooWithId(@PathVariable Integer id) throws Exception {
return fooService.getFooWithId(id); return fooService.getFooWithId(id);
} }
@GetMapping("/") @GetMapping("/")
public Foo getFooWithName(@RequestParam String name) throws Exception { public Foo getFooWithName(@RequestParam String name) throws Exception {
return fooService.getFooWithName(name); return fooService.getFooWithName(name);

View File

@ -22,7 +22,8 @@ import static org.junit.Assert.*;
@TestPropertySource(properties = { "security.basic.enabled=false" }) @TestPropertySource(properties = { "security.basic.enabled=false" })
public class SpringBootWithServletComponentIntegrationTest { public class SpringBootWithServletComponentIntegrationTest {
@Autowired private ServletContext servletContext; @Autowired
private ServletContext servletContext;
@Test @Test
public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() { public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() {
@ -37,12 +38,11 @@ public class SpringBootWithServletComponentIntegrationTest {
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNotNull(filterRegistration); assertNotNull(filterRegistration);
assertTrue(filterRegistration assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet"));
.getServletNameMappings()
.contains("echo servlet"));
} }
@Autowired private TestRestTemplate restTemplate; @Autowired
private TestRestTemplate restTemplate;
@Test @Test
public void givenServletFilter_whenGetHello_thenRequestFiltered() { public void givenServletFilter_whenGetHello_thenRequestFiltered() {
@ -58,8 +58,4 @@ public class SpringBootWithServletComponentIntegrationTest {
assertEquals("filtering echo", responseEntity.getBody()); assertEquals("filtering echo", responseEntity.getBody());
} }
} }

View File

@ -22,9 +22,11 @@ import static org.junit.Assert.*;
@TestPropertySource(properties = { "security.basic.enabled=false" }) @TestPropertySource(properties = { "security.basic.enabled=false" })
public class SpringBootWithoutServletComponentIntegrationTest { public class SpringBootWithoutServletComponentIntegrationTest {
@Autowired private ServletContext servletContext; @Autowired
private ServletContext servletContext;
@Autowired private TestRestTemplate restTemplate; @Autowired
private TestRestTemplate restTemplate;
@Test @Test
public void givenServletContext_whenAccessAttrs_thenNotFound() { public void givenServletContext_whenAccessAttrs_thenNotFound() {
@ -46,5 +48,3 @@ public class SpringBootWithoutServletComponentIntegrationTest {
} }
} }

View File

@ -26,16 +26,12 @@ public class AppLiveTest {
@Test @Test
public void getIndex() throws Exception { public void getIndex() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page")));
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Index Page")));
} }
@Test @Test
public void getLocal() throws Exception { public void getLocal() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)) mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local")));
.andExpect(status().isOk())
.andExpect(content().string(equalTo("/local")));
} }
} }

View File

@ -10,32 +10,26 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.baeldung.utils.controller.UtilsController; import com.baeldung.utils.controller.UtilsController;
public class UtilsControllerIntegrationTest { public class UtilsControllerIntegrationTest {
@InjectMocks @InjectMocks
private UtilsController utilsController; private UtilsController utilsController;
private MockMvc mockMvc; private MockMvc mockMvc;
@Before @Before
public void setup() { public void setup() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build();
.build();
} }
@Test @Test
public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception {
String param = "testparam"; String param = "testparam";
this.mockMvc.perform( this.mockMvc.perform(post("/setParam").param("param", param).sessionAttr("parameter", param)).andExpect(status().isOk());
post("/setParam")
.param("param", param)
.sessionAttr("parameter", param))
.andExpect(status().isOk());
} }
} }

View File

@ -9,8 +9,6 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
import org.subethamail.wiser.Wiser; import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage; import org.subethamail.wiser.WiserMessage;

View File

@ -23,9 +23,7 @@ import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest( @SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
classes = DemoApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT)
public class FooComponentIntegrationTest { public class FooComponentIntegrationTest {
@Autowired @Autowired

View File

@ -1,4 +1,5 @@
package org.baeldung.boot; package org.baeldung.boot;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -16,28 +17,27 @@ import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes=DemoApplication.class,webEnvironment = WebEnvironment.RANDOM_PORT) @SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class FooIntegrationTest { public class FooIntegrationTest {
@Autowired @Autowired
private TestRestTemplate testRestTemplate; private TestRestTemplate testRestTemplate;
@Test @Test
public void givenInquiryingFooWithId_whenIdIsValid_thenHttpStatusOK(){ public void givenInquiryingFooWithId_whenIdIsValid_thenHttpStatusOK() {
Map<String,String> pathVariables = new HashMap<String,String>(); Map<String, String> pathVariables = new HashMap<String, String>();
pathVariables.put("id", "1"); pathVariables.put("id", "1");
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables); ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables);
Assert.assertNotNull(fooResponse); Assert.assertNotNull(fooResponse);
Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode()); Assert.assertEquals(HttpStatus.OK, fooResponse.getStatusCode());
} }
@Test @Test
public void givenInquiryingFooWithName_whenNameIsValid_thenHttpStatusOK(){ public void givenInquiryingFooWithName_whenNameIsValid_thenHttpStatusOK() {
Map<String,String> pathVariables = new HashMap<String,String>(); Map<String, String> pathVariables = new HashMap<String, String>();
pathVariables.put("name", "Foo_Name"); pathVariables.put("name", "Foo_Name");
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables); ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables);
Assert.assertNotNull(fooResponse); Assert.assertNotNull(fooResponse);
Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode()); Assert.assertEquals(HttpStatus.OK, fooResponse.getStatusCode());
} }
} }

View File

@ -27,8 +27,8 @@ public class FooJPAIntegrationTest {
this.entityManager.persist(new Foo("Foo_Name_2")); this.entityManager.persist(new Foo("Foo_Name_2"));
Foo foo = this.repository.findByName("Foo_Name_2"); Foo foo = this.repository.findByName("Foo_Name_2");
assertNotNull(foo); assertNotNull(foo);
assertEquals("Foo_Name_2",foo.getName()); assertEquals("Foo_Name_2", foo.getName());
// Due to having Insert query for Foo with Id 1, so TestEntityManager generates new Id of 2 // Due to having Insert query for Foo with Id 1, so TestEntityManager generates new Id of 2
assertEquals(2l,foo.getId().longValue()); assertEquals(2l, foo.getId().longValue());
} }
} }

View File

@ -16,7 +16,6 @@ public class FooJsonIntegrationTest {
@Autowired @Autowired
private JacksonTester<Foo> json; private JacksonTester<Foo> json;
@Test @Test
public void testSerialize() throws Exception { public void testSerialize() throws Exception {
@ -30,6 +29,6 @@ public class FooJsonIntegrationTest {
public void testDeserialize() throws Exception { public void testDeserialize() throws Exception {
String content = "{\"id\":4,\"name\":\"Foo_Name_4\"}"; String content = "{\"id\":4,\"name\":\"Foo_Name_4\"}";
assertThat(this.json.parseObject(content).getName()).isEqualTo("Foo_Name_4"); assertThat(this.json.parseObject(content).getName()).isEqualTo("Foo_Name_4");
assertThat(this.json.parseObject(content).getId()==4); assertThat(this.json.parseObject(content).getId() == 4);
} }
} }