Update formatting of spring-boot-samples

This commit is contained in:
Andy Wilkinson 2019-06-08 08:16:27 +01:00
parent da1d4b8c3b
commit 9d28238598
167 changed files with 745 additions and 1172 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -33,10 +33,9 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
return new InMemoryUserDetailsManager(
User.withDefaultPasswordEncoder().username("user").password("password")
.authorities("ROLE_USER").build(),
User.withDefaultPasswordEncoder().username("beans").password("beans")
.authorities("ROLE_BEANS").build(),
User.withDefaultPasswordEncoder().username("user").password("password").authorities("ROLE_USER")
.build(),
User.withDefaultPasswordEncoder().username("beans").password("beans").authorities("ROLE_BEANS").build(),
User.withDefaultPasswordEncoder().username("admin").password("admin")
.authorities("ROLE_ACTUATOR", "ROLE_USER").build());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -55,37 +55,31 @@ public class CorsSampleActuatorApplicationTests {
@Before
public void setUp() {
RestTemplateBuilder builder = new RestTemplateBuilder();
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
this.applicationContext.getEnvironment(), "http");
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(this.applicationContext.getEnvironment(),
"http");
builder = builder.uriTemplateHandler(handler);
this.testRestTemplate = new TestRestTemplate(builder);
}
@Test
public void endpointShouldReturnUnauthorized() {
ResponseEntity<?> entity = this.testRestTemplate.getForEntity("/actuator/env",
Map.class);
ResponseEntity<?> entity = this.testRestTemplate.getForEntity("/actuator/env", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void preflightRequestToEndpointShouldReturnOk() throws Exception {
RequestEntity<?> healthRequest = RequestEntity.options(new URI("/actuator/env"))
.header("Origin", "http://localhost:8080")
.header("Access-Control-Request-Method", "GET").build();
ResponseEntity<?> exchange = this.testRestTemplate.exchange(healthRequest,
Map.class);
.header("Origin", "http://localhost:8080").header("Access-Control-Request-Method", "GET").build();
ResponseEntity<?> exchange = this.testRestTemplate.exchange(healthRequest, Map.class);
assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden()
throws Exception {
public void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception {
RequestEntity<?> entity = RequestEntity.options(new URI("/actuator/env"))
.header("Origin", "http://localhost:9095")
.header("Access-Control-Request-Method", "GET").build();
ResponseEntity<byte[]> exchange = this.testRestTemplate.exchange(entity,
byte[].class);
.header("Origin", "http://localhost:9095").header("Access-Control-Request-Method", "GET").build();
ResponseEntity<byte[]> exchange = this.testRestTemplate.exchange(entity, byte[].class);
assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}

View File

@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0",
"management.server.servlet.context-path=/management" })
properties = { "management.server.port=0", "management.server.servlet.context-path=/management" })
public class ManagementPortAndPathSampleActuatorApplicationTests {
@LocalServerPort
@ -58,17 +57,15 @@ public class ManagementPortAndPathSampleActuatorApplicationTests {
@Test
public void testSecureActuator() {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.managementPort + "/management/actuator/env",
String.class);
ResponseEntity<String> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/management/actuator/env", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void testInsecureActuator() {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.managementPort + "/management/actuator/health",
String.class);
ResponseEntity<String> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/management/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}
@ -76,8 +73,7 @@ public class ManagementPortAndPathSampleActuatorApplicationTests {
@Test
public void testMissing() {
ResponseEntity<String> entity = new TestRestTemplate("admin", "admin")
.getForEntity("http://localhost:" + this.managementPort
+ "/management/actuator/missing", String.class);
.getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(entity.getBody()).contains("\"status\":404");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -61,30 +61,26 @@ public class SampleActuatorCustomSecurityApplicationTests {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat((String) body.get("message"))
.contains("Expected exception in controller");
assertThat((String) body.get("message")).contains("Expected exception in controller");
}
@Test
public void testInsecureStaticResources() {
ResponseEntity<String> entity = restTemplate()
.getForEntity("/css/bootstrap.min.css", String.class);
ResponseEntity<String> entity = restTemplate().getForEntity("/css/bootstrap.min.css", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("body");
}
@Test
public void actuatorInsecureEndpoint() {
ResponseEntity<String> entity = restTemplate().getForEntity("/actuator/health",
String.class);
ResponseEntity<String> entity = restTemplate().getForEntity("/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}
@Test
public void actuatorLinksIsSecure() {
ResponseEntity<Object> entity = restTemplate().getForEntity("/actuator",
Object.class);
ResponseEntity<Object> entity = restTemplate().getForEntity("/actuator", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
entity = adminRestTemplate().getForEntity("/actuator", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@ -92,43 +88,40 @@ public class SampleActuatorCustomSecurityApplicationTests {
@Test
public void actuatorSecureEndpointWithAnonymous() {
ResponseEntity<Object> entity = restTemplate().getForEntity("/actuator/env",
Object.class);
ResponseEntity<Object> entity = restTemplate().getForEntity("/actuator/env", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void actuatorSecureEndpointWithUnauthorizedUser() {
ResponseEntity<Object> entity = userRestTemplate().getForEntity("/actuator/env",
Object.class);
ResponseEntity<Object> entity = userRestTemplate().getForEntity("/actuator/env", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
public void actuatorSecureEndpointWithAuthorizedUser() {
ResponseEntity<Object> entity = adminRestTemplate().getForEntity("/actuator/env",
Object.class);
ResponseEntity<Object> entity = adminRestTemplate().getForEntity("/actuator/env", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void actuatorCustomMvcSecureEndpointWithAnonymous() {
ResponseEntity<String> entity = restTemplate()
.getForEntity("/actuator/example/echo?text={t}", String.class, "test");
ResponseEntity<String> entity = restTemplate().getForEntity("/actuator/example/echo?text={t}", String.class,
"test");
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void actuatorCustomMvcSecureEndpointWithUnauthorizedUser() {
ResponseEntity<String> entity = userRestTemplate()
.getForEntity("/actuator/example/echo?text={t}", String.class, "test");
ResponseEntity<String> entity = userRestTemplate().getForEntity("/actuator/example/echo?text={t}", String.class,
"test");
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
public void actuatorCustomMvcSecureEndpointWithAuthorizedUser() {
ResponseEntity<String> entity = adminRestTemplate()
.getForEntity("/actuator/example/echo?text={t}", String.class, "test");
ResponseEntity<String> entity = adminRestTemplate().getForEntity("/actuator/example/echo?text={t}",
String.class, "test");
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).isEqualTo("test");
assertThat(entity.getHeaders().getFirst("echo")).isEqualTo("test");
@ -136,15 +129,13 @@ public class SampleActuatorCustomSecurityApplicationTests {
@Test
public void actuatorExcludedFromEndpointRequestMatcher() {
ResponseEntity<Object> entity = userRestTemplate()
.getForEntity("/actuator/mappings", Object.class);
ResponseEntity<Object> entity = userRestTemplate().getForEntity("/actuator/mappings", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void mvcMatchersCanBeUsedToSecureActuators() {
ResponseEntity<Object> entity = beansRestTemplate()
.getForEntity("/actuator/beans", Object.class);
ResponseEntity<Object> entity = beansRestTemplate().getForEntity("/actuator/beans", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
entity = beansRestTemplate().getForEntity("/actuator/beans/", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@ -167,8 +158,7 @@ public class SampleActuatorCustomSecurityApplicationTests {
}
private TestRestTemplate configure(TestRestTemplate restTemplate) {
restTemplate
.setUriTemplateHandler(new LocalHostUriTemplateHandler(this.environment));
restTemplate.setUriTemplateHandler(new LocalHostUriTemplateHandler(this.environment));
return restTemplate;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -48,8 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@AutoConfigureMockMvc
public class SampleActuatorLog4J2ApplicationTests {
private static final Logger logger = LogManager
.getLogger(SampleActuatorLog4J2ApplicationTests.class);
private static final Logger logger = LogManager.getLogger(SampleActuatorLog4J2ApplicationTests.class);
@Rule
public OutputCapture output = new OutputCapture();
@ -65,12 +64,9 @@ public class SampleActuatorLog4J2ApplicationTests {
@Test
public void validateLoggersEndpoint() throws Exception {
this.mvc.perform(
get("/actuator/loggers/org.apache.coyote.http11.Http11NioProtocol")
.header("Authorization", "Basic " + getBasicAuth()))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("{\"configuredLevel\":\"WARN\","
+ "\"effectiveLevel\":\"WARN\"}")));
this.mvc.perform(get("/actuator/loggers/org.apache.coyote.http11.Http11NioProtocol").header("Authorization",
"Basic " + getBasicAuth())).andExpect(status().isOk()).andExpect(
content().string(equalTo("{\"configuredLevel\":\"WARN\"," + "\"effectiveLevel\":\"WARN\"}")));
}
private String getBasicAuth() {

View File

@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port:0" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port:0" })
public class SampleActuatorUiApplicationPortTests {
@LocalServerPort
@ -50,26 +49,23 @@ public class SampleActuatorUiApplicationPortTests {
@Test
public void testHome() {
ResponseEntity<String> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port, String.class);
ResponseEntity<String> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port,
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void testMetrics() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.managementPort + "/actuator/metrics",
Map.class);
ResponseEntity<Map> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate()
.withBasicAuth("user", getPassword()).getForEntity(
"http://localhost:" + this.managementPort + "/actuator/health",
String.class);
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -52,17 +52,15 @@ public class SampleActuatorUiApplicationTests {
public void testHome() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword()).exchange("/", HttpMethod.GET,
new HttpEntity<Void>(headers), String.class);
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/",
HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("<title>Hello");
}
@Test
public void testCss() {
ResponseEntity<String> entity = this.restTemplate
.getForEntity("/css/bootstrap.min.css", String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("body");
}
@ -70,8 +68,7 @@ public class SampleActuatorUiApplicationTests {
@Test
public void testMetrics() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics",
Map.class);
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@ -79,9 +76,8 @@ public class SampleActuatorUiApplicationTests {
public void testError() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword()).exchange("/error", HttpMethod.GET,
new HttpEntity<Void>(headers), String.class);
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/error",
HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(entity.getBody()).contains("<html>").contains("<body>")
.contains("Please contact the operator with the above information");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,8 +45,7 @@ public class SampleController {
@GetMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String, String> hello() {
return Collections.singletonMap("message",
this.helloWorldService.getHelloMessage());
return Collections.singletonMap("message", this.helloWorldService.getHelloMessage());
}
@PostMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -48,8 +48,8 @@ public class EndpointsPropertiesSampleActuatorApplicationTests {
@Test
public void testCustomErrorPath() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword()).getForEntity("/oops", Map.class);
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/oops",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -59,8 +59,7 @@ public class EndpointsPropertiesSampleActuatorApplicationTests {
@Test
public void testCustomContextPath() {
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/admin/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");

View File

@ -38,9 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0", "management.server.address=127.0.0.1",
"management.server.servlet.context-path:/admin" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=0",
"management.server.address=127.0.0.1", "management.server.servlet.context-path:/admin" })
public class ManagementAddressActuatorApplicationTests {
@LocalServerPort
@ -52,16 +51,14 @@ public class ManagementAddressActuatorApplicationTests {
@Test
public void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port, Map.class);
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port, Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate()
.withBasicAuth("user", getPassword()).getForEntity("http://localhost:"
+ this.managementPort + "/admin/actuator/health", String.class);
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/admin/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}

View File

@ -46,8 +46,7 @@ public class ManagementPathSampleActuatorApplicationTests {
@Test
public void testHealth() {
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/admin/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");

View File

@ -40,10 +40,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0",
"management.endpoints.web.base-path=/admin",
"management.endpoint.health.show-details=never" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=0",
"management.endpoints.web.base-path=/admin", "management.endpoint.health.show-details=never" })
public class ManagementPortAndPathSampleActuatorApplicationTests {
@LocalServerPort
@ -70,17 +68,15 @@ public class ManagementPortAndPathSampleActuatorApplicationTests {
public void testMetrics() {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.managementPort + "/admin/metrics", Map.class);
ResponseEntity<Map> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate()
.withBasicAuth("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/admin/health",
String.class);
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\"}");
}
@ -89,19 +85,15 @@ public class ManagementPortAndPathSampleActuatorApplicationTests {
public void testEnvNotFound() {
String unknownProperty = "test-does-not-exist";
assertThat(this.environment.containsProperty(unknownProperty)).isFalse();
ResponseEntity<String> entity = new TestRestTemplate()
.withBasicAuth("user", getPassword()).getForEntity("http://localhost:"
+ this.managementPort + "/admin/env/" + unknownProperty,
String.class);
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword()).getForEntity(
"http://localhost:" + this.managementPort + "/admin/env/" + unknownProperty, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
@Test
public void testMissing() {
ResponseEntity<String> entity = new TestRestTemplate("user", getPassword())
.getForEntity(
"http://localhost:" + this.managementPort + "/admin/missing",
String.class);
.getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(entity.getBody()).contains("\"status\":404");
}
@ -121,8 +113,7 @@ public class ManagementPortAndPathSampleActuatorApplicationTests {
public void testManagementErrorPage() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/error",
Map.class);
.getForEntity("http://localhost:" + this.managementPort + "/error", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -38,8 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {
"management.server.port=0", "management.endpoint.health.show-details=always" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0", "management.endpoint.health.show-details=always" })
public class ManagementPortSampleActuatorApplicationTests {
@LocalServerPort
@ -63,18 +63,15 @@ public class ManagementPortSampleActuatorApplicationTests {
public void testMetrics() {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.managementPort + "/actuator/metrics",
Map.class);
ResponseEntity<Map> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate()
.withBasicAuth("user", getPassword()).getForEntity(
"http://localhost:" + this.managementPort + "/actuator/health",
String.class);
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
assertThat(entity.getBody()).contains("\"example\"");
@ -85,8 +82,7 @@ public class ManagementPortSampleActuatorApplicationTests {
public void testErrorPage() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/error",
Map.class);
.getForEntity("http://localhost:" + this.managementPort + "/error", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();

View File

@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=-1" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=-1" })
public class NoManagementSampleActuatorApplicationTests {
@Autowired
@ -47,8 +46,8 @@ public class NoManagementSampleActuatorApplicationTests {
@Test
public void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword()).getForEntity("/", Map.class);
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -59,8 +58,8 @@ public class NoManagementSampleActuatorApplicationTests {
public void testMetricsNotAvailable() {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword()).getForEntity("/metrics", Map.class);
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/metrics",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -69,8 +69,7 @@ public class SampleActuatorApplicationTests {
@Test
public void testMetricsIsSecure() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics",
Map.class);
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
entity = this.restTemplate.getForEntity("/actuator/metrics/", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
@ -83,8 +82,8 @@ public class SampleActuatorApplicationTests {
@Test
public void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword()).getForEntity("/", Map.class);
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -96,8 +95,7 @@ public class SampleActuatorApplicationTests {
public void testMetrics() {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
Map<String, Object> body = entity.getBody();
@ -109,8 +107,7 @@ public class SampleActuatorApplicationTests {
@Test
public void testEnv() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/env", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
@ -120,8 +117,7 @@ public class SampleActuatorApplicationTests {
@Test
public void testHealth() {
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
@ -130,23 +126,19 @@ public class SampleActuatorApplicationTests {
@Test
public void testInfo() {
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/info", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody())
.contains("\"artifact\":\"spring-boot-sample-actuator\"");
assertThat(entity.getBody()).contains("\"artifact\":\"spring-boot-sample-actuator\"");
assertThat(entity.getBody()).contains("\"someKey\":\"someValue\"");
assertThat(entity.getBody()).contains("\"java\":{", "\"source\":\"1.8\"",
"\"target\":\"1.8\"");
assertThat(entity.getBody()).contains("\"encoding\":{", "\"source\":\"UTF-8\"",
"\"reporting\":\"UTF-8\"");
assertThat(entity.getBody()).contains("\"java\":{", "\"source\":\"1.8\"", "\"target\":\"1.8\"");
assertThat(entity.getBody()).contains("\"encoding\":{", "\"source\":\"UTF-8\"", "\"reporting\":\"UTF-8\"");
}
@Test
public void testErrorPage() {
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword()).getForEntity("/foo", String.class);
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/foo",
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
String body = entity.getBody();
assertThat(body).contains("\"error\":");
@ -157,9 +149,8 @@ public class SampleActuatorApplicationTests {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
HttpEntity<?> request = new HttpEntity<Void>(headers);
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword())
.exchange("/foo", HttpMethod.GET, request, String.class);
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/foo",
HttpMethod.GET, request, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
String body = entity.getBody();
assertThat(body).as("Body was null").isNotNull();
@ -169,8 +160,8 @@ public class SampleActuatorApplicationTests {
@Test
public void testErrorPageDirectAccess() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword()).getForEntity("/error", Map.class);
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/error",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -182,8 +173,7 @@ public class SampleActuatorApplicationTests {
@SuppressWarnings("unchecked")
public void testBeans() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/beans", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).containsOnlyKeys("contexts");
@ -193,17 +183,14 @@ public class SampleActuatorApplicationTests {
@Test
public void testConfigProps() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/configprops", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
Map<String, Object> body = entity.getBody();
Map<String, Object> contexts = (Map<String, Object>) body.get("contexts");
Map<String, Object> context = (Map<String, Object>) contexts
.get(this.applicationContext.getId());
Map<String, Object> context = (Map<String, Object>) contexts.get(this.applicationContext.getId());
Map<String, Object> beans = (Map<String, Object>) context.get("beans");
assertThat(beans)
.containsKey("spring.datasource-" + DataSourceProperties.class.getName());
assertThat(beans).containsKey("spring.datasource-" + DataSourceProperties.class.getName());
}
private String getPassword() {

View File

@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "server.servlet.path=/spring" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.servlet.path=/spring" })
public class ServletPathSampleActuatorApplicationTests {
@Autowired
@ -47,8 +46,7 @@ public class ServletPathSampleActuatorApplicationTests {
@Test
public void testErrorPath() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/spring/error", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@SuppressWarnings("unchecked")
@ -59,8 +57,7 @@ public class ServletPathSampleActuatorApplicationTests {
@Test
public void testHealth() {
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/spring/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
@ -69,8 +66,7 @@ public class ServletPathSampleActuatorApplicationTests {
@Test
public void testHomeIsSecure() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/",
Map.class);
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();

View File

@ -41,10 +41,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = { ShutdownSampleActuatorApplicationTests.SecurityConfiguration.class,
SampleActuatorApplication.class },
webEnvironment = WebEnvironment.RANDOM_PORT)
@SpringBootTest(classes = { ShutdownSampleActuatorApplicationTests.SecurityConfiguration.class,
SampleActuatorApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
public class ShutdownSampleActuatorApplicationTests {
@Autowired
@ -53,8 +51,8 @@ public class ShutdownSampleActuatorApplicationTests {
@Test
public void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword()).getForEntity("/", Map.class);
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -65,8 +63,7 @@ public class ShutdownSampleActuatorApplicationTests {
@DirtiesContext
public void testShutdown() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate
.withBasicAuth("user", getPassword())
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.postForEntity("/actuator/shutdown", null, Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -48,12 +48,10 @@ public class SampleAntApplicationIT {
});
assertThat(jarFiles).hasSize(1);
Process process = new JavaExecutable()
.processBuilder("-jar", jarFiles[0].getName()).directory(target).start();
Process process = new JavaExecutable().processBuilder("-jar", jarFiles[0].getName()).directory(target).start();
process.waitFor(5, TimeUnit.MINUTES);
assertThat(process.exitValue()).isEqualTo(0);
String output = FileCopyUtils
.copyToString(new InputStreamReader(process.getInputStream()));
String output = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream()));
assertThat(output).contains("Spring Boot Ant Example");
}

View File

@ -48,13 +48,11 @@ public class ChatService {
@org.atmosphere.config.service.Message(encoders = JacksonEncoderDecoder.class,
decoders = JacksonEncoderDecoder.class)
public Message onMessage(Message message) throws IOException {
this.logger.info("Author {} sent message {}", message.getAuthor(),
message.getMessage());
this.logger.info("Author {} sent message {}", message.getAuthor(), message.getMessage());
return message;
}
public static class JacksonEncoderDecoder
implements Encoder<Message, String>, Decoder<String, Message> {
public static class JacksonEncoderDecoder implements Encoder<Message, String>, Decoder<String, Message> {
private final ObjectMapper mapper = new ObjectMapper();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -48,11 +48,11 @@ public class SampleAtmosphereApplication {
public ServletRegistrationBean<AtmosphereServlet> atmosphereServlet() {
// Dispatcher servlet is mapped to '/home' to allow the AtmosphereServlet
// to be mapped to '/chat'
ServletRegistrationBean<AtmosphereServlet> registration = new ServletRegistrationBean<>(
new AtmosphereServlet(), "/chat/*");
ServletRegistrationBean<AtmosphereServlet> registration = new ServletRegistrationBean<>(new AtmosphereServlet(),
"/chat/*");
registration.addInitParameter("org.atmosphere.cpr.packages", "sample");
registration.addInitParameter("org.atmosphere.interceptor.HeartbeatInterceptor"
+ ".clientHeartbeatFrequencyInSeconds", "10");
registration.addInitParameter(
"org.atmosphere.interceptor.HeartbeatInterceptor" + ".clientHeartbeatFrequencyInSeconds", "10");
registration.setLoadOnStartup(0);
// Need to occur before the EmbeddedAtmosphereInitializer
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);

View File

@ -45,8 +45,7 @@ import org.springframework.web.socket.handler.TextWebSocketHandler;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SampleAtmosphereApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT)
@SpringBootTest(classes = SampleAtmosphereApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class SampleAtmosphereApplicationTests {
private static Log logger = LogFactory.getLog(SampleAtmosphereApplicationTests.class);
@ -56,18 +55,15 @@ public class SampleAtmosphereApplicationTests {
@Test
public void chatEndpoint() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class)
.properties("websocket.uri:ws://localhost:" + this.port
+ "/chat/websocket")
ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class,
PropertyPlaceholderAutoConfiguration.class)
.properties("websocket.uri:ws://localhost:" + this.port + "/chat/websocket")
.run("--spring.main.web-application-type=none");
long count = context.getBean(ClientConfiguration.class).latch.getCount();
AtomicReference<String> messagePayloadReference = context
.getBean(ClientConfiguration.class).messagePayload;
AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload;
context.close();
assertThat(count).isEqualTo(0L);
assertThat(messagePayloadReference.get())
.contains("{\"message\":\"test\",\"author\":\"test\",\"time\":");
assertThat(messagePayloadReference.get()).contains("{\"message\":\"test\",\"author\":\"test\",\"time\":");
}
@Configuration
@ -93,8 +89,7 @@ public class SampleAtmosphereApplicationTests {
@Bean
public WebSocketConnectionManager wsConnectionManager() {
WebSocketConnectionManager manager = new WebSocketConnectionManager(client(),
handler(), this.webSocketUri);
WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri);
manager.setAutoStartup(true);
return manager;
}
@ -109,17 +104,13 @@ public class SampleAtmosphereApplicationTests {
return new TextWebSocketHandler() {
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {
session.sendMessage(new TextMessage(
"{\"author\":\"test\",\"message\":\"test\"}"));
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
session.sendMessage(new TextMessage("{\"author\":\"test\",\"message\":\"test\"}"));
}
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
logger.info("Received: " + message + " ("
+ ClientConfiguration.this.latch.getCount() + ")");
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
logger.info("Received: " + message + " (" + ClientConfiguration.this.latch.getCount() + ")");
session.close();
ClientConfiguration.this.messagePayload.set(message.getPayload());
ClientConfiguration.this.latch.countDown();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,8 +45,7 @@ public class SampleBatchApplication {
return new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution,
ChunkContext context) {
public RepeatStatus execute(StepContribution contribution, ChunkContext context) {
return RepeatStatus.FINISHED;
}
};
@ -66,8 +65,7 @@ public class SampleBatchApplication {
public static void main(String[] args) {
// System.exit is common for Batch applications since the exit code can be used to
// drive a workflow
System.exit(SpringApplication
.exit(SpringApplication.run(SampleBatchApplication.class, args)));
System.exit(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class, args)));
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -31,8 +31,7 @@ public class SampleBatchApplicationTests {
@Test
public void testDefaultSettings() {
assertThat(SpringApplication
.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0);
assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0);
String output = this.outputCapture.toString();
assertThat(output).contains("completed with the following parameters");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -36,8 +36,8 @@ public class CacheManagerCheck implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
logger.info("\n\n" + "=========================================================\n"
+ "Using cache manager: " + this.cacheManager.getClass().getName() + "\n"
logger.info("\n\n" + "=========================================================\n" + "Using cache manager: "
+ this.cacheManager.getClass().getName() + "\n"
+ "=========================================================\n\n");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,8 +27,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
public class SampleCacheApplication {
public static void main(String[] args) {
new SpringApplicationBuilder().sources(SampleCacheApplication.class)
.profiles("app").run(args);
new SpringApplicationBuilder().sources(SampleCacheApplication.class).profiles("app").run(args);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,26 +28,21 @@ import org.springframework.stereotype.Component;
@Profile("app")
class SampleClient {
private static final List<String> SAMPLE_COUNTRY_CODES = Arrays.asList("AF", "AX",
"AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT",
"AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BQ",
"BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV",
"KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR",
"CI", "HR", "CU", "CW", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG", "SV",
"GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", "GA",
"GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN",
"GW", "GY", "HT", "HM", "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ",
"IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KP", "KR",
"KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK",
"MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM",
"MD", "MC", "MN", "ME", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "NC",
"NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", "PS", "PA",
"PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW",
"BL", "SH", "KN", "LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS",
"SC", "SL", "SG", "SX", "SK", "SI", "SB", "SO", "ZA", "GS", "SS", "ES", "LK",
"SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG",
"TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US",
"UM", "UY", "UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW");
private static final List<String> SAMPLE_COUNTRY_CODES = Arrays.asList("AF", "AX", "AL", "DZ", "AS", "AD", "AO",
"AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM",
"BT", "BO", "BQ", "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF",
"TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CI", "HR", "CU", "CW", "CY", "CZ", "DK",
"DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF",
"GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM",
"VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ",
"KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG",
"MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA",
"MZ", "MM", "NA", "NR", "NP", "NL", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW",
"PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "BL", "SH", "KN",
"LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SG", "SX", "SK", "SI", "SB", "SO",
"ZA", "GS", "SS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG",
"TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY", "UZ", "VU", "VE",
"VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW");
private final CountryRepository countryService;
@ -60,8 +55,7 @@ class SampleClient {
@Scheduled(fixedDelay = 500)
public void retrieveCountry() {
String randomCode = SAMPLE_COUNTRY_CODES
.get(this.random.nextInt(SAMPLE_COUNTRY_CODES.size()));
String randomCode = SAMPLE_COUNTRY_CODES.get(this.random.nextInt(SAMPLE_COUNTRY_CODES.size()));
System.out.println("Looking for country with code '" + randomCode + "'");
this.countryService.findByCode(randomCode);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -42,8 +42,7 @@ public class Customer {
@Override
public String toString() {
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id,
this.firstName, this.lastName);
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,11 +22,9 @@ import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
public class OrderedCassandraTestExecutionListener
extends CassandraUnitDependencyInjectionTestExecutionListener {
public class OrderedCassandraTestExecutionListener extends CassandraUnitDependencyInjectionTestExecutionListener {
private static final Logger logger = LoggerFactory
.getLogger(OrderedCassandraTestExecutionListener.class);
private static final Logger logger = LoggerFactory.getLogger(OrderedCassandraTestExecutionListener.class);
@Override
public int getOrder() {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -59,8 +59,8 @@ public class User {
@Override
public String toString() {
return "User{" + "id='" + this.id + '\'' + ", firstName='" + this.firstName + '\''
+ ", lastName='" + this.lastName + '\'' + '}';
return "User{" + "id='" + this.id + '\'' + ", firstName='" + this.firstName + '\'' + ", lastName='"
+ this.lastName + '\'' + '}';
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -34,8 +34,7 @@ public class SampleCouchbaseApplicationTests {
@Test
public void testDefaultSettings() {
try {
new SpringApplicationBuilder(SampleCouchbaseApplication.class)
.run("--server.port=0");
new SpringApplicationBuilder(SampleCouchbaseApplication.class).run("--server.port=0");
}
catch (RuntimeException ex) {
if (serverNotRunning(ex)) {

View File

@ -19,8 +19,7 @@ package sample.data.elasticsearch;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "customer", type = "customer", shards = 1, replicas = 0,
refreshInterval = "-1")
@Document(indexName = "customer", type = "customer", shards = 1, replicas = 0, refreshInterval = "-1")
public class Customer {
@Id
@ -64,8 +63,7 @@ public class Customer {
@Override
public String toString() {
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id,
this.firstName, this.lastName);
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName);
}
}

View File

@ -30,8 +30,7 @@ public class City implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "city_generator", sequenceName = "city_sequence",
initialValue = 23)
@SequenceGenerator(name = "city_generator", sequenceName = "city_sequence", initialValue = 23)
@GeneratedValue(generator = "city_generator")
private Long id;

View File

@ -36,8 +36,7 @@ public class Hotel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "hotel_generator", sequenceName = "hotel_sequence",
initialValue = 28)
@SequenceGenerator(name = "hotel_generator", sequenceName = "hotel_sequence", initialValue = 28)
@GeneratedValue(generator = "hotel_generator")
private Long id;

View File

@ -38,8 +38,7 @@ public class Review implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "review_generator", sequenceName = "review_sequence",
initialValue = 64)
@SequenceGenerator(name = "review_generator", sequenceName = "review_sequence", initialValue = 64)
@GeneratedValue(generator = "review_generator")
private Long id;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -26,8 +26,7 @@ interface CityRepository extends Repository<City, Long> {
Page<City> findAll(Pageable pageable);
Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name,
String country, Pageable pageable);
Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable);
City findByNameAndCountryAllIgnoringCase(String name, String country);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -57,9 +57,8 @@ class CityServiceImpl implements CityService {
name = name.substring(0, splitPos);
}
return this.cityRepository
.findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(),
country.trim(), pageable);
return this.cityRepository.findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(), country.trim(),
pageable);
}
@Override

View File

@ -45,8 +45,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*/
@RunWith(SpringRunner.class)
// Enable JMX so we can test the MBeans (you can't do this in a properties file)
@SpringBootTest(
properties = { "spring.jmx.enabled:true", "spring.datasource.jmx-enabled:true" })
@SpringBootTest(properties = { "spring.jmx.enabled:true", "spring.datasource.jmx-enabled:true" })
@ActiveProfiles("scratch")
// Separate profile for web tests to avoid clashing databases
public class SampleDataJpaApplicationTests {
@ -64,15 +63,13 @@ public class SampleDataJpaApplicationTests {
@Test
public void testHome() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("Bath"));
this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Bath"));
}
@Test
public void testJmx() throws Exception {
assertThat(ManagementFactory.getPlatformMBeanServer()
.queryMBeans(new ObjectName("jpa.sample:type=HikariDataSource,*"), null))
.hasSize(1);
.queryMBeans(new ObjectName("jpa.sample:type=HikariDataSource,*"), null)).hasSize(1);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -51,13 +51,10 @@ public class HotelRepositoryIntegrationTests {
@Test
public void executesQueryMethodsCorrectly() {
City city = this.cityRepository
.findAll(PageRequest.of(0, 1, Direction.ASC, "name")).getContent().get(0);
City city = this.cityRepository.findAll(PageRequest.of(0, 1, Direction.ASC, "name")).getContent().get(0);
assertThat(city.getName()).isEqualTo("Atlanta");
Page<HotelSummary> hotels = this.repository.findByCity(city,
PageRequest.of(0, 10, Direction.ASC, "name"));
Hotel hotel = this.repository.findByCityAndName(city,
hotels.getContent().get(0).getName());
Page<HotelSummary> hotels = this.repository.findByCity(city, PageRequest.of(0, 10, Direction.ASC, "name"));
Hotel hotel = this.repository.findByCityAndName(city, hotels.getContent().get(0).getName());
assertThat(hotel.getName()).isEqualTo("Doubletree");
List<RatingCount> counts = this.repository.findRatingCounts(hotel);
assertThat(counts).hasSize(1);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -37,8 +37,7 @@ public class Customer {
@Override
public String toString() {
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id,
this.firstName, this.lastName);
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -41,8 +41,7 @@ public class Customer {
@Override
public String toString() {
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id,
this.firstName, this.lastName);
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName);
}
}

View File

@ -30,8 +30,7 @@ public class City implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "city_generator", sequenceName = "city_sequence",
initialValue = 23)
@SequenceGenerator(name = "city_generator", sequenceName = "city_sequence", initialValue = 23)
@GeneratedValue(generator = "city_generator")
private Long id;

View File

@ -33,8 +33,7 @@ public class Hotel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "hotel_generator", sequenceName = "hotel_sequence",
initialValue = 28)
@SequenceGenerator(name = "hotel_generator", sequenceName = "hotel_sequence", initialValue = 28)
@GeneratedValue(generator = "hotel_generator")
private Long id;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,11 +27,9 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "cities", path = "cities")
interface CityRepository extends PagingAndSortingRepository<City, Long> {
Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(
@Param("name") String name, @Param("country") String country,
Pageable pageable);
Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(@Param("name") String name,
@Param("country") String country, Pageable pageable);
City findByNameAndCountryAllIgnoringCase(@Param("name") String name,
@Param("country") String country);
City findByNameAndCountryAllIgnoringCase(@Param("name") String name, @Param("country") String country);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -58,25 +58,21 @@ public class SampleDataRestApplicationTests {
@Test
public void testHome() throws Exception {
this.mvc.perform(get("/api")).andExpect(status().isOk())
.andExpect(content().string(containsString("hotels")));
this.mvc.perform(get("/api")).andExpect(status().isOk()).andExpect(content().string(containsString("hotels")));
}
@Test
public void findByNameAndCountry() throws Exception {
this.mvc.perform(get(
"/api/cities/search/findByNameAndCountryAllIgnoringCase?name=Melbourne&country=Australia"))
.andExpect(status().isOk())
.andExpect(jsonPath("state", equalTo("Victoria")))
this.mvc.perform(get("/api/cities/search/findByNameAndCountryAllIgnoringCase?name=Melbourne&country=Australia"))
.andExpect(status().isOk()).andExpect(jsonPath("state", equalTo("Victoria")))
.andExpect(jsonPath("name", equalTo("Melbourne")));
}
@Test
public void findByContaining() throws Exception {
this.mvc.perform(get(
"/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK"))
.andExpect(status().isOk())
.andExpect(jsonPath("_embedded.cities", hasSize(3)));
this.mvc.perform(
get("/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK"))
.andExpect(status().isOk()).andExpect(jsonPath("_embedded.cities", hasSize(3)));
}
}

View File

@ -49,17 +49,15 @@ public class CityRepositoryIntegrationTests {
@Test
public void findByNameAndCountry() {
City city = this.repository.findByNameAndCountryAllIgnoringCase("Melbourne",
"Australia");
City city = this.repository.findByNameAndCountryAllIgnoringCase("Melbourne", "Australia");
assertThat(city).isNotNull();
assertThat(city.getName()).isEqualTo("Melbourne");
}
@Test
public void findContaining() {
Page<City> cities = this.repository
.findByNameContainingAndCountryContainingAllIgnoringCase("", "UK",
PageRequest.of(0, 10));
Page<City> cities = this.repository.findByNameContainingAndCountryContainingAllIgnoringCase("", "UK",
PageRequest.of(0, 10));
assertThat(cities.getTotalElements()).isEqualTo(3L);
}

View File

@ -93,8 +93,8 @@ public class Product {
@Override
public String toString() {
return "Product [id=" + this.id + ", name=" + this.name + ", price=" + this.price
+ ", category=" + this.category + ", location=" + this.location + "]";
return "Product [id=" + this.id + ", name=" + this.name + ", price=" + this.price + ", category="
+ this.category + ", location=" + this.location + "]";
}
}

View File

@ -41,8 +41,7 @@ public class MyController {
sessionVar = new Date();
session.setAttribute("var", sessionVar);
}
ModelMap model = new ModelMap("message", Message.MESSAGE)
.addAttribute("sessionVar", sessionVar);
ModelMap model = new ModelMap("message", Message.MESSAGE).addAttribute("sessionVar", sessionVar);
return new ModelAndView("hello", model);
}

View File

@ -44,24 +44,21 @@ public class SampleDevToolsApplicationIntegrationTests {
@Test
public void testStaticResource() {
ResponseEntity<String> entity = this.restTemplate
.getForEntity("/css/application.css", String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/application.css", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("color: green;");
}
@Test
public void testPublicResource() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/public.txt",
String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/public.txt", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("public file");
}
@Test
public void testClassResource() {
ResponseEntity<String> entity = this.restTemplate
.getForEntity("/application.properties", String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/application.properties", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}

View File

@ -25,8 +25,7 @@ import javax.persistence.SequenceGenerator;
public class Person {
@Id
@SequenceGenerator(name = "person_generator", sequenceName = "person_sequence",
allocationSize = 1)
@SequenceGenerator(name = "person_generator", sequenceName = "person_sequence", allocationSize = 1)
@GeneratedValue(generator = "person_generator")
private Long id;
@ -52,8 +51,7 @@ public class Person {
@Override
public String toString() {
return "Person [firstName=" + this.firstName + ", lastName=" + this.lastName
+ "]";
return "Person [firstName=" + this.firstName + ", lastName=" + this.lastName + "]";
}
}

View File

@ -35,8 +35,7 @@ public class SampleFlywayApplicationTests {
@Test
public void testDefaultSettings() {
assertThat(this.template.queryForObject("SELECT COUNT(*) from PERSON",
Integer.class)).isEqualTo(1);
assertThat(this.template.queryForObject("SELECT COUNT(*) from PERSON", Integer.class)).isEqualTo(1);
}
}

View File

@ -42,11 +42,9 @@ public class SampleHateoasApplicationTests {
@Test
public void hasHalLinks() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/customers/1",
String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/customers/1", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).startsWith(
"{\"id\":1,\"firstName\":\"Oliver\"" + ",\"lastName\":\"Gierke\"");
assertThat(entity.getBody()).startsWith("{\"id\":1,\"firstName\":\"Oliver\"" + ",\"lastName\":\"Gierke\"");
assertThat(entity.getBody()).contains("_links\":{\"self\":{\"href\"");
}
@ -55,8 +53,8 @@ public class SampleHateoasApplicationTests {
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.ACCEPT, "application/xml;q=0.9,application/json;q=0.8");
HttpEntity<?> request = new HttpEntity<>(headers);
ResponseEntity<String> response = this.restTemplate.exchange("/customers/1",
HttpMethod.GET, request, String.class);
ResponseEntity<String> response = this.restTemplate.exchange("/customers/1", HttpMethod.GET, request,
String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getHeaders().getContentType())
.isEqualTo(MediaType.parseMediaType("application/json;charset=UTF-8"));

View File

@ -54,25 +54,22 @@ public class SampleIntegrationApplication {
@Bean
public FileWritingMessageHandler fileWriter() {
FileWritingMessageHandler writer = new FileWritingMessageHandler(
new File("target/output"));
FileWritingMessageHandler writer = new FileWritingMessageHandler(new File("target/output"));
writer.setExpectReply(false);
return writer;
}
@Bean
public IntegrationFlow integrationFlow(SampleEndpoint endpoint) {
return IntegrationFlows.from(fileReader(), new FixedRatePoller())
.channel(inputChannel()).handle(endpoint).channel(outputChannel())
.handle(fileWriter()).get();
return IntegrationFlows.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint)
.channel(outputChannel()).handle(fileWriter()).get();
}
public static void main(String[] args) {
SpringApplication.run(SampleIntegrationApplication.class, args);
}
private static class FixedRatePoller
implements Consumer<SourcePollingChannelAdapterSpec> {
private static class FixedRatePoller implements Consumer<SourcePollingChannelAdapterSpec> {
@Override
public void accept(SourcePollingChannelAdapterSpec spec) {

View File

@ -79,38 +79,34 @@ public class SampleIntegrationApplicationTests {
@Test
public void testMessageGateway() throws Exception {
this.context = SpringApplication.run(SampleIntegrationApplication.class,
"testviamg");
this.context = SpringApplication.run(SampleIntegrationApplication.class, "testviamg");
String output = getOutput();
assertThat(output).contains("testviamg");
}
private String getOutput() throws Exception {
Future<String> future = Executors.newSingleThreadExecutor()
.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Resource[] resources = getResourcesWithContent();
while (resources.length == 0) {
Thread.sleep(200);
resources = getResourcesWithContent();
}
StringBuilder builder = new StringBuilder();
for (Resource resource : resources) {
try (InputStream inputStream = resource.getInputStream()) {
builder.append(new String(
StreamUtils.copyToByteArray(inputStream)));
}
}
return builder.toString();
Future<String> future = Executors.newSingleThreadExecutor().submit(new Callable<String>() {
@Override
public String call() throws Exception {
Resource[] resources = getResourcesWithContent();
while (resources.length == 0) {
Thread.sleep(200);
resources = getResourcesWithContent();
}
StringBuilder builder = new StringBuilder();
for (Resource resource : resources) {
try (InputStream inputStream = resource.getInputStream()) {
builder.append(new String(StreamUtils.copyToByteArray(inputStream)));
}
});
}
return builder.toString();
}
});
return future.get(30, TimeUnit.SECONDS);
}
private Resource[] getResourcesWithContent() throws IOException {
Resource[] candidates = ResourcePatternUtils
.getResourcePatternResolver(new DefaultResourceLoader())
Resource[] candidates = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader())
.getResources("file:target/output/**");
for (Resource candidate : candidates) {
if (candidate.contentLength() == 0) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -30,8 +30,7 @@ public class ProducerApplication implements CommandLineRunner {
public void run(String... args) throws Exception {
new File("target/input").mkdirs();
if (args.length > 0) {
FileOutputStream stream = new FileOutputStream(
"target/input/data" + System.currentTimeMillis() + ".txt");
FileOutputStream stream = new FileOutputStream("target/input/data" + System.currentTimeMillis() + ".txt");
for (String arg : args) {
stream.write(arg.getBytes());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -24,9 +24,7 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
public class SampleJerseyApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
new SampleJerseyApplication()
.configure(new SpringApplicationBuilder(SampleJerseyApplication.class))
.run(args);
new SampleJerseyApplication().configure(new SpringApplicationBuilder(SampleJerseyApplication.class)).run(args);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -38,30 +38,26 @@ public class SampleJerseyApplicationTests {
@Test
public void contextLoads() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/hello",
String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/hello", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void reverse() {
ResponseEntity<String> entity = this.restTemplate
.getForEntity("/reverse?input=olleh", String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse?input=olleh", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).isEqualTo("hello");
}
@Test
public void validation() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse",
String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
public void actuatorStatus() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health",
String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\"}");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -49,14 +49,12 @@ public class SampleJersey1Application {
public FilterRegistrationBean<ServletContainer> jersey() {
FilterRegistrationBean<ServletContainer> bean = new FilterRegistrationBean<>();
bean.setFilter(new ServletContainer());
bean.addInitParameter("com.sun.jersey.config.property.packages",
"com.sun.jersey;sample.jersey1");
bean.addInitParameter("com.sun.jersey.config.property.packages", "com.sun.jersey;sample.jersey1");
return bean;
}
public static void main(String[] args) {
new SpringApplicationBuilder(SampleJersey1Application.class)
.web(WebApplicationType.SERVLET).run(args);
new SpringApplicationBuilder(SampleJersey1Application.class).web(WebApplicationType.SERVLET).run(args);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -36,8 +36,7 @@ public class SampleJersey1ApplicationTests {
@Test
public void rootReturnsHelloWorld() {
assertThat(this.restTemplate.getForObject("/", String.class))
.isEqualTo("Hello World");
assertThat(this.restTemplate.getForObject("/", String.class)).isEqualTo("Hello World");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -62,13 +62,10 @@ public class SampleJettyApplicationTests {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept-Encoding", "gzip");
HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders);
ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET,
requestEntity, byte[].class);
ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
try (GZIPInputStream inflater = new GZIPInputStream(
new ByteArrayInputStream(entity.getBody()))) {
assertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8))
.isEqualTo("Hello World");
try (GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody()))) {
assertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8)).isEqualTo("Hello World");
}
}

View File

@ -62,18 +62,15 @@ public class JooqExamples implements CommandLineRunner {
}
private void jooqSql() {
Query query = this.dsl.select(BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
.from(BOOK).join(AUTHOR).on(BOOK.AUTHOR_ID.equal(AUTHOR.ID))
.where(BOOK.PUBLISHED_IN.equal(2015));
Query query = this.dsl.select(BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME).from(BOOK).join(AUTHOR)
.on(BOOK.AUTHOR_ID.equal(AUTHOR.ID)).where(BOOK.PUBLISHED_IN.equal(2015));
Object[] bind = query.getBindValues().toArray(new Object[0]);
List<String> list = this.jdbc.query(query.getSQL(), bind,
new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString(1) + " : " + rs.getString(2) + " "
+ rs.getString(3);
}
});
List<String> list = this.jdbc.query(query.getSQL(), bind, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString(1) + " : " + rs.getString(2) + " " + rs.getString(3);
}
});
System.out.println("jOOQ SQL " + list);
}

View File

@ -38,9 +38,8 @@ public class SampleJooqApplicationTests {
SampleJooqApplication.main(NO_ARGS);
assertThat(this.out.toString()).contains("jOOQ Fetch 1 Greg Turnquest");
assertThat(this.out.toString()).contains("jOOQ Fetch 2 Craig Walls");
assertThat(this.out.toString())
.contains("jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, "
+ "Spring Boot in Action : Craig Walls]");
assertThat(this.out.toString()).contains(
"jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, " + "Spring Boot in Action : Craig Walls]");
}
}

View File

@ -28,8 +28,7 @@ import javax.persistence.SequenceGenerator;
public class Note {
@Id
@SequenceGenerator(name = "note_generator", sequenceName = "note_sequence",
initialValue = 5)
@SequenceGenerator(name = "note_generator", sequenceName = "note_sequence", initialValue = 5)
@GeneratedValue(generator = "note_generator")
private long id;

View File

@ -28,8 +28,7 @@ import javax.persistence.SequenceGenerator;
public class Tag {
@Id
@SequenceGenerator(name = "tag_generator", sequenceName = "tag_sequence",
initialValue = 4)
@SequenceGenerator(name = "tag_generator", sequenceName = "tag_sequence", initialValue = 4)
@GeneratedValue(generator = "tag_generator")
private long id;

View File

@ -33,8 +33,7 @@ class JpaNoteRepository implements NoteRepository {
@Override
public List<Note> findAll() {
return this.entityManager.createQuery("SELECT n FROM Note n", Note.class)
.getResultList();
return this.entityManager.createQuery("SELECT n FROM Note n", Note.class).getResultList();
}
}

View File

@ -33,8 +33,7 @@ class JpaTagRepository implements TagRepository {
@Override
public List<Tag> findAll() {
return this.entityManager.createQuery("SELECT t FROM Tag t", Tag.class)
.getResultList();
return this.entityManager.createQuery("SELECT t FROM Tag t", Tag.class).getResultList();
}
}

View File

@ -55,8 +55,7 @@ public class SampleJpaApplicationTests {
@Test
public void testHome() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(xpath("//tbody/tr").nodeCount(4));
this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(xpath("//tbody/tr").nodeCount(4));
}
}

View File

@ -26,8 +26,7 @@ import org.springframework.context.ApplicationContext;
public class SampleAtomikosApplication {
public static void main(String[] args) throws Exception {
ApplicationContext context = SpringApplication
.run(SampleAtomikosApplication.class, args);
ApplicationContext context = SpringApplication.run(SampleAtomikosApplication.class, args);
AccountService service = context.getBean(AccountService.class);
AccountRepository repository = context.getBean(AccountRepository.class);
service.createAccountAndNotify("josh");

View File

@ -45,8 +45,7 @@ public class SampleAtomikosApplicationTests {
}
private Condition<String> substring(int times, String substring) {
return new Condition<String>(
"containing '" + substring + "' " + times + " times") {
return new Condition<String>("containing '" + substring + "' " + times + " times") {
@Override
public boolean matches(String value) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -26,8 +26,7 @@ import org.springframework.context.ApplicationContext;
public class SampleBitronixApplication {
public static void main(String[] args) throws Exception {
ApplicationContext context = SpringApplication
.run(SampleBitronixApplication.class, args);
ApplicationContext context = SpringApplication.run(SampleBitronixApplication.class, args);
AccountService service = context.getBean(AccountService.class);
AccountRepository repository = context.getBean(AccountRepository.class);
service.createAccountAndNotify("josh");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -49,20 +49,17 @@ public class SampleBitronixApplicationTests {
@Test
public void testExposesXaAndNonXa() {
ApplicationContext context = SpringApplication
.run(SampleBitronixApplication.class);
ApplicationContext context = SpringApplication.run(SampleBitronixApplication.class);
Object jmsConnectionFactory = context.getBean("jmsConnectionFactory");
Object xaJmsConnectionFactory = context.getBean("xaJmsConnectionFactory");
Object nonXaJmsConnectionFactory = context.getBean("nonXaJmsConnectionFactory");
assertThat(jmsConnectionFactory).isSameAs(xaJmsConnectionFactory);
assertThat(jmsConnectionFactory).isInstanceOf(PoolingConnectionFactory.class);
assertThat(nonXaJmsConnectionFactory)
.isNotInstanceOf(PoolingConnectionFactory.class);
assertThat(nonXaJmsConnectionFactory).isNotInstanceOf(PoolingConnectionFactory.class);
}
private Condition<String> substring(int times, String substring) {
return new Condition<String>(
"containing '" + substring + "' " + times + " times") {
return new Condition<String>("containing '" + substring + "' " + times + " times") {
@Override
public boolean matches(String value) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -26,8 +26,7 @@ import org.springframework.context.ApplicationContext;
public class SampleNarayanaApplication {
public static void main(String[] args) throws Exception {
ApplicationContext context = SpringApplication
.run(SampleNarayanaApplication.class, args);
ApplicationContext context = SpringApplication.run(SampleNarayanaApplication.class, args);
AccountService service = context.getBean(AccountService.class);
AccountRepository repository = context.getBean(AccountRepository.class);
service.createAccountAndNotify("josh");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,8 +45,7 @@ public class SampleNarayanaApplicationTests {
}
private Condition<String> substring(int times, String substring) {
return new Condition<String>(
"containing '" + substring + "' " + times + " times") {
return new Condition<String>("containing '" + substring + "' " + times + " times") {
@Override
public boolean matches(String value) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,8 +25,7 @@ public class SampleMessage {
private final String message;
@JsonCreator
public SampleMessage(@JsonProperty("id") Integer id,
@JsonProperty("message") String message) {
public SampleMessage(@JsonProperty("id") Integer id, @JsonProperty("message") String message) {
this.id = id;
this.message = message;
}

View File

@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
properties = "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}")
@SpringBootTest(properties = "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}")
@EmbeddedKafka
public class SampleKafkaApplicationTests {
@ -52,8 +51,7 @@ public class SampleKafkaApplicationTests {
@Test
public void testVanillaExchange() throws Exception {
assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(this.outputCapture.toString().contains("A simple test message"))
.isTrue();
assertThat(this.outputCapture.toString().contains("A simple test message")).isTrue();
}
@TestConfiguration

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -43,16 +43,12 @@ public class SampleLiquibaseApplicationTests {
}
String output = this.outputCapture.toString();
assertThat(output).contains("Successfully acquired change log lock")
.contains("Creating database history "
+ "table with name: PUBLIC.DATABASECHANGELOG")
.contains("Creating database history " + "table with name: PUBLIC.DATABASECHANGELOG")
.contains("Table person created")
.contains("ChangeSet classpath:/db/"
+ "changelog/db.changelog-master.yaml::1::"
+ "marceloverdijk ran successfully")
.contains("New row inserted into person")
.contains("ChangeSet classpath:/db/changelog/"
+ "db.changelog-master.yaml::2::"
.contains("ChangeSet classpath:/db/" + "changelog/db.changelog-master.yaml::1::"
+ "marceloverdijk ran successfully")
.contains("New row inserted into person").contains("ChangeSet classpath:/db/changelog/"
+ "db.changelog-master.yaml::2::" + "marceloverdijk ran successfully")
.contains("Successfully released change log lock");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,8 +27,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleLogbackApplication {
private static final Logger logger = LoggerFactory
.getLogger(SampleLogbackApplication.class);
private static final Logger logger = LoggerFactory.getLogger(SampleLogbackApplication.class);
@PostConstruct
public void logSomething() {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -38,8 +38,7 @@ public class SampleLogbackApplicationTests {
@Test
public void testProfile() throws Exception {
SampleLogbackApplication
.main(new String[] { "--spring.profiles.active=staging" });
SampleLogbackApplication.main(new String[] { "--spring.profiles.active=staging" });
this.outputCapture.expect(containsString("Sample Debug Message"));
this.outputCapture.expect(containsString("Sample Trace Message"));
}

View File

@ -32,8 +32,8 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
"APP-CLIENT-ID=my-client-id", "APP-CLIENT-SECRET=my-client-secret" })
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = { "APP-CLIENT-ID=my-client-id", "APP-CLIENT-SECRET=my-client-secret" })
public class SampleOAuth2ClientApplicationTests {
@LocalServerPort
@ -46,14 +46,12 @@ public class SampleOAuth2ClientApplicationTests {
public void everythingShouldRedirectToLogin() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND);
assertThat(entity.getHeaders().getLocation())
.isEqualTo(URI.create("http://localhost:" + this.port + "/login"));
assertThat(entity.getHeaders().getLocation()).isEqualTo(URI.create("http://localhost:" + this.port + "/login"));
}
@Test
public void loginShouldHaveBothOAuthClientsToChooseFrom() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/login",
String.class);
ResponseEntity<String> entity = this.restTemplate.getForEntity("/login", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("/oauth2/authorization/github-client-1");
assertThat(entity.getBody()).contains("/oauth2/authorization/github-client-2");

View File

@ -38,8 +38,7 @@ import org.springframework.integration.file.FileWritingMessageHandler;
public class SampleParentContextApplication {
public static void main(String[] args) throws Exception {
new SpringApplicationBuilder(Parent.class)
.child(SampleParentContextApplication.class).run(args);
new SpringApplicationBuilder(Parent.class).child(SampleParentContextApplication.class).run(args);
}
@Configuration
@ -65,21 +64,18 @@ public class SampleParentContextApplication {
@Bean
public FileWritingMessageHandler fileWriter() {
FileWritingMessageHandler writer = new FileWritingMessageHandler(
new File("target/output"));
FileWritingMessageHandler writer = new FileWritingMessageHandler(new File("target/output"));
writer.setExpectReply(false);
return writer;
}
@Bean
public IntegrationFlow integrationFlow(SampleEndpoint endpoint) {
return IntegrationFlows.from(fileReader(), new FixedRatePoller())
.channel(inputChannel()).handle(endpoint).channel(outputChannel())
.handle(fileWriter()).get();
return IntegrationFlows.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint)
.channel(outputChannel()).handle(fileWriter()).get();
}
private static class FixedRatePoller
implements Consumer<SourcePollingChannelAdapterSpec> {
private static class FixedRatePoller implements Consumer<SourcePollingChannelAdapterSpec> {
@Override
public void accept(SourcePollingChannelAdapterSpec spec) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -81,21 +81,18 @@ public class SampleIntegrationParentApplicationTests {
}
}
}
fail("Timed out awaiting output containing '" + requiredContents
+ "'. Output was '" + output + "'");
fail("Timed out awaiting output containing '" + requiredContents + "'. Output was '" + output + "'");
}
private Resource[] findResources() throws IOException {
return ResourcePatternUtils
.getResourcePatternResolver(new DefaultResourceLoader())
return ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader())
.getResources("file:target/output/*.txt");
}
private String readResources(Resource[] resources) throws IOException {
StringBuilder builder = new StringBuilder();
for (Resource resource : resources) {
builder.append(
new String(StreamUtils.copyToByteArray(resource.getInputStream())));
builder.append(new String(StreamUtils.copyToByteArray(resource.getInputStream())));
}
return builder.toString();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -30,8 +30,7 @@ public class ProducerApplication implements CommandLineRunner {
public void run(String... args) throws Exception {
new File("target/input").mkdirs();
if (args.length > 0) {
FileOutputStream stream = new FileOutputStream(
"target/input/data" + System.currentTimeMillis() + ".txt");
FileOutputStream stream = new FileOutputStream("target/input/data" + System.currentTimeMillis() + ".txt");
for (String arg : args) {
stream.write(arg.getBytes());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -78,8 +78,7 @@ public class SampleProfileApplicationTests {
@Test
public void testGoodbyeProfileFromCommandline() throws Exception {
SampleProfileApplication
.main(new String[] { "--spring.profiles.active=goodbye" });
SampleProfileApplication.main(new String[] { "--spring.profiles.active=goodbye" });
String output = this.outputCapture.toString();
assertThat(output).contains("Goodbye Everyone");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -36,8 +36,7 @@ public class SamplePropertiesValidator implements Validator {
ValidationUtils.rejectIfEmpty(errors, "host", "host.empty");
ValidationUtils.rejectIfEmpty(errors, "port", "port.empty");
SampleProperties properties = (SampleProperties) o;
if (properties.getHost() != null
&& !this.pattern.matcher(properties.getHost()).matches()) {
if (properties.getHost() != null && !this.pattern.matcher(properties.getHost()).matches()) {
errors.rejectValue("host", "Invalid host");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -49,8 +49,7 @@ public class SamplePropertyValidationApplicationTests {
@Test
public void bindValidProperties() {
this.context.register(SamplePropertyValidationApplication.class);
TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090")
.applyTo(this.context);
TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090").applyTo(this.context);
this.context.refresh();
SampleProperties properties = this.context.getBean(SampleProperties.class);
assertThat(properties.getHost()).isEqualTo("192.168.0.1");
@ -60,8 +59,7 @@ public class SamplePropertyValidationApplicationTests {
@Test
public void bindInvalidHost() {
this.context.register(SamplePropertyValidationApplication.class);
TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090")
.applyTo(this.context);
TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090").applyTo(this.context);
this.thrown.expect(BeanCreationException.class);
this.thrown.expectMessage("Failed to bind properties under 'sample'");
this.context.refresh();
@ -79,8 +77,7 @@ public class SamplePropertyValidationApplicationTests {
public void validatorOnlyCalledOnSupportedClass() {
this.context.register(SamplePropertyValidationApplication.class);
this.context.register(ServerProperties.class); // our validator will not apply
TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090")
.applyTo(this.context);
TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090").applyTo(this.context);
this.context.refresh();
SampleProperties properties = this.context.getBean(SampleProperties.class);
assertThat(properties.getHost()).isEqualTo("192.168.0.1");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -31,8 +31,7 @@ public class SampleJob extends QuartzJobBean {
}
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println(String.format("Hello %s!", this.name));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -35,17 +35,17 @@ public class SampleQuartzApplication {
@Bean
public JobDetail sampleJobDetail() {
return JobBuilder.newJob(SampleJob.class).withIdentity("sampleJob")
.usingJobData("name", "World").storeDurably().build();
return JobBuilder.newJob(SampleJob.class).withIdentity("sampleJob").usingJobData("name", "World").storeDurably()
.build();
}
@Bean
public Trigger sampleJobTrigger() {
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2).repeatForever();
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2)
.repeatForever();
return TriggerBuilder.newTrigger().forJob(sampleJobDetail())
.withIdentity("sampleTrigger").withSchedule(scheduleBuilder).build();
return TriggerBuilder.newTrigger().forJob(sampleJobDetail()).withIdentity("sampleTrigger")
.withSchedule(scheduleBuilder).build();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -37,11 +37,9 @@ public class SampleQuartzApplicationTests {
@Test
public void quartzJobIsTriggered() throws InterruptedException {
try (ConfigurableApplicationContext context = SpringApplication
.run(SampleQuartzApplication.class)) {
try (ConfigurableApplicationContext context = SpringApplication.run(SampleQuartzApplication.class)) {
long end = System.currentTimeMillis() + 5000;
while ((!this.outputCapture.toString().contains("Hello World!"))
&& System.currentTimeMillis() < end) {
while ((!this.outputCapture.toString().contains("Hello World!")) && System.currentTimeMillis() < end) {
Thread.sleep(100);
}
assertThat(this.outputCapture.toString()).contains("Hello World!");

View File

@ -43,28 +43,28 @@ public class SampleSecureWebFluxApplicationTests {
@Test
public void userDefinedMappingsSecureByDefault() {
this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange()
.expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED);
this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus()
.isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void actuatorsSecureByDefault() {
this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON)
.exchange().expectStatus().isUnauthorized();
this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus()
.isUnauthorized();
}
@Test
public void userDefinedMappingsAccessibleOnLogin() {
this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON)
.header("Authorization", "basic " + getBasicAuth()).exchange()
.expectBody(String.class).isEqualTo("Hello user");
.header("Authorization", "basic " + getBasicAuth()).exchange().expectBody(String.class)
.isEqualTo("Hello user");
}
@Test
public void actuatorsAccessibleOnLogin() {
this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON)
.header("Authorization", "basic " + getBasicAuth()).exchange()
.expectBody(String.class).isEqualTo("{\"status\":\"UP\"}");
.header("Authorization", "basic " + getBasicAuth()).exchange().expectBody(String.class)
.isEqualTo("{\"status\":\"UP\"}");
}
private String getBasicAuth() {

View File

@ -43,9 +43,8 @@ import org.springframework.test.web.reactive.server.WebTestClient;
* @author Madhura Bhave
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = { SampleSecureWebFluxCustomSecurityTests.SecurityConfiguration.class,
SampleSecureWebFluxApplication.class })
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {
SampleSecureWebFluxCustomSecurityTests.SecurityConfiguration.class, SampleSecureWebFluxApplication.class })
public class SampleSecureWebFluxCustomSecurityTests {
@Autowired
@ -53,52 +52,47 @@ public class SampleSecureWebFluxCustomSecurityTests {
@Test
public void userDefinedMappingsSecure() {
this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange()
.expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED);
this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus()
.isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void healthAndInfoDoNotRequireAuthentication() {
this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON)
.exchange().expectStatus().isOk();
this.webClient.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON)
.exchange().expectStatus().isOk();
this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus()
.isOk();
this.webClient.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk();
}
@Test
public void actuatorsSecuredByRole() {
this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON)
.header("Authorization", "basic " + getBasicAuth()).exchange()
.expectStatus().isForbidden();
.header("Authorization", "basic " + getBasicAuth()).exchange().expectStatus().isForbidden();
}
@Test
public void actuatorsAccessibleOnCorrectLogin() {
this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON)
.header("Authorization", "basic " + getBasicAuthForAdmin()).exchange()
.expectStatus().isOk();
.header("Authorization", "basic " + getBasicAuthForAdmin()).exchange().expectStatus().isOk();
}
@Test
public void actuatorExcludedFromEndpointRequestMatcher() {
this.webClient.get().uri("/actuator/mappings").accept(MediaType.APPLICATION_JSON)
.header("Authorization", "basic " + getBasicAuth()).exchange()
.expectStatus().isOk();
.header("Authorization", "basic " + getBasicAuth()).exchange().expectStatus().isOk();
}
@Test
public void staticResourceShouldBeAccessible() {
this.webClient.get().uri("/css/bootstrap.min.css")
.accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk();
this.webClient.get().uri("/css/bootstrap.min.css").accept(MediaType.APPLICATION_JSON).exchange().expectStatus()
.isOk();
}
@Test
public void actuatorLinksIsSecure() {
this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON).exchange().expectStatus()
.isUnauthorized();
this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON)
.exchange().expectStatus().isUnauthorized();
this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON)
.header("Authorization", "basic " + getBasicAuthForAdmin()).exchange()
.expectStatus().isOk();
.header("Authorization", "basic " + getBasicAuthForAdmin()).exchange().expectStatus().isOk();
}
private String getBasicAuth() {
@ -116,22 +110,18 @@ public class SampleSecureWebFluxCustomSecurityTests {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
return new MapReactiveUserDetailsService(
User.withDefaultPasswordEncoder().username("user")
.password("password").authorities("ROLE_USER").build(),
User.withDefaultPasswordEncoder().username("user").password("password").authorities("ROLE_USER")
.build(),
User.withDefaultPasswordEncoder().username("admin").password("admin")
.authorities("ROLE_ACTUATOR", "ROLE_USER").build());
}
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange().matchers(EndpointRequest.to("health", "info"))
.permitAll()
.matchers(EndpointRequest.toAnyEndpoint()
.excluding(MappingsEndpoint.class))
.hasRole("ACTUATOR")
.matchers(PathRequest.toStaticResources().atCommonLocations())
.permitAll().pathMatchers("/login").permitAll().anyExchange()
.authenticated().and().httpBasic().and().build();
return http.authorizeExchange().matchers(EndpointRequest.to("health", "info")).permitAll()
.matchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)).hasRole("ACTUATOR")
.matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll().pathMatchers("/login")
.permitAll().anyExchange().authenticated().and().httpBasic().and().build();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -36,9 +36,8 @@ public class SampleSecureApplication implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A",
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")));
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A",
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")));
try {
System.out.println(this.service.secure());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -40,8 +40,7 @@ public class SampleServletApplication extends SpringBootServletInitializer {
public Servlet dispatcherServlet() {
return new GenericServlet() {
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
res.setContentType("text/plain");
res.getWriter().append("Hello World");
}

View File

@ -51,15 +51,15 @@ public class SampleServletApplicationTests {
public void testHomeIsSecure() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET,
new HttpEntity<Void>(headers), String.class);
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers),
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void testHome() {
ResponseEntity<String> entity = this.restTemplate
.withBasicAuth("user", getPassword()).getForEntity("/", String.class);
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/",
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).isEqualTo("Hello World");
}

View File

@ -51,22 +51,17 @@ public class SampleSessionWebFluxApplicationTests {
@Test
public void userDefinedMappingsSecureByDefault() throws Exception {
WebClient webClient = this.webClientBuilder
.baseUrl("http://localhost:" + this.port + "/").build();
ClientResponse response = webClient.get().header("Authorization", getBasicAuth())
.exchange().block(Duration.ofSeconds(30));
WebClient webClient = this.webClientBuilder.baseUrl("http://localhost:" + this.port + "/").build();
ClientResponse response = webClient.get().header("Authorization", getBasicAuth()).exchange()
.block(Duration.ofSeconds(30));
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
ResponseCookie sessionCookie = response.cookies().getFirst("SESSION");
String sessionId = response.bodyToMono(String.class)
.block(Duration.ofSeconds(30));
response = webClient.get().cookie("SESSION", sessionCookie.getValue()).exchange()
.block(Duration.ofSeconds(30));
String sessionId = response.bodyToMono(String.class).block(Duration.ofSeconds(30));
response = webClient.get().cookie("SESSION", sessionCookie.getValue()).exchange().block(Duration.ofSeconds(30));
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.bodyToMono(String.class).block(Duration.ofSeconds(30)))
.isEqualTo(sessionId);
assertThat(response.bodyToMono(String.class).block(Duration.ofSeconds(30))).isEqualTo(sessionId);
Thread.sleep(2000);
response = webClient.get().cookie("SESSION", sessionCookie.getValue()).exchange()
.block(Duration.ofSeconds(30));
response = webClient.get().cookie("SESSION", sessionCookie.getValue()).exchange().block(Duration.ofSeconds(30));
assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -57,8 +57,7 @@ public class SampleSessionApplicationTests {
}
private ConfigurableApplicationContext createContext() {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.sources(SampleSessionApplication.class)
ConfigurableApplicationContext context = new SpringApplicationBuilder().sources(SampleSessionApplication.class)
.properties("server.port:0", "server.servlet.session.timeout:1")
.initializers(new ServerPortInfoApplicationContextInitializer()).run();
return context;
@ -66,14 +65,12 @@ public class SampleSessionApplicationTests {
private ResponseEntity<String> firstRequest(RestTemplate restTemplate, URI uri) {
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic "
+ Base64.getEncoder().encodeToString("user:password".getBytes()));
headers.set("Authorization", "Basic " + Base64.getEncoder().encodeToString("user:password".getBytes()));
RequestEntity<Object> request = new RequestEntity<>(headers, HttpMethod.GET, uri);
return restTemplate.exchange(request, String.class);
}
private ResponseEntity<String> nextRequest(RestTemplate restTemplate, URI uri,
String cookie) {
private ResponseEntity<String> nextRequest(RestTemplate restTemplate, URI uri, String cookie) {
HttpHeaders headers = new HttpHeaders();
headers.set("Cookie", cookie);
RequestEntity<Object> request = new RequestEntity<>(headers, HttpMethod.GET, uri);

View File

@ -35,15 +35,12 @@ import org.springframework.web.client.RestTemplate;
@Service
public class RemoteVehicleDetailsService implements VehicleDetailsService {
private static final Logger logger = LoggerFactory
.getLogger(RemoteVehicleDetailsService.class);
private static final Logger logger = LoggerFactory.getLogger(RemoteVehicleDetailsService.class);
private final RestTemplate restTemplate;
public RemoteVehicleDetailsService(ServiceProperties properties,
RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.rootUri(properties.getVehicleServiceRootUrl()).build();
public RemoteVehicleDetailsService(ServiceProperties properties, RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.rootUri(properties.getVehicleServiceRootUrl()).build();
}
@Override
@ -52,8 +49,7 @@ public class RemoteVehicleDetailsService implements VehicleDetailsService {
Assert.notNull(vin, "VIN must not be null");
logger.debug("Retrieving vehicle data for: " + vin);
try {
return this.restTemplate.getForObject("/vehicle/{vin}/details",
VehicleDetails.class, vin);
return this.restTemplate.getForObject("/vehicle/{vin}/details", VehicleDetails.class, vin);
}
catch (HttpStatusCodeException ex) {
if (HttpStatus.NOT_FOUND.equals(ex.getStatusCode())) {

View File

@ -33,8 +33,7 @@ public class VehicleDetails {
private final String model;
@JsonCreator
public VehicleDetails(@JsonProperty("make") String make,
@JsonProperty("model") String model) {
public VehicleDetails(@JsonProperty("make") String make, @JsonProperty("model") String model) {
Assert.notNull(make, "Make must not be null");
Assert.notNull(model, "Model must not be null");
this.make = make;

View File

@ -31,8 +31,7 @@ public class VehicleIdentificationNumberNotFoundException extends RuntimeExcepti
this(vin, null);
}
public VehicleIdentificationNumberNotFoundException(VehicleIdentificationNumber vin,
Throwable cause) {
public VehicleIdentificationNumberNotFoundException(VehicleIdentificationNumber vin, Throwable cause) {
super("Unable to find VehicleIdentificationNumber " + vin, cause);
this.vehicleIdentificationNumber = vin;
}

View File

@ -37,15 +37,13 @@ public class UserVehicleService {
private final VehicleDetailsService vehicleDetailsService;
public UserVehicleService(UserRepository userRepository,
VehicleDetailsService vehicleDetailsService) {
public UserVehicleService(UserRepository userRepository, VehicleDetailsService vehicleDetailsService) {
this.userRepository = userRepository;
this.vehicleDetailsService = vehicleDetailsService;
}
public VehicleDetails getVehicleDetails(String username)
throws UserNameNotFoundException,
VehicleIdentificationNumberNotFoundException {
throws UserNameNotFoundException, VehicleIdentificationNumberNotFoundException {
Assert.notNull(username, "Username must not be null");
User user = this.userRepository.findByUsername(username);
if (user == null) {

View File

@ -43,8 +43,7 @@ import static org.mockito.BDDMockito.given;
@AutoConfigureTestDatabase
public class SampleTestApplicationWebIntegrationTests {
private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber(
"01234567890123456");
private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("01234567890123456");
@Autowired
private TestRestTemplate restTemplate;
@ -54,8 +53,7 @@ public class SampleTestApplicationWebIntegrationTests {
@Before
public void setup() {
given(this.vehicleDetailsService.getVehicleDetails(VIN))
.willReturn(new VehicleDetails("Honda", "Civic"));
given(this.vehicleDetailsService.getVehicleDetails(VIN)).willReturn(new VehicleDetails("Honda", "Civic"));
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
public class UserEntityTests {
private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber(
"00000000000000000");
private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000");
@Rule
public ExpectedException thrown = ExpectedException.none();

Some files were not shown because too many files have changed in this diff Show More