This commit is contained in:
Phillip Webb 2014-04-23 09:42:10 +01:00
parent 316cb87583
commit fad5ce45db
46 changed files with 276 additions and 253 deletions

View File

@ -200,15 +200,15 @@ public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware,
registerContainer(this.applicationContext,
childContext.getEmbeddedServletContainer());
}
catch (RuntimeException e) {
catch (RuntimeException ex) {
// No support currently for deploying a war with management.port=<different>,
// and this is the signature of that happening
if (e instanceof EmbeddedServletContainerException
|| e.getCause() instanceof EmbeddedServletContainerException) {
if (ex instanceof EmbeddedServletContainerException
|| ex.getCause() instanceof EmbeddedServletContainerException) {
logger.warn("Could not start embedded container (management endpoints are still available through JMX)");
}
else {
throw e;
throw ex;
}
}
};

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2014 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.

View File

@ -178,7 +178,7 @@ public class ThymeleafAutoConfiguration {
resolver.setTemplateEngine(this.templateEngine);
resolver.setCharacterEncoding(this.environment.getProperty("encoding",
"UTF-8"));
resolver.setContentType(addEncoding(
resolver.setContentType(appendCharset(
this.environment.getProperty("contentType", "text/html"),
resolver.getCharacterEncoding()));
resolver.setExcludedViewNames(this.environment.getProperty(
@ -191,13 +191,11 @@ public class ThymeleafAutoConfiguration {
return resolver;
}
private String addEncoding(String type, String charset) {
private String appendCharset(String type, String charset) {
if (type.contains("charset=")) {
return type;
}
else {
return type + ";charset=" + charset;
}
return type + ";charset=" + charset;
}
}

View File

@ -143,7 +143,7 @@ public class WebMvcAutoConfiguration {
@Value("${spring.resources.cachePeriod:}")
private Integer cachePeriod;
@Value("${spring.mvc.locale:}")
private String locale = "";

View File

@ -38,6 +38,7 @@ import static org.junit.Assert.assertTrue;
public class SecurityPropertiesTests {
private SecurityProperties security = new SecurityProperties();
private RelaxedDataBinder binder = new RelaxedDataBinder(this.security, "security");
@Before

View File

@ -149,7 +149,6 @@ public class WebMvcAutoConfigurationTests {
equalTo((Resource) new ClassPathResource("/foo/")));
}
@Test(expected = NoSuchBeanDefinitionException.class)
public void noLocaleResolver() throws Exception {
this.context = new AnnotationConfigEmbeddedWebApplicationContext();
this.context.register(AllResources.class, Config.class,
@ -157,6 +156,7 @@ public class WebMvcAutoConfigurationTests {
HttpMessageConvertersAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
this.thrown.expect(NoSuchBeanDefinitionException.class);
this.context.getBean(LocaleResolver.class);
}
@ -164,8 +164,7 @@ public class WebMvcAutoConfigurationTests {
public void overrideLocale() throws Exception {
this.context = new AnnotationConfigEmbeddedWebApplicationContext();
// set fixed locale
EnvironmentTestUtils.addEnvironment(this.context,
"spring.mvc.locale:en_UK");
EnvironmentTestUtils.addEnvironment(this.context, "spring.mvc.locale:en_UK");
this.context.register(AllResources.class, Config.class,
WebMvcAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
@ -176,11 +175,9 @@ public class WebMvcAutoConfigurationTests {
request.addPreferredLocale(StringUtils.parseLocaleString("nl_NL"));
LocaleResolver localeResolver = this.context.getBean(LocaleResolver.class);
Locale locale = localeResolver.resolveLocale(request);
assertThat(localeResolver,
instanceOf(FixedLocaleResolver.class));
assertThat(localeResolver, instanceOf(FixedLocaleResolver.class));
// test locale resolver uses fixed locale and not user preferred locale
assertThat(locale.toString(),
equalTo("en_UK"));
assertThat(locale.toString(), equalTo("en_UK"));
}
@SuppressWarnings("unchecked")

View File

@ -77,7 +77,7 @@ content into your application; rather pick only the properties that you need.
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.contentType=text/html # ;charset=<encoding> is added
spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added
spring.thymeleaf.cache=true # set to false for hot refresh
# INTERNATIONALIZATION ({sc-spring-boot-autoconfigure}/MessageSourceAutoConfiguration.{sc-ext}[MessageSourceAutoConfiguration])

View File

@ -365,7 +365,7 @@ that and be sure that it has initialized is to add a `@Bean` of type
out of the event when it is published.
A really useful thing to do in is to use `@IntegrationTest` to set `server.port=0`
and then inject the actual ("local") port as a `@Value`. Example:
and then inject the actual (``local'') port as a `@Value`. For example:
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@ -377,8 +377,8 @@ and then inject the actual ("local") port as a `@Value`. Example:
@Autowired
EmbeddedWebApplicationContext server;
@Value("${local.server.port}")
@Value("${local.server.port}")
int port;
// ...
@ -386,6 +386,8 @@ and then inject the actual ("local") port as a `@Value`. Example:
}
----
[[howto-configure-tomcat]]
=== Configure Tomcat
Generally you can follow the advice from
@ -630,6 +632,8 @@ then `http://localhost:8080/thing` will serve a JSON representation of it by def
Sometimes in a browser you might see XML responses (but by default only if `MyThing` was
a JAXB object) because browsers tend to send accept headers that prefer XML.
[[howto-write-an-xml-rest-service]]
=== Write an XML REST service
Since JAXB is in the JDK the same example as we used for JSON would work, as long as the
@ -637,15 +641,16 @@ Since JAXB is in the JDK the same example as we used for JSON would work, as lon
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@XmlRootElement
@XmlRootElement
public class MyThing {
private String name;
// .. getters and setters
private String name;
// .. getters and setters
}
----
To get the server to render XML instead of JSON you might have to send
an `Accept: text/xml` header (or use a browser).
To get the server to render XML instead of JSON you might have to send an
`Accept: text/xml` header (or use a browser).
[[howto-customize-the-jackson-objectmapper]]
@ -1009,7 +1014,7 @@ not something you want to be on the classpath in production. It is a Hibernate f
Spring JDBC has a `DataSource` initializer feature. Spring Boot enables it by default and
loads SQL from the standard locations `schema.sql` and `data.sql` (in the root of the
classpath). In addition Spring Boot will load a file `schema-${platform}.sql` where
`platform` is the value of `spring.datasource.platform`, e.g. you might choose to set
`platform` is the value of `spring.datasource.platform`, e.g. you might choose to set
it to the vendor name of the database (`hsqldb`, `h2`, `oracle`, `mysql`,
`postgresql` etc.). Spring Boot enables the failfast feature of the Spring JDBC
initializer by default, so if the scripts cause exceptions the application will fail

View File

@ -740,18 +740,15 @@ if needed.
[[production-ready-error-handling]]
== Error Handling
Spring Boot Actuator provides an `/error` mapping by default that handles all errors in a
sensible way, and it is registered as a ``global'' error page in the servlet container.
For machine clients it will produce a JSON response with details of the error, the HTTP
status and the exception message. For browser clients there is a ``whitelabel'' error
view that renders the same data in HTML format (to customize it just add a `View` that
resolves to ``error'').
Spring Boot Actuator provides an `/error` mapping by default that
handles all errors in a sensible way, and it is registered as a
"global" error page in the servlet container. For machine clients it
will produce a JSON response with details of the error, the HTTP
status and the exception message. For browser clients there is a
"whitelabel" error view that renders the same data in HTML format (to
customize it just add a `View` that resolves to ``error'').
If you want more specific error
pages for some conditions, the embedded servlet containers support a
uniform Java DSL for customizing the error handling. For example:
If you want more specific error pages for some conditions, the embedded servlet containers
support a uniform Java DSL for customizing the error handling. For example:
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@ -772,11 +769,11 @@ uniform Java DSL for customizing the error handling. For example:
}
----
You can also use regular Spring MVC features like http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-exception-handlers[`@ExceptionHandler`
methods] and http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-controller-advice[`@ControllerAdvice`].
[[production-ready-process-monitoring]]
== Process monitoring
In Spring Boot Actuator you can find `ApplicationPidListener` which creates file
@ -789,10 +786,11 @@ ways described below.
[[production-ready-process-monitoring-configuration]]
=== Extend configuration
In `META-INF/spring.factories` file you have to activate the listener:
[indent=0]
----
org.springframework.context.ApplicationListener=\
org.springframework.boot.actuate.system.ApplicationPidListener
org.springframework.context.ApplicationListener=\
org.springframework.boot.actuate.system.ApplicationPidListener
----

View File

@ -231,24 +231,23 @@ default `name`. When running in production, an `application.properties` can be p
outside of your jar that overrides `name`; and for one-off testing, you can launch with
a specific command line switch (e.g. `java -jar app.jar --name="Spring"`).
The `RandomValuePropertySource` is useful for injecting random values
(e.g. into secrets or test cases). It can produce integers, longs or
strings, e.g.
The `RandomValuePropertySource` is useful for injecting random values (e.g. into secrets
or test cases). It can produce integers, longs or strings, e.g.
[source,properties,indent=0]
----
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
----
The `random.int*` syntax is `OPEN value (,max) CLOSE` where the
`OPEN,CLOSE` are any character and `value,max` are integers. If
`max` is provided then `value` is the minimum value and `max` is the
maximum (exclusive).
The `random.int*` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any
character and `value,max` are integers. If `max` is provided then `value` is the minimum
value and `max` is the maximum (exclusive).
[[boot-features-external-config-command-line-args]]
=== Accessing command line properties
@ -372,15 +371,15 @@ Would be transformed into these properties:
environments.prod.name=My Cool App
----
YAML lists are represented as property keys with `[index]` dereferencers,
YAML lists are represented as property keys with `[index]` dereferencers,
for example this YAML:
[source,yaml,indent=0]
----
my:
servers:
- dev.bar.com
- foo.bar.com
servers:
- dev.bar.com
- foo.bar.com
----
Would be transformed into these properties:
@ -391,22 +390,25 @@ Would be transformed into these properties:
my.servers[1]=foo.bar.com
----
To bind to properties like that using the Spring `DataBinder`
utilities (which is what `@ConfigurationProperties` does) you need to
have a property in the target bean of type `java.util.List` (or `Set`)
and you either need to provide a setter, or initialize it with a
mutable value, e.g. this will bind to the properties above
To bind to properties like that using the Spring `DataBinder` utilities (which is what
`@ConfigurationProperties` does) you need to have a property in the target bean of type
`java.util.List` (or `Set`) and you either need to provide a setter, or initialize it
with a mutable value, e.g. this will bind to the properties above
[source,java,indent=0]
----
@ConfigurationProperties(prefix="my")
public class Config {
private List<String> servers = new ArrayList<String>();
public List<String> getServers() { return this.servers; }
}
@ConfigurationProperties(prefix="my")
public class Config {
private List<String> servers = new ArrayList<String>();
public List<String> getServers() {
return this.servers;
}
}
----
[[boot-features-external-config-exposing-yaml-to-spring]]
==== Exposing YAML as properties in the Spring Environment
The `YamlPropertySourceLoader` class can be used to expose YAML as a `PropertySource`
@ -1570,9 +1572,10 @@ interaction. For Example:
}
----
To change the port you can add environment properties to
`@IntegrationTest` as colon- or equals-separated name-value pairs,
e.g. `@IntegrationTest("server.port:9000")`.
To change the port you can add environment properties to `@IntegrationTest` as colon- or
equals-separated name-value pairs, e.g. `@IntegrationTest("server.port:9000")`.
[[boot-features-test-utilities]]
=== Test utilities

View File

@ -16,8 +16,6 @@
package sample.actuator.ui;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
@ -34,6 +32,8 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
/**
* Integration tests for separate management and main service ports.
*
@ -42,7 +42,7 @@ import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleActuatorUiApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0", "management.port:0"})
@IntegrationTest({ "server.port=0", "management.port:0" })
@DirtiesContext
public class SampleActuatorUiApplicationPortTests {

View File

@ -23,8 +23,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
@ -58,8 +58,8 @@ public class SampleActuatorUiApplicationTests {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = new TestRestTemplate().exchange(
"http://localhost:" + port, HttpMethod.GET, new HttpEntity<Void>(headers),
String.class);
"http://localhost:" + this.port, HttpMethod.GET, new HttpEntity<Void>(
headers), String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), entity
.getBody().contains("<title>Hello"));
@ -68,7 +68,7 @@ public class SampleActuatorUiApplicationTests {
@Test
public void testCss() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/css/bootstrap.min.css", String.class);
"http://localhost:" + this.port + "/css/bootstrap.min.css", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body"));
}
@ -77,7 +77,7 @@ public class SampleActuatorUiApplicationTests {
public void testMetrics() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/metrics", Map.class);
"http://localhost:" + this.port + "/metrics", Map.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
}
@ -86,8 +86,8 @@ public class SampleActuatorUiApplicationTests {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = new TestRestTemplate().exchange(
"http://localhost:" + port + "/error", HttpMethod.GET, new HttpEntity<Void>(
headers), String.class);
"http://localhost:" + this.port + "/error", HttpMethod.GET,
new HttpEntity<Void>(headers), String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody()
.contains("<html>"));

View File

@ -53,7 +53,7 @@ public class EndpointsPropertiesSampleActuatorApplicationTests {
public void testCustomErrorPath() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", "password")
.getForEntity("http://localhost:" + port + "/oops", Map.class);
.getForEntity("http://localhost:" + this.port + "/oops", Map.class);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -64,7 +64,7 @@ public class EndpointsPropertiesSampleActuatorApplicationTests {
@Test
public void testCustomContextPath() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/admin/health", String.class);
"http://localhost:" + this.port + "/admin/health", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
String body = entity.getBody();
assertEquals("ok", body);

View File

@ -16,8 +16,6 @@
package sample.actuator;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
@ -34,6 +32,8 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
/**
* Integration tests for separate management and main service ports.
*
@ -42,7 +42,8 @@ import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleActuatorApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0", "management.port=0", "management.address=127.0.0.1", "management.contextPath:/admin"})
@IntegrationTest({ "server.port=0", "management.port=0", "management.address=127.0.0.1",
"management.contextPath:/admin" })
@DirtiesContext
public class ManagementAddressActuatorApplicationTests {

View File

@ -16,8 +16,6 @@
package sample.actuator;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
@ -34,6 +32,8 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
/**
* Integration tests for separate management and main service ports.
*
@ -42,7 +42,7 @@ import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleActuatorApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0", "management.port=0"})
@IntegrationTest({ "server.port=0", "management.port=0" })
@DirtiesContext
public class ManagementPortSampleActuatorApplicationTests {

View File

@ -16,8 +16,6 @@
package sample.actuator;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
@ -34,6 +32,8 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
/**
* Integration tests for switching off management endpoints.
*
@ -42,13 +42,13 @@ import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleActuatorApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0", "management.port=-1"})
@IntegrationTest({ "server.port=0", "management.port=-1" })
@DirtiesContext
public class NoManagementSampleActuatorApplicationTests {
@Autowired
private SecurityProperties security;
@Value("${local.server.port}")
private int port = 0;
@ -56,7 +56,7 @@ public class NoManagementSampleActuatorApplicationTests {
public void testHome() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port, Map.class);
.getForEntity("http://localhost:" + this.port, Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -68,7 +68,7 @@ public class NoManagementSampleActuatorApplicationTests {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port + "/metrics", Map.class);
.getForEntity("http://localhost:" + this.port + "/metrics", Map.class);
assertEquals(HttpStatus.NOT_FOUND, entity.getStatusCode());
}

View File

@ -65,7 +65,7 @@ public class SampleActuatorApplicationTests {
public void testHomeIsSecure() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, Map.class);
"http://localhost:" + this.port, Map.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -78,16 +78,16 @@ public class SampleActuatorApplicationTests {
public void testMetricsIsSecure() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/metrics", Map.class);
"http://localhost:" + this.port + "/metrics", Map.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
entity = new TestRestTemplate().getForEntity("http://localhost:" + port + "/metrics/",
Map.class);
entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port
+ "/metrics/", Map.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
entity = new TestRestTemplate().getForEntity("http://localhost:" + port + "/metrics/foo",
Map.class);
entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port
+ "/metrics/foo", Map.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/metrics.json", Map.class);
entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port
+ "/metrics.json", Map.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
}
@ -95,7 +95,7 @@ public class SampleActuatorApplicationTests {
public void testHome() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port, Map.class);
.getForEntity("http://localhost:" + this.port, Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -107,7 +107,7 @@ public class SampleActuatorApplicationTests {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port + "/metrics", Map.class);
.getForEntity("http://localhost:" + this.port + "/metrics", Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -118,7 +118,7 @@ public class SampleActuatorApplicationTests {
public void testEnv() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port + "/env", Map.class);
.getForEntity("http://localhost:" + this.port + "/env", Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -128,7 +128,7 @@ public class SampleActuatorApplicationTests {
@Test
public void testHealth() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/health", String.class);
"http://localhost:" + this.port + "/health", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("ok", entity.getBody());
}
@ -136,7 +136,7 @@ public class SampleActuatorApplicationTests {
@Test
public void testErrorPage() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port + "/foo", String.class);
.getForEntity("http://localhost:" + this.port + "/foo", String.class);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode());
String body = entity.getBody();
assertNotNull(body);
@ -149,8 +149,8 @@ public class SampleActuatorApplicationTests {
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
HttpEntity<?> request = new HttpEntity<Void>(headers);
ResponseEntity<String> entity = new TestRestTemplate("user", getPassword())
.exchange("http://localhost:" + port + "/foo", HttpMethod.GET, request,
String.class);
.exchange("http://localhost:" + this.port + "/foo", HttpMethod.GET,
request, String.class);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode());
String body = entity.getBody();
assertNotNull("Body was null", body);
@ -160,10 +160,11 @@ public class SampleActuatorApplicationTests {
@Test
public void testTrace() throws Exception {
new TestRestTemplate().getForEntity("http://localhost:" + port + "/health", String.class);
new TestRestTemplate().getForEntity("http://localhost:" + this.port + "/health",
String.class);
@SuppressWarnings("rawtypes")
ResponseEntity<List> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port + "/trace", List.class);
.getForEntity("http://localhost:" + this.port + "/trace", List.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
List<Map<String, Object>> list = entity.getBody();
@ -178,7 +179,7 @@ public class SampleActuatorApplicationTests {
public void testErrorPageDirectAccess() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/error", Map.class);
"http://localhost:" + this.port + "/error", Map.class);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -190,7 +191,7 @@ public class SampleActuatorApplicationTests {
public void testBeans() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<List> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port + "/beans", List.class);
.getForEntity("http://localhost:" + this.port + "/beans", List.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals(1, entity.getBody().size());
@SuppressWarnings("unchecked")

View File

@ -24,8 +24,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
@ -57,7 +57,7 @@ public class ShutdownSampleActuatorApplicationTests {
public void testHome() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port, Map.class);
.getForEntity("http://localhost:" + this.port, Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -68,7 +68,8 @@ public class ShutdownSampleActuatorApplicationTests {
public void testShutdown() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.postForEntity("http://localhost:" + port + "/shutdown", null, Map.class);
.postForEntity("http://localhost:" + this.port + "/shutdown", null,
Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();

View File

@ -22,8 +22,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
@ -44,7 +44,7 @@ import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleActuatorApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port:0", "management.security.enabled:false"})
@IntegrationTest({ "server.port:0", "management.security.enabled:false" })
@DirtiesContext
@ActiveProfiles("unsecure-management")
public class UnsecureManagementSampleActuatorApplicationTests {
@ -56,7 +56,7 @@ public class UnsecureManagementSampleActuatorApplicationTests {
public void testHomeIsSecure() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, Map.class);
"http://localhost:" + this.port, Map.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
@ -75,7 +75,7 @@ public class UnsecureManagementSampleActuatorApplicationTests {
}
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/metrics", Map.class);
"http://localhost:" + this.port + "/metrics", Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();

View File

@ -16,9 +16,6 @@
package sample.actuator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.Map;
import org.junit.Test;
@ -33,6 +30,9 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* Integration tests for unsecured service endpoints (even with Spring Security on
* classpath).
@ -42,7 +42,7 @@ import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleActuatorApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port:0", "security.basic.enabled:false"})
@IntegrationTest({ "server.port:0", "security.basic.enabled:false" })
@DirtiesContext
public class UnsecureSampleActuatorApplicationTests {
@ -53,7 +53,7 @@ public class UnsecureSampleActuatorApplicationTests {
public void testHome() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, Map.class);
"http://localhost:" + this.port, Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();

View File

@ -20,8 +20,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
@ -48,7 +48,7 @@ public class SampleJettyApplicationTests {
@Test
public void testHome() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, String.class);
"http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("Hello World", entity.getBody());
}

View File

@ -16,8 +16,6 @@
package sample.servlet;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -32,6 +30,8 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
/**
* Basic integration tests for demo application.
*
@ -53,14 +53,14 @@ public class SampleServletApplicationTests {
@Test
public void testHomeIsSecure() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, String.class);
"http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
}
@Test
public void testHome() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + port, String.class);
.getForEntity("http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("Hello World", entity.getBody());
}

View File

@ -27,8 +27,8 @@ import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfi
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@ -41,6 +41,7 @@ import org.springframework.test.context.web.WebAppConfiguration;
import sample.tomcat.NonAutoConfigurationSampleTomcatApplicationTests.NonAutoConfigurationSampleTomcatApplication;
import sample.tomcat.service.HelloWorldService;
import sample.tomcat.web.SampleController;
import static org.junit.Assert.assertEquals;
/**
@ -76,7 +77,7 @@ public class NonAutoConfigurationSampleTomcatApplicationTests {
@Test
public void testHome() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, String.class);
"http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("Hello World", entity.getBody());
}

View File

@ -20,8 +20,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
@ -48,7 +48,7 @@ public class SampleTomcatApplicationTests {
@Test
public void testHome() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, String.class);
"http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("Hello World", entity.getBody());
}

View File

@ -20,8 +20,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
@ -49,7 +49,7 @@ public class SampleTraditionalApplicationTests {
@Test
public void testHomeJsp() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, String.class);
"http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
String body = entity.getBody();
assertTrue("Wrong body:\n" + body, body.contains("<html>"));
@ -59,7 +59,7 @@ public class SampleTraditionalApplicationTests {
@Test
public void testStaticPage() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/index.html", String.class);
"http://localhost:" + this.port + "/index.html", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
String body = entity.getBody();
assertTrue("Wrong body:\n" + body, body.contains("<html>"));

View File

@ -20,8 +20,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
@ -49,7 +49,7 @@ public class SampleWebJspApplicationTests {
@Test
public void testJspWithEl() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, String.class);
"http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body:\n" + entity.getBody(),
entity.getBody().contains("/resources/text.txt"));

View File

@ -16,9 +16,6 @@
package sample.ui.method;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -41,6 +38,9 @@ import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Basic integration tests for demo application.
*
@ -61,8 +61,8 @@ public class SampleMethodSecurityApplicationTests {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = new TestRestTemplate().exchange(
"http://localhost:" + port, HttpMethod.GET, new HttpEntity<Void>(headers),
String.class);
"http://localhost:" + this.port, HttpMethod.GET, new HttpEntity<Void>(
headers), String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), entity
.getBody().contains("<title>Login"));
@ -77,12 +77,12 @@ public class SampleMethodSecurityApplicationTests {
form.set("password", "admin");
getCsrf(form, headers);
ResponseEntity<String> entity = new TestRestTemplate().exchange(
"http://localhost:" + port + "/login", HttpMethod.POST,
"http://localhost:" + this.port + "/login", HttpMethod.POST,
new HttpEntity<MultiValueMap<String, String>>(form, headers),
String.class);
assertEquals(HttpStatus.FOUND, entity.getStatusCode());
assertEquals("http://localhost:" + port + "/", entity.getHeaders().getLocation()
.toString());
assertEquals("http://localhost:" + this.port + "/", entity.getHeaders()
.getLocation().toString());
}
@Test
@ -94,7 +94,7 @@ public class SampleMethodSecurityApplicationTests {
form.set("password", "user");
getCsrf(form, headers);
ResponseEntity<String> entity = new TestRestTemplate().exchange(
"http://localhost:" + port + "/login", HttpMethod.POST,
"http://localhost:" + this.port + "/login", HttpMethod.POST,
new HttpEntity<MultiValueMap<String, String>>(form, headers),
String.class);
assertEquals(HttpStatus.FOUND, entity.getStatusCode());
@ -110,28 +110,28 @@ public class SampleMethodSecurityApplicationTests {
@Test
public void testManagementProtected() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + port + "/beans", String.class);
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.port + "/beans", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
}
@Test
public void testManagementAuthorizedAccess() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate("admin", "admin")
.getForEntity("http://localhost:" + port + "/beans", String.class);
.getForEntity("http://localhost:" + this.port + "/beans", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
}
@Test
public void testManagementUnauthorizedAccess() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate("user", "user")
.getForEntity("http://localhost:" + port + "/beans", String.class);
.getForEntity("http://localhost:" + this.port + "/beans", String.class);
assertEquals(HttpStatus.FORBIDDEN, entity.getStatusCode());
}
private void getCsrf(MultiValueMap<String, String> form, HttpHeaders headers) {
ResponseEntity<String> page = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/login", String.class);
"http://localhost:" + this.port + "/login", String.class);
String cookie = page.getHeaders().getFirst("Set-Cookie");
headers.set("Cookie", cookie);
String body = page.getBody();

View File

@ -22,8 +22,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
@ -57,8 +57,8 @@ public class SampleSecureApplicationTests {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = new TestRestTemplate().exchange(
"http://localhost:" + port, HttpMethod.GET, new HttpEntity<Void>(headers),
String.class);
"http://localhost:" + this.port, HttpMethod.GET, new HttpEntity<Void>(
headers), String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), entity
.getBody().contains("<title>Login"));
@ -67,7 +67,7 @@ public class SampleSecureApplicationTests {
@Test
public void testCss() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/css/bootstrap.min.css", String.class);
"http://localhost:" + this.port + "/css/bootstrap.min.css", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body"));
}

View File

@ -16,9 +16,6 @@
package sample.ui;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
@ -32,6 +29,9 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Basic integration tests for demo application.
*
@ -43,14 +43,14 @@ import org.springframework.test.context.web.WebAppConfiguration;
@IntegrationTest("server.port=0")
@DirtiesContext
public class SampleWebStaticApplicationTests {
@Value("${local.server.port}")
private int port = 0;
@Test
public void testHome() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, String.class);
"http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), entity
.getBody().contains("<title>Static"));
@ -59,8 +59,8 @@ public class SampleWebStaticApplicationTests {
@Test
public void testCss() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/webjars/bootstrap/3.0.3/css/bootstrap.min.css",
String.class);
"http://localhost:" + this.port
+ "/webjars/bootstrap/3.0.3/css/bootstrap.min.css", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body"));
assertEquals("Wrong content type:\n" + entity.getHeaders().getContentType(),

View File

@ -22,8 +22,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
@ -54,7 +54,7 @@ public class SampleWebUiApplicationTests {
@Test
public void testHome() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port, String.class);
"http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), entity
.getBody().contains("<title>Messages"));
@ -67,16 +67,16 @@ public class SampleWebUiApplicationTests {
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.set("text", "FOO text");
map.set("summary", "FOO");
URI location = new TestRestTemplate().postForLocation("http://localhost:" + port,
map);
URI location = new TestRestTemplate().postForLocation("http://localhost:"
+ this.port, map);
assertTrue("Wrong location:\n" + location,
location.toString().contains("localhost:" + port));
location.toString().contains("localhost:" + this.port));
}
@Test
public void testCss() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + port + "/css/bootstrap.min.css", String.class);
"http://localhost:" + this.port + "/css/bootstrap.min.css", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body"));
}

View File

@ -16,8 +16,6 @@
package samples.websocket.echo;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ -47,6 +45,8 @@ import samples.websocket.client.SimpleGreetingService;
import samples.websocket.config.SampleWebSocketsApplication;
import samples.websocket.echo.CustomContainerWebSocketsApplicationTests.CustomContainerConfiguration;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { SampleWebSocketsApplication.class,
CustomContainerConfiguration.class })
@ -57,7 +57,7 @@ public class CustomContainerWebSocketsApplicationTests {
private static Log logger = LogFactory
.getLog(CustomContainerWebSocketsApplicationTests.class);
private static int PORT = SocketUtils.findAvailableTcpPort();
private static final String WS_URI = "ws://localhost:" + PORT + "/ws/echo/websocket";

View File

@ -16,8 +16,6 @@
package samples.websocket.echo;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ -45,6 +43,8 @@ import samples.websocket.client.SimpleClientWebSocketHandler;
import samples.websocket.client.SimpleGreetingService;
import samples.websocket.config.SampleWebSocketsApplication;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleWebSocketsApplication.class)
@WebAppConfiguration
@ -58,10 +58,10 @@ public class SampleWebSocketsApplicationTests {
@Value("${local.server.port}")
private int port;
@Before
public void init() {
WS_URI = "ws://localhost:" + port + "/echo/websocket";
WS_URI = "ws://localhost:" + this.port + "/echo/websocket";
}
@Test

View File

@ -18,8 +18,6 @@ package org.springframework.boot.gradle.task;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
@ -30,7 +28,7 @@ import org.springframework.boot.loader.tools.LibraryScope;
/**
* Expose Gradle {@link Configuration}s as {@link Libraries}.
*
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@ -44,7 +42,7 @@ class ProjectLibraries implements Libraries {
/**
* Create a new {@link ProjectLibraries} instance of the specified {@link Project}.
*
*
* @param project the gradle project
*/
public ProjectLibraries(Project project) {
@ -53,7 +51,7 @@ class ProjectLibraries implements Libraries {
/**
* Set the name of the provided configuration. Defaults to 'providedRuntime'.
*
*
* @param providedConfigurationName the providedConfigurationName to set
*/
public void setProvidedConfigurationName(String providedConfigurationName) {

View File

@ -111,7 +111,9 @@ public class RunMojo extends AbstractMojo {
getLog().info("Attaching agent: " + this.agent);
if (this.noverify != null && this.noverify && !AgentAttacher.hasNoVerify()) {
throw new MojoExecutionException(
"The JVM must be started with -noverify for this agent to work. You can use MAVEN_OPTS=-noverify to add that flag.");
"The JVM must be started with -noverify for "
+ "this agent to work. You can use MAVEN_OPTS=-noverify "
+ "to add that flag.");
}
AgentAttacher.attach(this.agent);
}

View File

@ -89,10 +89,7 @@ import org.springframework.web.context.support.WebApplicationContextUtils;
*/
public class EmbeddedWebApplicationContext extends GenericWebApplicationContext {
/**
*
*/
private static final String SERVER = "server";
private static final String DEFAULT_SERVER_NAME = "server";
/**
* Constant value for the DispatcherServlet bean name. A Servlet bean with this name
@ -166,7 +163,7 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext
EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
this.embeddedServletContainer = containerFactory
.getEmbeddedServletContainer(getSelfInitializer());
this.containers.put(SERVER, this.embeddedServletContainer);
this.containers.put(DEFAULT_SERVER_NAME, this.embeddedServletContainer);
}
else if (getServletContext() != null) {
try {
@ -391,7 +388,7 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext
try {
this.embeddedServletContainer.stop();
this.embeddedServletContainer = null;
this.containers.remove(SERVER);
this.containers.remove(DEFAULT_SERVER_NAME);
}
catch (Exception ex) {
throw new IllegalStateException(ex);
@ -439,7 +436,6 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext
* A registry of embedded containers by name. The
* {@link #getEmbeddedServletContainer() canonical container} is called "server".
* Anyone else who creates one can register it with whatever name they please.
*
* @return the containers
*/
public Map<String, EmbeddedServletContainer> getEmbeddedServletContainers() {

View File

@ -70,7 +70,6 @@ public abstract class RegistrationBean implements ServletContextInitializer, Ord
/**
* Flag to indicate that the registration is enabled.
*
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2014 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2014 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.
@ -18,34 +18,36 @@ package org.springframework.boot.test;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
/**
* Listener that injects the server port (if one is discoverable from the application
* context)into a field annotated with {@link Value @Value("dynamic.port")}.
* Listener that injects the server port into an {@link Environment} property named
* {@literal local.&lt;server&gt;.port}. Useful when the server is running on a dynamic
* port.
*
* @author Dave Syer
*/
public class EmbeddedServletContainerListener extends AbstractTestExecutionListener {
public class EmbeddedServletContainerTestExecutionListener extends
AbstractTestExecutionListener {
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
ApplicationContext context = testContext.getApplicationContext();
if (!(context instanceof EmbeddedWebApplicationContext)) {
return;
if (context instanceof EmbeddedWebApplicationContext) {
prepareTestInstance((EmbeddedWebApplicationContext) context);
}
EmbeddedWebApplicationContext embedded = (EmbeddedWebApplicationContext) context;
Map<String, EmbeddedServletContainer> containers = embedded
.getEmbeddedServletContainers();
for (String name : containers.keySet()) {
int port = containers.get(name).getPort();
EnvironmentTestUtils.addEnvironment(embedded, "local." + name + ".port:"
+ port);
}
private void prepareTestInstance(EmbeddedWebApplicationContext context) {
for (Map.Entry<String, EmbeddedServletContainer> entry : context
.getEmbeddedServletContainers().entrySet()) {
EnvironmentTestUtils.addEnvironment(context, "local." + entry.getKey()
+ ".port:" + entry.getValue().getPort());
}
}
}

View File

@ -37,7 +37,6 @@ public abstract class EnvironmentTestUtils {
* Add additional (high priority) values to an {@link Environment} owned by an
* {@link ApplicationContext}. Name-value pairs can be specified with colon (":") or
* equals ("=") separators.
*
* @param context the context with an environment to modify
* @param pairs the name:value pairs
*/
@ -49,7 +48,6 @@ public abstract class EnvironmentTestUtils {
/**
* Add additional (high priority) values to an {@link Environment}. Name-value pairs
* can be specified with colon (":") or equals ("=") separators.
*
* @param environment the environment to modify
* @param pairs the name:value pairs
*/
@ -61,7 +59,6 @@ public abstract class EnvironmentTestUtils {
/**
* Add additional (high priority) values to an {@link Environment}. Name-value pairs
* can be specified with colon (":") or equals ("=") separators.
*
* @param environment the environment to modify
* @param name the property source name
* @param pairs the name:value pairs

View File

@ -23,6 +23,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
@ -40,11 +41,17 @@ import org.springframework.test.context.transaction.TransactionalTestExecutionLi
@Target(ElementType.TYPE)
// Leave out the ServletTestExecutionListener because it only deals with Mock* servlet
// stuff. A real embedded application will not need the mocks.
@TestExecutionListeners(listeners = { EmbeddedServletContainerListener.class,
@TestExecutionListeners(listeners = {
EmbeddedServletContainerTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class })
public @interface IntegrationTest {
String[] value() default "";
/**
* Properties in form {@literal key=value} that should be added to the Spring
* {@link Environment} before the test runs.
*/
String[] value() default {};
}

View File

@ -18,6 +18,7 @@ package org.springframework.boot.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@ -66,19 +67,18 @@ import org.springframework.web.context.support.GenericWebApplicationContext;
public class SpringApplicationContextLoader extends AbstractContextLoader {
@Override
public ApplicationContext loadContext(MergedContextConfiguration mergedConfig)
public ApplicationContext loadContext(MergedContextConfiguration config)
throws Exception {
SpringApplication application = getSpringApplication();
application.setSources(getSources(mergedConfig));
if (!ObjectUtils.isEmpty(mergedConfig.getActiveProfiles())) {
application.setAdditionalProfiles(mergedConfig.getActiveProfiles());
application.setSources(getSources(config));
if (!ObjectUtils.isEmpty(config.getActiveProfiles())) {
application.setAdditionalProfiles(config.getActiveProfiles());
}
application.setDefaultProperties(getArgs(mergedConfig));
List<ApplicationContextInitializer<?>> initializers = getInitializers(
mergedConfig, application);
if (mergedConfig instanceof WebMergedContextConfiguration) {
new WebConfigurer().configure(mergedConfig, application, initializers);
application.setDefaultProperties(getEnvironmentProperties(config));
List<ApplicationContextInitializer<?>> initializers = getInitializers(config,
application);
if (config instanceof WebMergedContextConfiguration) {
new WebConfigurer().configure(config, application, initializers);
}
else {
application.setWebEnvironment(false);
@ -134,32 +134,41 @@ public class SpringApplicationContextLoader extends AbstractContextLoader {
.detectDefaultConfigurationClasses(declaringClass);
}
private Map<String, Object> getArgs(MergedContextConfiguration mergedConfig) {
Map<String, Object> args = new LinkedHashMap<String, Object>();
private Map<String, Object> getEnvironmentProperties(MergedContextConfiguration config) {
Map<String, Object> properties = new LinkedHashMap<String, Object>();
// JMX bean names will clash if the same bean is used in multiple contexts
args.put("spring.jmx.enabled", "false");
disableJmx(properties);
IntegrationTest annotation = AnnotationUtils.findAnnotation(
mergedConfig.getTestClass(), IntegrationTest.class);
if (annotation == null) {
// Not running an embedded server, just setting up web context
args.put("server.port", "-1");
}
else {
args.putAll(extractProperties(annotation.value()));
}
return args;
config.getTestClass(), IntegrationTest.class);
properties.putAll(getEnvironmentProperties(annotation));
return properties;
}
private Map<String, String> extractProperties(String[] values) {
Map<String, String> map = new HashMap<String, String>();
private void disableJmx(Map<String, Object> properties) {
properties.put("spring.jmx.enabled", "false");
}
private Map<String, String> getEnvironmentProperties(IntegrationTest annotation) {
if (annotation == null) {
return getDefaultEnvironmentProperties();
}
return extractEnvironmentProperties(annotation.value());
}
private Map<String, String> getDefaultEnvironmentProperties() {
return Collections.singletonMap("server.port", "-1");
}
private Map<String, String> extractEnvironmentProperties(String[] values) {
Map<String, String> properties = new HashMap<String, String>();
for (String pair : values) {
int index = pair.indexOf(":");
index = index < 0 ? index = pair.indexOf("=") : index;
index = (index < 0 ? index = pair.indexOf("=") : index);
String key = pair.substring(0, index > 0 ? index : pair.length());
String value = index > 0 ? pair.substring(index + 1) : "";
map.put(key.trim(), value.trim());
String value = (index > 0 ? pair.substring(index + 1) : "");
properties.put(key.trim(), value.trim());
}
return map;
return properties;
}
private List<ApplicationContextInitializer<?>> getInitializers(

View File

@ -264,7 +264,7 @@ public class RelaxedDataBinderTests {
bind(target, "nested.foo: bar\n" + "nested.value: 123");
assertEquals("123", target.getNested().get("value"));
}
@Test
public void testBindNestedMapOfString() throws Exception {
TargetWithNestedMapOfString target = new TargetWithNestedMapOfString();
@ -510,7 +510,7 @@ public class RelaxedDataBinderTests {
}
}
@SuppressWarnings("rawtypes")
public static class TargetWithNestedUntypedMap {
@ -526,7 +526,6 @@ public class RelaxedDataBinderTests {
}
public static class TargetWithNestedMapOfString {
private Map<String, String> nested;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2014 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.
@ -23,6 +23,8 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link RandomValuePropertySource}.
*
* @author Dave Syer
*/
public class RandomValuePropertySourceTests {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2014 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.
@ -21,6 +21,8 @@ import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link PropertySourcesLoader}.
*
* @author Dave Syer
*/
public class PropertySourcesLoaderTests {
@ -28,7 +30,7 @@ public class PropertySourcesLoaderTests {
private PropertySourcesLoader loader = new PropertySourcesLoader();
@Test
public void test() {
public void fileExtensions() {
assertTrue(this.loader.getAllFileExtensions().contains("yml"));
assertTrue(this.loader.getAllFileExtensions().contains("yaml"));
assertTrue(this.loader.getAllFileExtensions().contains("properties"));

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -24,6 +24,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Tests for {@link YamlPropertySourceLoader}.
*
* @author Dave Syer
*/
public class YamlPropertySourceLoaderTests {
@ -31,9 +33,9 @@ public class YamlPropertySourceLoaderTests {
private YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
@Test
public void test() throws Exception {
PropertySource<?> source = this.loader.load("resource", new ByteArrayResource(
"foo:\n bar: spam".getBytes()), null);
public void load() throws Exception {
ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes());
PropertySource<?> source = this.loader.load("resource", resource, null);
assertNotNull(source);
assertEquals("spam", source.getProperty("foo.bar"));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2014 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.
@ -23,6 +23,8 @@ import org.springframework.http.client.InterceptingClientHttpRequestFactory;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link TestRestTemplate}.
*
* @author Dave Syer
*/
public class TestRestTemplateTests {