Merge branch '2.1.x'

Closes gh-17079
This commit is contained in:
Andy Wilkinson
2019-06-07 11:00:44 +01:00
2799 changed files with 28402 additions and 47836 deletions

View File

@@ -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

@@ -52,36 +52,31 @@ class CorsSampleActuatorApplicationTests {
@BeforeEach
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
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
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
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

@@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Madhura Bhave
*/
@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" })
class ManagementPortAndPathSampleActuatorApplicationTests {
@LocalServerPort
@@ -55,24 +54,22 @@ class ManagementPortAndPathSampleActuatorApplicationTests {
@Test
void actuatorPathOnMainPortShouldNotMatch() {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.port + "/actuator/health", String.class);
ResponseEntity<String> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port + "/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
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
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\"");
}
@@ -80,8 +77,7 @@ class ManagementPortAndPathSampleActuatorApplicationTests {
@Test
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

@@ -58,30 +58,26 @@ 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
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
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
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);
@@ -89,43 +85,40 @@ class SampleActuatorCustomSecurityApplicationTests {
@Test
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
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
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
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
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
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");
@@ -133,15 +126,13 @@ class SampleActuatorCustomSecurityApplicationTests {
@Test
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
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);
@@ -164,8 +155,7 @@ class SampleActuatorCustomSecurityApplicationTests {
}
private TestRestTemplate configure(TestRestTemplate restTemplate) {
restTemplate
.setUriTemplateHandler(new LocalHostUriTemplateHandler(this.environment));
restTemplate.setUriTemplateHandler(new LocalHostUriTemplateHandler(this.environment));
return restTemplate;
}

View File

@@ -47,8 +47,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@ExtendWith(OutputCaptureExtension.class)
class SampleActuatorLog4J2ApplicationTests {
private static final Logger logger = LogManager
.getLogger(SampleActuatorLog4J2ApplicationTests.class);
private static final Logger logger = LogManager.getLogger(SampleActuatorLog4J2ApplicationTests.class);
@Autowired
private MockMvc mvc;
@@ -61,12 +60,9 @@ class SampleActuatorLog4J2ApplicationTests {
@Test
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

@@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port:0" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port:0" })
class SampleActuatorUiApplicationPortTests {
@LocalServerPort
@@ -47,26 +46,23 @@ class SampleActuatorUiApplicationPortTests {
@Test
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
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
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

@@ -49,17 +49,15 @@ class SampleActuatorUiApplicationTests {
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
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");
}
@@ -67,8 +65,7 @@ class SampleActuatorUiApplicationTests {
@Test
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);
}
@@ -76,9 +73,8 @@ class SampleActuatorUiApplicationTests {
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

@@ -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

@@ -45,8 +45,8 @@ class EndpointsPropertiesSampleActuatorApplicationTests {
@Test
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();
@@ -56,8 +56,7 @@ class EndpointsPropertiesSampleActuatorApplicationTests {
@Test
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

@@ -35,9 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Dave Syer
*/
@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" })
class ManagementAddressActuatorApplicationTests {
@LocalServerPort
@@ -49,16 +48,14 @@ class ManagementAddressActuatorApplicationTests {
@Test
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
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

@@ -43,8 +43,7 @@ class ManagementPathSampleActuatorApplicationTests {
@Test
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

@@ -37,10 +37,8 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Dave Syer
*/
@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" })
class ManagementPortAndPathSampleActuatorApplicationTests {
@LocalServerPort
@@ -67,17 +65,15 @@ class ManagementPortAndPathSampleActuatorApplicationTests {
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
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\"}");
}
@@ -86,19 +82,15 @@ class ManagementPortAndPathSampleActuatorApplicationTests {
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
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");
}
@@ -118,8 +110,7 @@ class ManagementPortAndPathSampleActuatorApplicationTests {
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

@@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Dave Syer
*/
@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" })
class ManagementPortSampleActuatorApplicationTests {
@LocalServerPort
@@ -60,18 +60,15 @@ class ManagementPortSampleActuatorApplicationTests {
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
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\"");
@@ -82,8 +79,7 @@ class ManagementPortSampleActuatorApplicationTests {
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

@@ -32,8 +32,8 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Madhura Bhave
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
"management.server.port=0", "spring.main.lazy-initialization=true" })
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0", "spring.main.lazy-initialization=true" })
class ManagementPortWithLazyInitializationTests {
@LocalManagementPort
@@ -41,10 +41,8 @@ class ManagementPortWithLazyInitializationTests {
@Test
void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate()
.withBasicAuth("user", "password").getForEntity(
"http://localhost:" + this.managementPort + "/actuator/health",
String.class);
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password")
.getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}

View File

@@ -34,8 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=-1" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=-1" })
class NoManagementSampleActuatorApplicationTests {
@Autowired
@@ -44,8 +43,8 @@ class NoManagementSampleActuatorApplicationTests {
@Test
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();
@@ -56,8 +55,8 @@ class NoManagementSampleActuatorApplicationTests {
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

@@ -66,8 +66,7 @@ class SampleActuatorApplicationTests {
@Test
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);
@@ -80,8 +79,8 @@ class SampleActuatorApplicationTests {
@Test
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();
@@ -93,8 +92,7 @@ class SampleActuatorApplicationTests {
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();
@@ -106,8 +104,7 @@ class SampleActuatorApplicationTests {
@Test
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")
@@ -117,8 +114,7 @@ class SampleActuatorApplicationTests {
@Test
void healthInsecureByDefault() {
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()).contains("\"status\":\"UP\"");
assertThat(entity.getBody()).doesNotContain("\"hello\":\"1\"");
@@ -126,22 +122,18 @@ class SampleActuatorApplicationTests {
@Test
void infoInsecureByDefault() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/info",
String.class);
ResponseEntity<String> entity = this.restTemplate.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
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\":");
@@ -152,9 +144,8 @@ 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();
@@ -164,8 +155,8 @@ class SampleActuatorApplicationTests {
@Test
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();
@@ -177,8 +168,7 @@ 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");
@@ -188,17 +178,14 @@ class SampleActuatorApplicationTests {
@Test
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

@@ -34,8 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "spring.mvc.servlet.path=/spring" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.mvc.servlet.path=/spring" })
class ServletPathSampleActuatorApplicationTests {
@Autowired
@@ -44,8 +43,7 @@ class ServletPathSampleActuatorApplicationTests {
@Test
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")
@@ -56,8 +54,7 @@ class ServletPathSampleActuatorApplicationTests {
@Test
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\"");
@@ -66,8 +63,7 @@ class ServletPathSampleActuatorApplicationTests {
@Test
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

@@ -38,10 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Dave Syer
*/
@SpringBootTest(
classes = { ShutdownSampleActuatorApplicationTests.SecurityConfiguration.class,
SampleActuatorApplication.class },
webEnvironment = WebEnvironment.RANDOM_PORT)
@SpringBootTest(classes = { ShutdownSampleActuatorApplicationTests.SecurityConfiguration.class,
SampleActuatorApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
class ShutdownSampleActuatorApplicationTests {
@Autowired
@@ -50,8 +48,8 @@ class ShutdownSampleActuatorApplicationTests {
@Test
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();
@@ -62,8 +60,7 @@ 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

@@ -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 " + message.getAuthor() + " sent message "
+ message.getMessage());
this.logger.info("Author " + message.getAuthor() + " sent message " + 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

@@ -50,11 +50,11 @@ public class SampleAtmosphereApplication {
// to be mapped to '/chat'
AtmosphereServlet atmosphereServlet = new AtmosphereServlet();
atmosphereServlet.framework().setHandlersPath("/");
ServletRegistrationBean<AtmosphereServlet> registration = new ServletRegistrationBean<>(
atmosphereServlet, "/chat/*");
ServletRegistrationBean<AtmosphereServlet> registration = new ServletRegistrationBean<>(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

@@ -42,8 +42,7 @@ import org.springframework.web.socket.handler.TextWebSocketHandler;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = SampleAtmosphereApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT)
@SpringBootTest(classes = SampleAtmosphereApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
class SampleAtmosphereApplicationTests {
private static Log logger = LogFactory.getLog(SampleAtmosphereApplicationTests.class);
@@ -53,18 +52,15 @@ class SampleAtmosphereApplicationTests {
@Test
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(proxyBeanMethods = false)
@@ -90,8 +86,7 @@ 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;
}
@@ -106,17 +101,13 @@ 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

@@ -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

@@ -30,8 +30,7 @@ class SampleBatchApplicationTests {
@Test
void testDefaultSettings(CapturedOutput capturedOutput) {
assertThat(SpringApplication
.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0);
assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0);
assertThat(capturedOutput).contains("completed with the following parameters");
}

View File

@@ -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

@@ -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

@@ -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

@@ -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

@@ -22,11 +22,9 @@ import org.cassandraunit.spring.CassandraUnitDependencyInjectionTestExecutionLis
import org.springframework.core.Ordered;
public class OrderedCassandraTestExecutionListener
extends CassandraUnitDependencyInjectionTestExecutionListener {
public class OrderedCassandraTestExecutionListener extends CassandraUnitDependencyInjectionTestExecutionListener {
private static final Log logger = LogFactory
.getLog(OrderedCassandraTestExecutionListener.class);
private static final Log logger = LogFactory.getLog(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

@@ -33,8 +33,7 @@ class SampleCouchbaseApplicationTests {
@Test
void testDefaultSettings(CapturedOutput capturedOutput) {
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

@@ -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

@@ -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

@@ -60,15 +60,13 @@ class SampleDataJpaApplicationTests {
@Test
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
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

@@ -48,13 +48,10 @@ class HotelRepositoryIntegrationTests {
@Test
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

@@ -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

@@ -61,9 +61,8 @@ public class SampleMongoApplication implements CommandLineRunner {
@Bean
public MongoClientSettingsBuilderCustomizer customizer() {
return (builder) -> builder
.applyToConnectionPoolSettings((connectionPool) -> connectionPool
.maxConnectionIdleTime(5, TimeUnit.MINUTES));
return (builder) -> builder.applyToConnectionPoolSettings(
(connectionPool) -> connectionPool.maxConnectionIdleTime(5, TimeUnit.MINUTES));
}
public static void main(String[] 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.
@@ -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

@@ -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

@@ -55,25 +55,21 @@ class SampleDataRestApplicationTests {
@Test
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
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
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

@@ -46,17 +46,15 @@ class CityRepositoryIntegrationTests {
@Test
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
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

@@ -41,24 +41,21 @@ class SampleDevToolsApplicationIntegrationTests {
@Test
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
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
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

@@ -32,8 +32,7 @@ class SampleFlywayApplicationTests {
@Test
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

@@ -48,8 +48,7 @@ public class CustomerController {
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
HttpEntity<CollectionModel<Customer>> showCustomers() {
CollectionModel<Customer> resources = new CollectionModel<>(
this.repository.findAll());
CollectionModel<Customer> resources = new CollectionModel<>(this.repository.findAll());
resources.add(this.entityLinks.linkToCollectionResource(Customer.class));
return new ResponseEntity<>(resources, HttpStatus.OK);
}

View File

@@ -39,11 +39,9 @@ class SampleHateoasApplicationTests {
@Test
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\"");
}
@@ -52,11 +50,10 @@ 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"));
assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.parseMediaType("application/json"));
}
}

View File

@@ -57,25 +57,22 @@ public class SampleIntegrationApplication {
@Bean
public FileWritingMessageHandler fileWriter() {
FileWritingMessageHandler writer = new FileWritingMessageHandler(
this.serviceProperties.getOutputDir());
FileWritingMessageHandler writer = new FileWritingMessageHandler(this.serviceProperties.getOutputDir());
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

@@ -62,10 +62,10 @@ class SampleIntegrationApplicationTests {
void testVanillaExchange(@TempDir Path temp) throws Exception {
File inputDir = new File(temp.toFile(), "input");
File outputDir = new File(temp.toFile(), "output");
this.context = SpringApplication.run(SampleIntegrationApplication.class,
"--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir);
SpringApplication.run(ProducerApplication.class, "World",
"--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir);
this.context = SpringApplication.run(SampleIntegrationApplication.class, "--service.input-dir=" + inputDir,
"--service.output-dir=" + outputDir);
SpringApplication.run(ProducerApplication.class, "World", "--service.input-dir=" + inputDir,
"--service.output-dir=" + outputDir);
String output = getOutput(outputDir);
assertThat(output).contains("Hello World");
}
@@ -74,44 +74,38 @@ class SampleIntegrationApplicationTests {
void testMessageGateway(@TempDir Path temp) throws Exception {
File inputDir = new File(temp.toFile(), "input");
File outputDir = new File(temp.toFile(), "output");
this.context = SpringApplication.run(SampleIntegrationApplication.class,
"testviamg", "--service.input-dir=" + inputDir,
"--service.output-dir=" + outputDir);
String output = getOutput(
this.context.getBean(ServiceProperties.class).getOutputDir());
this.context = SpringApplication.run(SampleIntegrationApplication.class, "testviamg",
"--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir);
String output = getOutput(this.context.getBean(ServiceProperties.class).getOutputDir());
assertThat(output).contains("testviamg");
}
private String getOutput(File outputDir) throws Exception {
Future<String> future = Executors.newSingleThreadExecutor()
.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Resource[] resources = getResourcesWithContent(outputDir);
while (resources.length == 0) {
Thread.sleep(200);
resources = getResourcesWithContent(outputDir);
}
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(outputDir);
while (resources.length == 0) {
Thread.sleep(200);
resources = getResourcesWithContent(outputDir);
}
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(File outputDir) throws IOException {
Resource[] candidates = ResourcePatternUtils
.getResourcePatternResolver(new DefaultResourceLoader())
Resource[] candidates = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader())
.getResources("file:" + outputDir.getAbsolutePath() + "/**");
for (Resource candidate : candidates) {
if ((candidate.getFilename() != null
&& candidate.getFilename().endsWith(".writing"))
if ((candidate.getFilename() != null && candidate.getFilename().endsWith(".writing"))
|| candidate.contentLength() == 0) {
return new Resource[0];
}

View File

@@ -42,8 +42,7 @@ public class ProducerApplication implements ApplicationRunner {
this.serviceProperties.getInputDir().mkdirs();
if (args.getNonOptionArgs().size() > 0) {
FileOutputStream stream = new FileOutputStream(
new File(this.serviceProperties.getInputDir(),
"data" + System.currentTimeMillis() + ".txt"));
new File(this.serviceProperties.getInputDir(), "data" + System.currentTimeMillis() + ".txt"));
for (String arg : args.getNonOptionArgs()) {
stream.write(arg.getBytes());
}

View File

@@ -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

@@ -33,8 +33,8 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Madhura Bhave
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
"management.server.port=0", "spring.jersey.application-path=/app" })
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0", "spring.jersey.application-path=/app" })
class JerseyApplicationPathAndManagementPortTests {
@LocalServerPort
@@ -48,9 +48,8 @@ class JerseyApplicationPathAndManagementPortTests {
@Test
void applicationPathShouldNotAffectActuators() {
ResponseEntity<String> entity = this.testRestTemplate.getForEntity(
"http://localhost:" + this.managementPort + "/actuator/health",
String.class);
ResponseEntity<String> entity = this.testRestTemplate
.getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}

View File

@@ -35,30 +35,26 @@ class SampleJerseyApplicationTests {
@Test
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
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
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
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

@@ -59,13 +59,10 @@ 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

@@ -35,8 +35,7 @@ class SampleJooqApplicationTests {
@Test
void outputResults(CapturedOutput capturedOutput) {
SampleJooqApplication.main(NO_ARGS);
assertThat(capturedOutput).contains("jOOQ Fetch 1 Greg Turnquest")
.contains("jOOQ Fetch 2 Craig Walls")
assertThat(capturedOutput).contains("jOOQ Fetch 1 Greg Turnquest").contains("jOOQ Fetch 2 Craig Walls")
.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

@@ -52,8 +52,7 @@ class SampleJpaApplicationTests {
@Test
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

@@ -36,14 +36,12 @@ class SampleAtomikosApplicationTests {
@Test
void testTransactionRollback(CapturedOutput capturedOutput) throws Exception {
SampleAtomikosApplication.main(new String[] {});
assertThat(capturedOutput.toString()).has(substring(1, "---->"))
.has(substring(1, "----> josh")).has(substring(2, "Count is 1"))
.has(substring(1, "Simulated error"));
assertThat(capturedOutput.toString()).has(substring(1, "---->")).has(substring(1, "----> josh"))
.has(substring(2, "Count is 1")).has(substring(1, "Simulated error"));
}
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

@@ -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

@@ -39,27 +39,23 @@ class SampleBitronixApplicationTests {
@Test
void testTransactionRollback(CapturedOutput capturedOutput) throws Exception {
SampleBitronixApplication.main(new String[] {});
assertThat(capturedOutput.toString()).has(substring(1, "---->"))
.has(substring(1, "----> josh")).has(substring(2, "Count is 1"))
.has(substring(1, "Simulated error"));
assertThat(capturedOutput.toString()).has(substring(1, "---->")).has(substring(1, "----> josh"))
.has(substring(2, "Count is 1")).has(substring(1, "Simulated error"));
}
@Test
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-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

@@ -30,8 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Gary Russell
* @author Stephane Nicoll
*/
@SpringBootTest(
properties = "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}")
@SpringBootTest(properties = "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}")
@EmbeddedKafka(topics = "testTopic")
class SampleKafkaApplicationTests {
@@ -41,12 +40,10 @@ class SampleKafkaApplicationTests {
@Test
void testVanillaExchange() throws Exception {
long end = System.currentTimeMillis() + 10000;
while (this.consumer.getMessages().isEmpty()
&& System.currentTimeMillis() < end) {
while (this.consumer.getMessages().isEmpty() && System.currentTimeMillis() < end) {
Thread.sleep(250);
}
assertThat(this.consumer.getMessages()).extracting("message")
.containsOnly("A simple test message");
assertThat(this.consumer.getMessages()).extracting("message").containsOnly("A simple test message");
}
}

View File

@@ -41,16 +41,12 @@ class SampleLiquibaseApplicationTests {
}
}
assertThat(capturedOutput).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

@@ -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

@@ -30,16 +30,13 @@ class SampleLogbackApplicationTests {
@Test
void testLoadedCustomLogbackConfig(CapturedOutput capturedOutput) throws Exception {
SampleLogbackApplication.main(new String[0]);
assertThat(capturedOutput).contains("Sample Debug Message")
.doesNotContain("Sample Trace Message");
assertThat(capturedOutput).contains("Sample Debug Message").doesNotContain("Sample Trace Message");
}
@Test
void testProfile(CapturedOutput capturedOutput) throws Exception {
SampleLogbackApplication
.main(new String[] { "--spring.profiles.active=staging" });
assertThat(capturedOutput).contains("Sample Debug Message")
.contains("Sample Trace Message");
SampleLogbackApplication.main(new String[] { "--spring.profiles.active=staging" });
assertThat(capturedOutput).contains("Sample Debug Message").contains("Sample Trace Message");
}
}

View File

@@ -31,8 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = { "APP-CLIENT-ID=my-client-id", "APP-CLIENT-SECRET=my-client-secret",
"YAHOO-CLIENT-ID=my-yahoo-client-id",
"YAHOO-CLIENT-SECRET=my-yahoo-client-secret" })
"YAHOO-CLIENT-ID=my-yahoo-client-id", "YAHOO-CLIENT-SECRET=my-yahoo-client-secret" })
class SampleOAuth2ClientApplicationTests {
@LocalServerPort
@@ -45,14 +44,12 @@ class SampleOAuth2ClientApplicationTests {
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
void loginShouldHaveAllOAuth2ClientsToChooseFrom() {
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/yahoo");
assertThat(entity.getBody()).contains("/oauth2/authorization/github-client-1");

View File

@@ -68,8 +68,7 @@ class SampleOauth2ResourceServerApplicationTests {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(VALID_TOKEN);
HttpEntity<?> request = new HttpEntity<Void>(headers);
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET,
request, String.class);
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, request, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@@ -77,8 +76,7 @@ class SampleOauth2ResourceServerApplicationTests {
void withNoBearerTokenShouldNotAllowAccess() {
HttpHeaders headers = new HttpHeaders();
HttpEntity<?> request = new HttpEntity<Void>(headers);
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET,
request, String.class);
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, request, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@@ -100,8 +98,7 @@ class SampleOauth2ResourceServerApplicationTests {
+ "V9gWuOzSJ0iEuWvtQ6eGBP5M6m7pccLNZfwUse8Cb4Ngx3XiTlyuqM7pv0LPyppZusfEHVEdeelou7Dy9k0OQ_nJTI3b2E1WBoHC5"
+ "8CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eq"
+ "D9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}";
return new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setResponseCode(200).setBody(body);
}

View File

@@ -35,8 +35,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(proxyBeanMethods = false)
@@ -68,21 +67,18 @@ public class SampleParentContextApplication {
@Bean
public FileWritingMessageHandler fileWriter() {
FileWritingMessageHandler writer = new FileWritingMessageHandler(
this.serviceProperties.getOutputDir());
FileWritingMessageHandler writer = new FileWritingMessageHandler(this.serviceProperties.getOutputDir());
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

@@ -46,13 +46,11 @@ class SampleIntegrationParentApplicationTests {
void testVanillaExchange(@TempDir Path temp) throws Exception {
File inputDir = new File(temp.toFile(), "input");
File outputDir = new File(temp.toFile(), "output");
ConfigurableApplicationContext app = SpringApplication.run(
SampleParentContextApplication.class, "--service.input-dir=" + inputDir,
"--service.output-dir=" + outputDir);
ConfigurableApplicationContext app = SpringApplication.run(SampleParentContextApplication.class,
"--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir);
try {
ConfigurableApplicationContext producer = SpringApplication.run(
ProducerApplication.class, "--service.input-dir=" + inputDir,
"--service.output-dir=" + outputDir, "World");
ConfigurableApplicationContext producer = SpringApplication.run(ProducerApplication.class,
"--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir, "World");
try {
awaitOutputContaining(outputDir, "Hello World");
}
@@ -65,8 +63,7 @@ class SampleIntegrationParentApplicationTests {
}
}
private void awaitOutputContaining(File outputDir, String requiredContents)
throws Exception {
private void awaitOutputContaining(File outputDir, String requiredContents) throws Exception {
long endTime = System.currentTimeMillis() + 30000;
String output = null;
while (System.currentTimeMillis() < endTime) {
@@ -86,21 +83,18 @@ 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(File outputDir) throws IOException {
return ResourcePatternUtils
.getResourcePatternResolver(new DefaultResourceLoader())
return ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader())
.getResources("file:" + outputDir.getAbsolutePath() + "/*.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

@@ -42,8 +42,7 @@ public class ProducerApplication implements ApplicationRunner {
this.serviceProperties.getInputDir().mkdirs();
if (args.getNonOptionArgs().size() > 0) {
FileOutputStream stream = new FileOutputStream(
new File(this.serviceProperties.getInputDir(),
"data" + System.currentTimeMillis() + ".txt"));
new File(this.serviceProperties.getInputDir(), "data" + System.currentTimeMillis() + ".txt"));
for (String arg : args.getNonOptionArgs()) {
stream.write(arg.getBytes());
}

View File

@@ -74,8 +74,7 @@ class SampleProfileApplicationTests {
@Test
void testGoodbyeProfileFromCommandline(CapturedOutput capturedOutput) {
SampleProfileApplication
.main(new String[] { "--spring.profiles.active=goodbye" });
SampleProfileApplication.main(new String[] { "--spring.profiles.active=goodbye" });
assertThat(capturedOutput).contains("Goodbye Everyone");
}

View File

@@ -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

@@ -45,8 +45,7 @@ class SamplePropertyValidationApplicationTests {
@Test
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");
@@ -56,18 +55,15 @@ class SamplePropertyValidationApplicationTests {
@Test
void bindInvalidHost() {
this.context.register(SamplePropertyValidationApplication.class);
TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090")
.applyTo(this.context);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.context.refresh())
TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090").applyTo(this.context);
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> this.context.refresh())
.withMessageContaining("Failed to bind properties under 'sample'");
}
@Test
void bindNullHost() {
this.context.register(SamplePropertyValidationApplication.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.context.refresh())
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> this.context.refresh())
.withMessageContaining("Failed to bind properties under 'sample'");
}
@@ -75,8 +71,7 @@ class SamplePropertyValidationApplicationTests {
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

@@ -36,11 +36,9 @@ class SampleQuartzApplicationTests {
@Test
void quartzJobIsTriggered(CapturedOutput capturedOutput) throws InterruptedException {
try (ConfigurableApplicationContext context = SpringApplication
.run(SampleQuartzApplication.class)) {
try (ConfigurableApplicationContext context = SpringApplication.run(SampleQuartzApplication.class)) {
long end = System.currentTimeMillis() + 5000;
while ((!capturedOutput.toString().contains("Hello World!"))
&& System.currentTimeMillis() < end) {
while ((!capturedOutput.toString().contains("Hello World!")) && System.currentTimeMillis() < end) {
Thread.sleep(100);
}
assertThat(capturedOutput).contains("Hello World!");

View File

@@ -26,8 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = { "APP-CLIENT-ID=my-client-id", "APP-CLIENT-SECRET=my-client-secret",
"YAHOO-CLIENT-ID=my-google-client-id",
"YAHOO-CLIENT-SECRET=my-google-client-secret" })
"YAHOO-CLIENT-ID=my-google-client-id", "YAHOO-CLIENT-SECRET=my-google-client-secret" })
class SampleReactiveOAuth2ClientApplicationTests {
@Autowired
@@ -35,14 +34,14 @@ class SampleReactiveOAuth2ClientApplicationTests {
@Test
void everythingShouldRedirectToLogin() {
this.webTestClient.get().uri("/").exchange().expectStatus().isFound()
.expectHeader().valueEquals("Location", "/login");
this.webTestClient.get().uri("/").exchange().expectStatus().isFound().expectHeader().valueEquals("Location",
"/login");
}
@Test
void loginShouldHaveBothOAuthClientsToChooseFrom() {
byte[] body = this.webTestClient.get().uri("/login").exchange().expectStatus()
.isOk().returnResult(String.class).getResponseBodyContent();
byte[] body = this.webTestClient.get().uri("/login").exchange().expectStatus().isOk().returnResult(String.class)
.getResponseBodyContent();
String bodyString = new String(body);
assertThat(bodyString).contains("/oauth2/authorization/yahoo");
assertThat(bodyString).contains("/oauth2/authorization/github-client-1");

View File

@@ -58,16 +58,14 @@ class SampleReactiveOAuth2ResourceServerApplicationTests {
@Test
void getWhenValidTokenShouldBeOk() {
this.webTestClient.get().uri("/")
.headers((headers) -> headers.setBearerAuth(VALID_TOKEN)).exchange()
.expectStatus().isOk().expectBody(String.class)
.isEqualTo("Hello, subject!");
this.webTestClient.get().uri("/").headers((headers) -> headers.setBearerAuth(VALID_TOKEN)).exchange()
.expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, subject!");
}
@Test
void getWhenNoTokenShouldBeUnauthorized() {
this.webTestClient.get().uri("/").exchange().expectStatus().isUnauthorized()
.expectHeader().valueEquals(HttpHeaders.WWW_AUTHENTICATE, "Bearer");
this.webTestClient.get().uri("/").exchange().expectStatus().isUnauthorized().expectHeader()
.valueEquals(HttpHeaders.WWW_AUTHENTICATE, "Bearer");
}
private static MockResponse mockResponse() {
@@ -88,8 +86,7 @@ class SampleReactiveOAuth2ResourceServerApplicationTests {
+ "V9gWuOzSJ0iEuWvtQ6eGBP5M6m7pccLNZfwUse8Cb4Ngx3XiTlyuqM7pv0LPyppZusfEHVEdeelou7Dy9k0OQ_nJTI3b2E1WBoHC5"
+ "8CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eq"
+ "D9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}";
return new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setResponseCode(200).setBody(body);
}

View File

@@ -41,10 +41,8 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Madhura Bhave
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0" },
classes = { ManagementPortSampleSecureWebFluxTests.SecurityConfiguration.class,
SampleSecureWebFluxApplication.class })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=0" }, classes = {
ManagementPortSampleSecureWebFluxTests.SecurityConfiguration.class, SampleSecureWebFluxApplication.class })
class ManagementPortSampleSecureWebFluxTests {
@LocalServerPort
@@ -59,35 +57,29 @@ class ManagementPortSampleSecureWebFluxTests {
@Test
void testHome() {
this.webClient.get().uri("http://localhost:" + this.port, String.class)
.header("Authorization", "basic " + getBasicAuth()).exchange()
.expectStatus().isOk().expectBody(String.class).isEqualTo("Hello user");
.header("Authorization", "basic " + getBasicAuth()).exchange().expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello user");
}
@Test
void actuatorPathOnMainPortShouldNotMatch() {
this.webClient.get()
.uri("http://localhost:" + this.port + "/actuator", String.class)
.exchange().expectStatus().isUnauthorized();
this.webClient.get()
.uri("http://localhost:" + this.port + "/actuator/health", String.class)
.exchange().expectStatus().isUnauthorized();
this.webClient.get().uri("http://localhost:" + this.port + "/actuator", String.class).exchange().expectStatus()
.isUnauthorized();
this.webClient.get().uri("http://localhost:" + this.port + "/actuator/health", String.class).exchange()
.expectStatus().isUnauthorized();
}
@Test
void testSecureActuator() {
this.webClient.get()
.uri("http://localhost:" + this.managementPort + "/actuator/env",
String.class)
.exchange().expectStatus().isUnauthorized();
this.webClient.get().uri("http://localhost:" + this.managementPort + "/actuator/env", String.class).exchange()
.expectStatus().isUnauthorized();
}
@Test
void testInsecureActuator() {
String responseBody = this.webClient.get()
.uri("http://localhost:" + this.managementPort + "/actuator/health",
String.class)
.exchange().expectStatus().isOk().expectBody(String.class).returnResult()
.getResponseBody();
.uri("http://localhost:" + this.managementPort + "/actuator/health", String.class).exchange()
.expectStatus().isOk().expectBody(String.class).returnResult().getResponseBody();
assertThat(responseBody).contains("\"status\":\"UP\"");
}
@@ -100,14 +92,10 @@ class ManagementPortSampleSecureWebFluxTests {
@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

@@ -40,40 +40,39 @@ class SampleSecureWebFluxApplicationTests {
@Test
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
void healthInsecureByDefault() {
this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON)
.exchange().expectStatus().isOk();
this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus()
.isOk();
}
@Test
void infoInsecureByDefault() {
this.webClient.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON)
.exchange().expectStatus().isOk();
this.webClient.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk();
}
@Test
void otherActuatorsSecureByDefault() {
this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON)
.exchange().expectStatus().isUnauthorized();
this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON).exchange().expectStatus()
.isUnauthorized();
}
@Test
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
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

@@ -40,9 +40,8 @@ import org.springframework.test.web.reactive.server.WebTestClient;
*
* @author Madhura Bhave
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = { SampleSecureWebFluxCustomSecurityTests.SecurityConfiguration.class,
SampleSecureWebFluxApplication.class })
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {
SampleSecureWebFluxCustomSecurityTests.SecurityConfiguration.class, SampleSecureWebFluxApplication.class })
class SampleSecureWebFluxCustomSecurityTests {
@Autowired
@@ -50,52 +49,47 @@ class SampleSecureWebFluxCustomSecurityTests {
@Test
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
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
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
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
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
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
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() {
@@ -113,22 +107,18 @@ 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

@@ -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

@@ -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

@@ -48,15 +48,15 @@ class SampleServletApplicationTests {
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
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

@@ -48,22 +48,17 @@ class SampleSessionWebFluxApplicationTests {
@Test
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

@@ -57,8 +57,7 @@ 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 @@ 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

@@ -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,15 +35,12 @@ import org.springframework.web.client.RestTemplate;
@Service
public class RemoteVehicleDetailsService implements VehicleDetailsService {
private static final Log logger = LogFactory
.getLog(RemoteVehicleDetailsService.class);
private static final Log logger = LogFactory.getLog(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

@@ -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,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;

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