Commit 0489a3b4 authored by Phillip Webb's avatar Phillip Webb

Polish

parent f3bcf94f
......@@ -150,39 +150,44 @@ public class ManagementWebSecurityAutoConfiguration {
@Override
public void init(WebSecurity builder) throws Exception {
if (this.server != null) {
IgnoredRequestConfigurer ignoring = builder.ignoring();
// The ignores are not cumulative, so to prevent overwriting the defaults
// we add them back.
Set<String> ignored = new LinkedHashSet<String>(
SpringBootWebSecurityConfiguration.getIgnored(this.security));
if (ignored.contains("none")) {
ignored.remove("none");
}
if (this.errorController != null) {
ignored.add(normalizePath(this.errorController.getErrorPath()));
}
String[] paths = this.server.getPathsArray(ignored);
RequestMatcher requestMatcher = this.management.getSecurity().isEnabled()
? null
: LazyEndpointPathRequestMatcher
.getRequestMatcher(this.contextResolver);
if (!ObjectUtils.isEmpty(paths)) {
List<RequestMatcher> matchers = new ArrayList<RequestMatcher>();
for (String pattern : paths) {
matchers.add(new AntPathRequestMatcher(pattern, null));
}
if (requestMatcher != null) {
matchers.add(requestMatcher);
}
requestMatcher = new OrRequestMatcher(matchers);
if (this.server == null) {
return;
}
IgnoredRequestConfigurer ignoring = builder.ignoring();
// The ignores are not cumulative, so to prevent overwriting the defaults
// we add them back.
Set<String> ignored = new LinkedHashSet<String>(
SpringBootWebSecurityConfiguration.getIgnored(this.security));
if (ignored.contains("none")) {
ignored.remove("none");
}
if (this.errorController != null) {
ignored.add(normalizePath(this.errorController.getErrorPath()));
}
RequestMatcher requestMatcher = getRequestMatcher();
String[] paths = this.server.getPathsArray(ignored);
if (!ObjectUtils.isEmpty(paths)) {
List<RequestMatcher> matchers = new ArrayList<RequestMatcher>();
for (String pattern : paths) {
matchers.add(new AntPathRequestMatcher(pattern, null));
}
if (requestMatcher != null) {
ignoring.requestMatchers(requestMatcher);
matchers.add(requestMatcher);
}
requestMatcher = new OrRequestMatcher(matchers);
}
if (requestMatcher != null) {
ignoring.requestMatchers(requestMatcher);
}
}
private RequestMatcher getRequestMatcher() {
if (this.management.getSecurity().isEnabled()) {
return null;
}
return LazyEndpointPathRequestMatcher.getRequestMatcher(this.contextResolver);
}
private String normalizePath(String errorPath) {
String result = StringUtils.cleanPath(errorPath);
if (!result.startsWith("/")) {
......@@ -239,10 +244,7 @@ public class ManagementWebSecurityAutoConfiguration {
@Override
protected void configure(HttpSecurity http) throws Exception {
// secure endpoints
RequestMatcher matcher = this.management.getSecurity().isEnabled()
? LazyEndpointPathRequestMatcher
.getRequestMatcher(this.contextResolver)
: null;
RequestMatcher matcher = getRequestMatcher();
if (matcher != null) {
// Always protect them if present
if (this.security.isRequireSsl()) {
......@@ -264,6 +266,14 @@ public class ManagementWebSecurityAutoConfiguration {
}
}
private RequestMatcher getRequestMatcher() {
if (this.management.getSecurity().isEnabled()) {
return LazyEndpointPathRequestMatcher
.getRequestMatcher(this.contextResolver);
}
return null;
}
private AuthenticationEntryPoint entryPoint() {
BasicAuthenticationEntryPoint entryPoint = new BasicAuthenticationEntryPoint();
entryPoint.setRealmName(this.security.getBasic().getRealm());
......
......@@ -65,15 +65,24 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
*/
protected void addBasicMetrics(Collection<Metric<?>> result) {
// NOTE: ManagementFactory must not be used here since it fails on GAE
result.add(new Metric<Long>("mem", Runtime.getRuntime().totalMemory() / 1024));
result.add(
new Metric<Long>("mem.free", Runtime.getRuntime().freeMemory() / 1024));
result.add(new Metric<Integer>("processors",
Runtime.getRuntime().availableProcessors()));
Runtime runtime = Runtime.getRuntime();
result.add(newMemoryMetric("mem",
runtime.totalMemory() + getTotalNonHeapMemoryIfPossible()));
result.add(newMemoryMetric("mem.free", runtime.freeMemory()));
result.add(new Metric<Integer>("processors", runtime.availableProcessors()));
result.add(new Metric<Long>("instance.uptime",
System.currentTimeMillis() - this.timestamp));
}
private long getTotalNonHeapMemoryIfPossible() {
try {
return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed();
}
catch (Throwable ex) {
return 0;
}
}
/**
* Add metrics from ManagementFactory if possible. Note that ManagementFactory is not
* available on Google App Engine.
......@@ -87,6 +96,7 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
result.add(new Metric<Double>("systemload.average",
ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage()));
addHeapMetrics(result);
addNonHeapMetrics(result);
addThreadMetrics(result);
addClassLoadingMetrics(result);
addGarbageCollectionMetrics(result);
......@@ -103,31 +113,27 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
protected void addHeapMetrics(Collection<Metric<?>> result) {
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean()
.getHeapMemoryUsage();
result.add(new Metric<Long>("heap.committed", memoryUsage.getCommitted() / 1024));
result.add(new Metric<Long>("heap.init", memoryUsage.getInit() / 1024));
result.add(new Metric<Long>("heap.used", memoryUsage.getUsed() / 1024));
result.add(new Metric<Long>("heap", memoryUsage.getMax() / 1024));
memoryUsage = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
result.add(
new Metric<Long>("nonheap.committed", memoryUsage.getCommitted() / 1024));
result.add(new Metric<Long>("nonheap.init", memoryUsage.getInit() / 1024));
result.add(new Metric<Long>("nonheap.used", memoryUsage.getUsed() / 1024));
result.add(new Metric<Long>("nonheap", memoryUsage.getMax() / 1024));
Metric<Long> mem = findMemory(result);
if (mem != null) {
mem.increment(new Long(memoryUsage.getUsed() / 1024).intValue());
}
result.add(newMemoryMetric("heap.committed", memoryUsage.getCommitted()));
result.add(newMemoryMetric("heap.init", memoryUsage.getInit()));
result.add(newMemoryMetric("heap.used", memoryUsage.getUsed()));
result.add(newMemoryMetric("heap", memoryUsage.getMax()));
}
private Metric<Long> findMemory(Collection<Metric<?>> result) {
for (Metric<?> metric : result) {
if ("mem".equals(metric.getName())) {
@SuppressWarnings("unchecked")
Metric<Long> value = (Metric<Long>) metric;
return value;
}
}
return null;
/**
* Add JVM non-heap metrics.
* @param result the result
*/
private void addNonHeapMetrics(Collection<Metric<?>> result) {
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean()
.getNonHeapMemoryUsage();
result.add(newMemoryMetric("nonheap.committed", memoryUsage.getCommitted()));
result.add(newMemoryMetric("nonheap.init", memoryUsage.getInit()));
result.add(newMemoryMetric("nonheap.used", memoryUsage.getUsed()));
result.add(newMemoryMetric("nonheap", memoryUsage.getMax()));
}
private Metric<Long> newMemoryMetric(String name, long bytes) {
return new Metric<Long>(name, bytes / 1024);
}
/**
......
......@@ -41,8 +41,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Integration tests for {@link HalBrowserMvcEndpoint}'s support for producing
* text/html
* Integration tests for {@link HalBrowserMvcEndpoint}'s support for producing text/html
*
* @author Dave Syer
* @author Andy Wilkinson
......
......@@ -44,8 +44,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Integration tests for {@link HalBrowserMvcEndpoint} when a custom management
* context path has been configured.
* Integration tests for {@link HalBrowserMvcEndpoint} when a custom management context
* path has been configured.
*
* @author Dave Syer
* @author Andy Wilkinson
......
......@@ -45,8 +45,8 @@ import static org.junit.Assert.assertTrue;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
/**
* Integration tests for {@link HalBrowserMvcEndpoint} when a custom server context
* path has been configured.
* Integration tests for {@link HalBrowserMvcEndpoint} when a custom server context path
* has been configured.
*
* @author Dave Syer
* @author Andy Wilkinson
......
......@@ -45,8 +45,8 @@ import static org.junit.Assert.assertTrue;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
/**
* Integration tests for {@link HalBrowserMvcEndpoint} when a custom server port has
* been configured.
* Integration tests for {@link HalBrowserMvcEndpoint} when a custom server port has been
* configured.
*
* @author Dave Syer
* @author Andy Wilkinson
......
......@@ -50,12 +50,14 @@ public abstract class SpringBootCondition implements Condition {
return outcome.isMatch();
}
catch (NoClassDefFoundError ex) {
throw new IllegalStateException("Could not evaluate condition on "
+ classOrMethodName + " due to " + ex.getMessage() + " not "
+ "found. Make sure your own configuration does not rely on "
+ "that class. This can also happen if you are "
+ "@ComponentScanning a springframework package (e.g. if you "
+ "put a @ComponentScan in the default package by mistake)", ex);
throw new IllegalStateException(
"Could not evaluate condition on " + classOrMethodName + " due to "
+ ex.getMessage() + " not "
+ "found. Make sure your own configuration does not rely on "
+ "that class. This can also happen if you are "
+ "@ComponentScanning a springframework package (e.g. if you "
+ "put a @ComponentScan in the default package by mistake)",
ex);
}
catch (RuntimeException ex) {
throw new IllegalStateException(
......
......@@ -78,6 +78,11 @@ import org.springframework.util.Assert;
@ConditionalOnClass({ Mongo.class, MongodStarter.class })
public class EmbeddedMongoAutoConfiguration {
private static final byte[] IP4_LOOPBACK_ADDRESS = { 127, 0, 0, 1 };
private static final byte[] IP6_LOOPBACK_ADDRESS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1 };
@Autowired
private MongoProperties properties;
......@@ -158,8 +163,7 @@ public class EmbeddedMongoAutoConfiguration {
private InetAddress getHost() throws UnknownHostException {
if (this.properties.getHost() == null) {
return InetAddress.getByAddress(Network.localhostIsIPv6()
? new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }
: new byte[] { 127, 0, 0, 1 });
? IP6_LOOPBACK_ADDRESS : IP4_LOOPBACK_ADDRESS);
}
return InetAddress.getByName(this.properties.getHost());
}
......
......@@ -204,7 +204,8 @@ public class FlywayAutoConfigurationTests {
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(flyway.getBaselineVersion(), equalTo(MigrationVersion.fromVersion("0")));
assertThat(flyway.getBaselineVersion(),
equalTo(MigrationVersion.fromVersion("0")));
}
private void registerAndRefresh(Class<?>... annotatedClasses) {
......
......@@ -146,8 +146,7 @@ public class OAuth2AutoConfigurationTests {
"security.oauth2.client.clientSecret:mysecret",
"security.oauth2.client.autoApproveScopes:read,write",
"security.oauth2.client.accessTokenValiditySeconds:40",
"security.oauth2.client.refreshTokenValiditySeconds:80"
);
"security.oauth2.client.refreshTokenValiditySeconds:80");
this.context.register(AuthorizationAndResourceServerConfiguration.class,
MinimalSecureWebApplication.class);
this.context.refresh();
......
......@@ -277,6 +277,7 @@ public class ResourceServerTokenServicesConfigurationTests {
ClientHttpRequestExecution execution) throws IOException {
return execution.execute(request, body);
}
});
}
......
......@@ -41,8 +41,8 @@ public class DefaultCommandFactory implements CommandFactory {
private static final List<Command> DEFAULT_COMMANDS = Arrays.<Command>asList(
new VersionCommand(), new RunCommand(), new TestCommand(), new GrabCommand(),
new JarCommand(), new WarCommand(), new InstallCommand(), new UninstallCommand(),
new InitCommand());
new JarCommand(), new WarCommand(), new InstallCommand(),
new UninstallCommand(), new InitCommand());
@Override
public Collection<Command> getCommands() {
......
......@@ -44,7 +44,8 @@ public class SpringApplicationRunnerTests {
given(configuration.getLogLevel()).willReturn(Level.INFO);
this.thrown.expect(RuntimeException.class);
this.thrown.expectMessage(equalTo("No classes found in '[foo, bar]'"));
new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }).compileAndRun();
new SpringApplicationRunner(configuration, new String[] { "foo", "bar" })
.compileAndRun();
}
}
......@@ -35,7 +35,6 @@ import org.springframework.util.ObjectUtils;
*
* @author Andy Wilkinson
* @author Rob Winch
*
* @see RedisTemplate#setHashKeySerializer(RedisSerializer)
* @see RedisTemplate#setHashValueSerializer(RedisSerializer)
* @see RedisTemplate#setKeySerializer(RedisSerializer)
......@@ -69,6 +68,8 @@ class RestartCompatibleRedisSerializerConfigurer implements BeanClassLoaderAware
static class RestartCompatibleRedisSerializer implements RedisSerializer<Object> {
private static final byte[] NO_BYTES = new byte[0];
private final Converter<Object, byte[]> serializer = new SerializingConverter();
private final Converter<byte[], Object> deserializer;
......@@ -80,12 +81,9 @@ class RestartCompatibleRedisSerializerConfigurer implements BeanClassLoaderAware
@Override
public Object deserialize(byte[] bytes) {
if (ObjectUtils.isEmpty(bytes)) {
return null;
}
try {
return this.deserializer.convert(bytes);
return (ObjectUtils.isEmpty(bytes) ? null
: this.deserializer.convert(bytes));
}
catch (Exception ex) {
throw new SerializationException("Cannot deserialize", ex);
......@@ -94,11 +92,8 @@ class RestartCompatibleRedisSerializerConfigurer implements BeanClassLoaderAware
@Override
public byte[] serialize(Object object) {
if (object == null) {
return new byte[0];
}
try {
return this.serializer.convert(object);
return (object == null ? NO_BYTES : this.serializer.convert(object));
}
catch (Exception ex) {
throw new SerializationException("Cannot serialize", ex);
......
......@@ -41,10 +41,9 @@ public class DefaultSourceFolderUrlFilter implements SourceFolderUrlFilter {
private static final Pattern VERSION_PATTERN = Pattern
.compile("^-\\d+(?:\\.\\d+)*(?:[.-].+)?$");
private static final Set<String> SKIPPED_PROJECTS = new HashSet<String>(
Arrays.asList("spring-boot", "spring-boot-devtools",
"spring-boot-autoconfigure", "spring-boot-actuator",
"spring-boot-starter"));
private static final Set<String> SKIPPED_PROJECTS = new HashSet<String>(Arrays.asList(
"spring-boot", "spring-boot-devtools", "spring-boot-autoconfigure",
"spring-boot-actuator", "spring-boot-starter"));
@Override
public boolean isMatch(String sourceFolder, URL url) {
......
......@@ -4026,6 +4026,7 @@ same semantic as the regular `@Order` annotation but provides a dedicated order
auto-configuration classes.
[[boot-features-condition-annotations]]
=== Condition annotations
You almost always want to include one or more `@Conditional` annotations on your
......
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2015 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.
......
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2015 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.
......
......@@ -95,8 +95,9 @@ public class ApplicationHome {
}
/**
* Returns the underlying source used to find the home directory. This is usually the jar
* file or a directory. Can return {@code null} if the source cannot be determined.
* Returns the underlying source used to find the home directory. This is usually the
* jar file or a directory. Can return {@code null} if the source cannot be
* determined.
* @return the underlying source or {@code null}
*/
public File getSource() {
......
......@@ -520,9 +520,7 @@ public class SpringApplication {
* @see #setBannerMode
*/
protected void printBanner(Environment environment) {
Banner selectedBanner = selectBanner(environment);
if (this.bannerMode == Banner.Mode.LOG) {
try {
this.log.info(createStringFromBanner(selectedBanner, environment));
......@@ -542,7 +540,6 @@ public class SpringApplication {
ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader
: new DefaultResourceLoader(getClassLoader());
Resource resource = resourceLoader.getResource(location);
if (resource.exists()) {
return new ResourceBanner(resource);
}
......
......@@ -144,8 +144,8 @@ public interface ConfigurableEmbeddedServletContainer {
void setMimeMappings(MimeMappings mimeMappings);
/**
* Sets the document root directory which will be used by the web context to serve static
* files.
* Sets the document root directory which will be used by the web context to serve
* static files.
* @param documentRoot the document root or {@code null} if not required
*/
void setDocumentRoot(File documentRoot);
......
......@@ -39,10 +39,9 @@ import org.springframework.web.context.support.StandardServletEnvironment;
/**
* An {@link EnvironmentPostProcessor} that parses JSON from
* {@code spring.application.json} or equivalently
* {@code SPRING_APPLICATION_JSON} and adds it as a map property
* source to the {@link Environment}. The new properties are added with higher priority
* than the system properties.
* {@code spring.application.json} or equivalently {@code SPRING_APPLICATION_JSON} and
* adds it as a map property source to the {@link Environment}. The new properties are
* added with higher priority than the system properties.
*
* @author Dave Syer
* @author Phillip Webb
......
......@@ -106,9 +106,9 @@ public class AtomikosProperties {
/**
* Specifies if subtransactions should be joined when possible. Defaults to true. When
* false, no attempt to call {@code XAResource.start(TM_JOIN)} will be made for
* different but related subtransactions. This setting has no effect on resource access
* within one and the same transaction. If you don't use subtransactions then this
* setting can be ignored.
* different but related subtransactions. This setting has no effect on resource
* access within one and the same transaction. If you don't use subtransactions then
* this setting can be ignored.
* @param serialJtaTransactions if serial JTA transaction are supported
*/
public void setSerialJtaTransactions(boolean serialJtaTransactions) {
......
......@@ -28,7 +28,8 @@ import org.springframework.mock.web.MockServletContext;
/**
* {@link MockServletContext} implementation for Spring Boot. Respects well know Spring
* Boot resource locations and uses an empty directory for "/" if no locations can be found.
* Boot resource locations and uses an empty directory for "/" if no locations can be
* found.
*
* @author Phillip Webb
*/
......
......@@ -82,8 +82,8 @@ public class SpringApplicationIntegrationTestTests {
@Test
public void validateWebApplicationContextIsSet() {
assertSame(this.context, WebApplicationContextUtils
.getWebApplicationContext(this.servletContext));
assertSame(this.context,
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
}
@Configuration
......
......@@ -71,11 +71,10 @@ public class SpringApplicationMockMvcTests {
@Test
public void validateWebApplicationContextIsSet() {
assertSame(this.context, WebApplicationContextUtils
.getWebApplicationContext(this.servletContext));
assertSame(this.context,
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
}
@Configuration
@EnableWebMvc
@RestController
......
......@@ -49,7 +49,7 @@ import static org.junit.Assert.assertSame;
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Config.class)
@WebIntegrationTest({"server.port=0", "value=123"})
@WebIntegrationTest({ "server.port=0", "value=123" })
public class SpringApplicationWebIntegrationTestTests {
@Value("${local.server.port}")
......@@ -80,8 +80,8 @@ public class SpringApplicationWebIntegrationTestTests {
@Test
public void validateWebApplicationContextIsSet() {
assertSame(this.context, WebApplicationContextUtils
.getWebApplicationContext(this.servletContext));
assertSame(this.context,
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
}
@Configuration
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment