Commit 8f4bf233 authored by Phillip Webb's avatar Phillip Webb

Update configuration properties to use Duration

Update appropriate configuration properties to use the `Duration`
type, rather than an ad-hoc mix of milliseconds or seconds.

Configuration properties can now be defined in a consistent and readable
way. For example `server.session.timeout=5m`.

Properties that were previously declared using seconds are annotated
with `@DurationUnit` to ensure a smooth upgrade experience. For example
`server.session.timeout=20` continues to mean 20 seconds.

Fixes gh-11080
parent cbaf0fa6
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.actuate.autoconfigure.elasticsearch; package org.springframework.boot.actuate.autoconfigure.elasticsearch;
import java.time.Duration;
import java.util.Map; import java.util.Map;
import io.searchbox.client.JestClient; import io.searchbox.client.JestClient;
...@@ -77,8 +78,10 @@ public class ElasticsearchHealthIndicatorAutoConfiguration { ...@@ -77,8 +78,10 @@ public class ElasticsearchHealthIndicatorAutoConfiguration {
@Override @Override
protected ElasticsearchHealthIndicator createHealthIndicator(Client client) { protected ElasticsearchHealthIndicator createHealthIndicator(Client client) {
Duration responseTimeout = this.properties.getResponseTimeout();
return new ElasticsearchHealthIndicator(client, return new ElasticsearchHealthIndicator(client,
this.properties.getResponseTimeout(), this.properties.getIndices()); responseTimeout == null ? 100 : responseTimeout.toMillis(),
this.properties.getIndices());
} }
} }
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.actuate.autoconfigure.elasticsearch; package org.springframework.boot.actuate.autoconfigure.elasticsearch;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -38,9 +39,9 @@ public class ElasticsearchHealthIndicatorProperties { ...@@ -38,9 +39,9 @@ public class ElasticsearchHealthIndicatorProperties {
private List<String> indices = new ArrayList<>(); private List<String> indices = new ArrayList<>();
/** /**
* Time, in milliseconds, to wait for a response from the cluster. * Time to wait for a response from the cluster.
*/ */
private long responseTimeout = 100L; private Duration responseTimeout = Duration.ofMillis(100);
public List<String> getIndices() { public List<String> getIndices() {
return this.indices; return this.indices;
...@@ -50,11 +51,11 @@ public class ElasticsearchHealthIndicatorProperties { ...@@ -50,11 +51,11 @@ public class ElasticsearchHealthIndicatorProperties {
this.indices = indices; this.indices = indices;
} }
public long getResponseTimeout() { public Duration getResponseTimeout() {
return this.responseTimeout; return this.responseTimeout;
} }
public void setResponseTimeout(long responseTimeout) { public void setResponseTimeout(Duration responseTimeout) {
this.responseTimeout = responseTimeout; this.responseTimeout = responseTimeout;
} }
......
...@@ -16,9 +16,14 @@ ...@@ -16,9 +16,14 @@
package org.springframework.boot.actuate.autoconfigure.endpoint; package org.springframework.boot.actuate.autoconfigure.endpoint;
import java.time.Duration;
import java.util.function.Function; import java.util.function.Function;
import org.springframework.boot.actuate.endpoint.cache.CachingOperationInvokerAdvisor; import org.springframework.boot.actuate.endpoint.cache.CachingOperationInvokerAdvisor;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertyResolver; import org.springframework.core.env.PropertyResolver;
/** /**
...@@ -30,20 +35,24 @@ import org.springframework.core.env.PropertyResolver; ...@@ -30,20 +35,24 @@ import org.springframework.core.env.PropertyResolver;
*/ */
class EndpointIdTimeToLivePropertyFunction implements Function<String, Long> { class EndpointIdTimeToLivePropertyFunction implements Function<String, Long> {
private final PropertyResolver propertyResolver; private static final Bindable<Duration> DURATION = Bindable.of(Duration.class);
private final Environment environment;
/** /**
* Create a new instance with the {@link PropertyResolver} to use. * Create a new instance with the {@link PropertyResolver} to use.
* @param propertyResolver the environment * @param environment the environment
*/ */
EndpointIdTimeToLivePropertyFunction(PropertyResolver propertyResolver) { EndpointIdTimeToLivePropertyFunction(Environment environment) {
this.propertyResolver = propertyResolver; this.environment = environment;
} }
@Override @Override
public Long apply(String endpointId) { public Long apply(String endpointId) {
String key = String.format("management.endpoint.%s.cache.time-to-live", String name = String.format("management.endpoint.%s.cache.time-to-live",
endpointId); endpointId);
return this.propertyResolver.getProperty(key, Long.class); BindResult<Duration> duration = Binder.get(this.environment).bind(name, DURATION);
return duration.map(Duration::toMillis).orElse(null);
} }
} }
...@@ -16,10 +16,13 @@ ...@@ -16,10 +16,13 @@
package org.springframework.boot.actuate.autoconfigure.endpoint.web.servlet; package org.springframework.boot.actuate.autoconfigure.endpoint.web.servlet;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.convert.DurationUnit;
/** /**
* Configuration properties for MVC endpoints' CORS support. * Configuration properties for MVC endpoints' CORS support.
...@@ -58,10 +61,11 @@ public class CorsEndpointProperties { ...@@ -58,10 +61,11 @@ public class CorsEndpointProperties {
private Boolean allowCredentials; private Boolean allowCredentials;
/** /**
* How long, in seconds, the response from a pre-flight request can be cached by * How long the response from a pre-flight request can be cached by clients. If a
* clients. * duration suffix is not specified, seconds will be used.
*/ */
private Long maxAge = 1800L; @DurationUnit(ChronoUnit.SECONDS)
private Duration maxAge = Duration.ofSeconds(1800);
public List<String> getAllowedOrigins() { public List<String> getAllowedOrigins() {
return this.allowedOrigins; return this.allowedOrigins;
...@@ -103,11 +107,11 @@ public class CorsEndpointProperties { ...@@ -103,11 +107,11 @@ public class CorsEndpointProperties {
this.allowCredentials = allowCredentials; this.allowCredentials = allowCredentials;
} }
public Long getMaxAge() { public Duration getMaxAge() {
return this.maxAge; return this.maxAge;
} }
public void setMaxAge(Long maxAge) { public void setMaxAge(Duration maxAge) {
this.maxAge = maxAge; this.maxAge = maxAge;
} }
......
...@@ -78,7 +78,7 @@ public class WebMvcEndpointManagementContextConfiguration { ...@@ -78,7 +78,7 @@ public class WebMvcEndpointManagementContextConfiguration {
configuration.setExposedHeaders(properties.getExposedHeaders()); configuration.setExposedHeaders(properties.getExposedHeaders());
} }
if (properties.getMaxAge() != null) { if (properties.getMaxAge() != null) {
configuration.setMaxAge(properties.getMaxAge()); configuration.setMaxAge(properties.getMaxAge().getSeconds());
} }
if (properties.getAllowCredentials() != null) { if (properties.getAllowCredentials() != null) {
configuration.setAllowCredentials(properties.getAllowCredentials()); configuration.setAllowCredentials(properties.getAllowCredentials());
......
...@@ -100,7 +100,7 @@ public abstract class AbstractRabbitListenerContainerFactoryConfigurer<T extends ...@@ -100,7 +100,7 @@ public abstract class AbstractRabbitListenerContainerFactoryConfigurer<T extends
factory.setDefaultRequeueRejected(configuration.getDefaultRequeueRejected()); factory.setDefaultRequeueRejected(configuration.getDefaultRequeueRejected());
} }
if (configuration.getIdleEventInterval() != null) { if (configuration.getIdleEventInterval() != null) {
factory.setIdleEventInterval(configuration.getIdleEventInterval()); factory.setIdleEventInterval(configuration.getIdleEventInterval().toMillis());
} }
ListenerRetry retryConfig = configuration.getRetry(); ListenerRetry retryConfig = configuration.getRetry();
if (retryConfig.isEnabled()) { if (retryConfig.isEnabled()) {
......
...@@ -105,7 +105,8 @@ public class RabbitAutoConfiguration { ...@@ -105,7 +105,8 @@ public class RabbitAutoConfiguration {
factory.setVirtualHost(config.determineVirtualHost()); factory.setVirtualHost(config.determineVirtualHost());
} }
if (config.getRequestedHeartbeat() != null) { if (config.getRequestedHeartbeat() != null) {
factory.setRequestedHeartbeat(config.getRequestedHeartbeat()); factory.setRequestedHeartbeat(
(int) config.getRequestedHeartbeat().getSeconds());
} }
RabbitProperties.Ssl ssl = config.getSsl(); RabbitProperties.Ssl ssl = config.getSsl();
if (ssl.isEnabled()) { if (ssl.isEnabled()) {
...@@ -121,7 +122,8 @@ public class RabbitAutoConfiguration { ...@@ -121,7 +122,8 @@ public class RabbitAutoConfiguration {
factory.setTrustStorePassphrase(ssl.getTrustStorePassword()); factory.setTrustStorePassphrase(ssl.getTrustStorePassword());
} }
if (config.getConnectionTimeout() != null) { if (config.getConnectionTimeout() != null) {
factory.setConnectionTimeout(config.getConnectionTimeout()); factory.setConnectionTimeout(
(int) config.getConnectionTimeout().toMillis());
} }
factory.afterPropertiesSet(); factory.afterPropertiesSet();
CachingConnectionFactory connectionFactory = new CachingConnectionFactory( CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
......
...@@ -16,12 +16,15 @@ ...@@ -16,12 +16,15 @@
package org.springframework.boot.autoconfigure.amqp; package org.springframework.boot.autoconfigure.amqp;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.springframework.amqp.core.AcknowledgeMode; import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory.CacheMode; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory.CacheMode;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.convert.DurationUnit;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
...@@ -74,9 +77,11 @@ public class RabbitProperties { ...@@ -74,9 +77,11 @@ public class RabbitProperties {
private String addresses; private String addresses;
/** /**
* Requested heartbeat timeout, in seconds; zero for none. * Requested heartbeat timeout; zero for none. If a duration suffix is not specified,
* seconds will be used.
*/ */
private Integer requestedHeartbeat; @DurationUnit(ChronoUnit.SECONDS)
private Duration requestedHeartbeat;
/** /**
* Enable publisher confirms. * Enable publisher confirms.
...@@ -89,9 +94,9 @@ public class RabbitProperties { ...@@ -89,9 +94,9 @@ public class RabbitProperties {
private boolean publisherReturns; private boolean publisherReturns;
/** /**
* Connection timeout, in milliseconds; zero for infinite. * Connection timeout; zero for infinite.
*/ */
private Integer connectionTimeout; private Duration connectionTimeout;
/** /**
* Cache configuration. * Cache configuration.
...@@ -258,11 +263,11 @@ public class RabbitProperties { ...@@ -258,11 +263,11 @@ public class RabbitProperties {
this.virtualHost = ("".equals(virtualHost) ? "/" : virtualHost); this.virtualHost = ("".equals(virtualHost) ? "/" : virtualHost);
} }
public Integer getRequestedHeartbeat() { public Duration getRequestedHeartbeat() {
return this.requestedHeartbeat; return this.requestedHeartbeat;
} }
public void setRequestedHeartbeat(Integer requestedHeartbeat) { public void setRequestedHeartbeat(Duration requestedHeartbeat) {
this.requestedHeartbeat = requestedHeartbeat; this.requestedHeartbeat = requestedHeartbeat;
} }
...@@ -282,11 +287,11 @@ public class RabbitProperties { ...@@ -282,11 +287,11 @@ public class RabbitProperties {
this.publisherReturns = publisherReturns; this.publisherReturns = publisherReturns;
} }
public Integer getConnectionTimeout() { public Duration getConnectionTimeout() {
return this.connectionTimeout; return this.connectionTimeout;
} }
public void setConnectionTimeout(Integer connectionTimeout) { public void setConnectionTimeout(Duration connectionTimeout) {
this.connectionTimeout = connectionTimeout; this.connectionTimeout = connectionTimeout;
} }
...@@ -557,9 +562,9 @@ public class RabbitProperties { ...@@ -557,9 +562,9 @@ public class RabbitProperties {
private Boolean defaultRequeueRejected; private Boolean defaultRequeueRejected;
/** /**
* How often idle container events should be published in milliseconds. * How often idle container events should be published.
*/ */
private Long idleEventInterval; private Duration idleEventInterval;
/** /**
* Optional properties for a retry interceptor. * Optional properties for a retry interceptor.
...@@ -598,11 +603,11 @@ public class RabbitProperties { ...@@ -598,11 +603,11 @@ public class RabbitProperties {
this.defaultRequeueRejected = defaultRequeueRejected; this.defaultRequeueRejected = defaultRequeueRejected;
} }
public Long getIdleEventInterval() { public Duration getIdleEventInterval() {
return this.idleEventInterval; return this.idleEventInterval;
} }
public void setIdleEventInterval(Long idleEventInterval) { public void setIdleEventInterval(Duration idleEventInterval) {
this.idleEventInterval = idleEventInterval; this.idleEventInterval = idleEventInterval;
} }
......
...@@ -16,9 +16,9 @@ ...@@ -16,9 +16,9 @@
package org.springframework.boot.autoconfigure.cache; package org.springframework.boot.autoconfigure.cache;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
...@@ -141,24 +141,16 @@ public class CacheProperties { ...@@ -141,24 +141,16 @@ public class CacheProperties {
public static class Couchbase { public static class Couchbase {
/** /**
* Entry expiration in milliseconds. By default the entries never expire. Note * Entry expiration. By default the entries never expire. Note that this value is
* that this value is ultimately converted to seconds. * ultimately converted to seconds.
*/ */
private int expiration; private Duration expiration;
public int getExpiration() { public Duration getExpiration() {
return this.expiration; return this.expiration;
} }
/** public void setExpiration(Duration expiration) {
* Return the expiration in seconds.
* @return the expiration in seconds
*/
public int getExpirationSeconds() {
return (int) TimeUnit.MILLISECONDS.toSeconds(this.expiration);
}
public void setExpiration(int expiration) {
this.expiration = expiration; this.expiration = expiration;
} }
...@@ -246,9 +238,9 @@ public class CacheProperties { ...@@ -246,9 +238,9 @@ public class CacheProperties {
public static class Redis { public static class Redis {
/** /**
* Entry expiration in milliseconds. By default the entries never expire. * Entry expiration. By default the entries never expire.
*/ */
private long timeToLive = 0; private Duration timeToLive;
/** /**
* Allow caching null values. * Allow caching null values.
...@@ -265,11 +257,11 @@ public class CacheProperties { ...@@ -265,11 +257,11 @@ public class CacheProperties {
*/ */
private boolean useKeyPrefix = true; private boolean useKeyPrefix = true;
public long getTimeToLive() { public Duration getTimeToLive() {
return this.timeToLive; return this.timeToLive;
} }
public void setTimeToLive(long timeToLive) { public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive; this.timeToLive = timeToLive;
} }
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.autoconfigure.cache; package org.springframework.boot.autoconfigure.cache;
import java.time.Duration;
import java.util.List; import java.util.List;
import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Bucket;
...@@ -59,11 +60,13 @@ public class CouchbaseCacheConfiguration { ...@@ -59,11 +60,13 @@ public class CouchbaseCacheConfiguration {
@Bean @Bean
public CouchbaseCacheManager cacheManager() { public CouchbaseCacheManager cacheManager() {
List<String> cacheNames = this.cacheProperties.getCacheNames(); List<String> cacheNames = this.cacheProperties.getCacheNames();
CouchbaseCacheManager cacheManager = new CouchbaseCacheManager( CacheBuilder builder = CacheBuilder.newInstance(this.bucket);
CacheBuilder.newInstance(this.bucket) Duration expiration = this.cacheProperties.getCouchbase().getExpiration();
.withExpiration(this.cacheProperties.getCouchbase() if (expiration != null) {
.getExpirationSeconds()), builder = builder.withExpiration((int) expiration.getSeconds());
cacheNames.toArray(new String[cacheNames.size()])); }
String[] names = cacheNames.toArray(new String[cacheNames.size()]);
CouchbaseCacheManager cacheManager = new CouchbaseCacheManager(builder, names);
return this.customizers.customize(cacheManager); return this.customizers.customize(cacheManager);
} }
......
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
package org.springframework.boot.autoconfigure.cache; package org.springframework.boot.autoconfigure.cache;
import java.time.Duration;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
...@@ -73,7 +72,9 @@ class RedisCacheConfiguration { ...@@ -73,7 +72,9 @@ class RedisCacheConfiguration {
Redis redisProperties = this.cacheProperties.getRedis(); Redis redisProperties = this.cacheProperties.getRedis();
org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
.defaultCacheConfig(); .defaultCacheConfig();
config = config.entryTtl(Duration.ofMillis(redisProperties.getTimeToLive())); if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) { if (redisProperties.getKeyPrefix() != null) {
config = config.prefixKeysWith(redisProperties.getKeyPrefix()); config = config.prefixKeysWith(redisProperties.getKeyPrefix());
} }
......
...@@ -125,17 +125,30 @@ public class CassandraAutoConfiguration { ...@@ -125,17 +125,30 @@ public class CassandraAutoConfiguration {
private SocketOptions getSocketOptions() { private SocketOptions getSocketOptions() {
SocketOptions options = new SocketOptions(); SocketOptions options = new SocketOptions();
options.setConnectTimeoutMillis(this.properties.getConnectTimeoutMillis()); if (this.properties.getConnectTimeout() != null) {
options.setReadTimeoutMillis(this.properties.getReadTimeoutMillis()); options.setConnectTimeoutMillis(
(int) this.properties.getConnectTimeout().toMillis());
}
if (this.properties.getReadTimeout() != null) {
options.setReadTimeoutMillis(
(int) this.properties.getReadTimeout().toMillis());
}
return options; return options;
} }
private PoolingOptions getPoolingOptions() { private PoolingOptions getPoolingOptions() {
CassandraProperties.Pool pool = this.properties.getPool(); CassandraProperties.Pool pool = this.properties.getPool();
PoolingOptions options = new PoolingOptions(); PoolingOptions options = new PoolingOptions();
options.setIdleTimeoutSeconds(pool.getIdleTimeout()); if (pool.getIdleTimeout() != null) {
options.setPoolTimeoutMillis(pool.getPoolTimeout()); options.setIdleTimeoutSeconds((int) pool.getIdleTimeout().getSeconds());
options.setHeartbeatIntervalSeconds(pool.getHeartbeatInterval()); }
if (pool.getPoolTimeout() != null) {
options.setPoolTimeoutMillis((int) pool.getPoolTimeout().toMillis());
}
if (pool.getHeartbeatInterval() != null) {
options.setHeartbeatIntervalSeconds(
(int) pool.getHeartbeatInterval().getSeconds());
}
options.setMaxQueueSize(pool.getMaxQueueSize()); options.setMaxQueueSize(pool.getMaxQueueSize());
return options; return options;
} }
......
...@@ -16,16 +16,19 @@ ...@@ -16,16 +16,19 @@
package org.springframework.boot.autoconfigure.cassandra; package org.springframework.boot.autoconfigure.cassandra;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import com.datastax.driver.core.ConsistencyLevel; import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.ProtocolOptions; import com.datastax.driver.core.ProtocolOptions;
import com.datastax.driver.core.ProtocolOptions.Compression; import com.datastax.driver.core.ProtocolOptions.Compression;
import com.datastax.driver.core.QueryOptions; import com.datastax.driver.core.QueryOptions;
import com.datastax.driver.core.SocketOptions;
import com.datastax.driver.core.policies.LoadBalancingPolicy; import com.datastax.driver.core.policies.LoadBalancingPolicy;
import com.datastax.driver.core.policies.ReconnectionPolicy; import com.datastax.driver.core.policies.ReconnectionPolicy;
import com.datastax.driver.core.policies.RetryPolicy; import com.datastax.driver.core.policies.RetryPolicy;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.convert.DurationUnit;
/** /**
* Configuration properties for Cassandra. * Configuration properties for Cassandra.
...@@ -107,12 +110,12 @@ public class CassandraProperties { ...@@ -107,12 +110,12 @@ public class CassandraProperties {
/** /**
* Socket option: connection time out. * Socket option: connection time out.
*/ */
private int connectTimeoutMillis = SocketOptions.DEFAULT_CONNECT_TIMEOUT_MILLIS; private Duration connectTimeout;
/** /**
* Socket option: read time out. * Socket option: read time out.
*/ */
private int readTimeoutMillis = SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS; private Duration readTimeout;
/** /**
* Schema action to take at startup. * Schema action to take at startup.
...@@ -235,20 +238,20 @@ public class CassandraProperties { ...@@ -235,20 +238,20 @@ public class CassandraProperties {
this.retryPolicy = retryPolicy; this.retryPolicy = retryPolicy;
} }
public int getConnectTimeoutMillis() { public Duration getConnectTimeout() {
return this.connectTimeoutMillis; return this.connectTimeout;
} }
public void setConnectTimeoutMillis(int connectTimeoutMillis) { public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeoutMillis = connectTimeoutMillis; this.connectTimeout = connectTimeout;
} }
public int getReadTimeoutMillis() { public Duration getReadTimeout() {
return this.readTimeoutMillis; return this.readTimeout;
} }
public void setReadTimeoutMillis(int readTimeoutMillis) { public void setReadTimeout(Duration readTimeout) {
this.readTimeoutMillis = readTimeoutMillis; this.readTimeout = readTimeout;
} }
public boolean isSsl() { public boolean isSsl() {
...@@ -277,48 +280,51 @@ public class CassandraProperties { ...@@ -277,48 +280,51 @@ public class CassandraProperties {
public static class Pool { public static class Pool {
/** /**
* Idle timeout (in seconds) before an idle connection is removed. * Idle timeout before an idle connection is removed. If a duration suffix is not
* specified, seconds will be used.
*/ */
private int idleTimeout = 120; @DurationUnit(ChronoUnit.SECONDS)
private Duration idleTimeout = Duration.ofSeconds(120);
/** /**
* Pool timeout (in milliseconds) when trying to acquire a connection from a * Pool timeout when trying to acquire a connection from a host's pool.
* host's pool.
*/ */
private int poolTimeout = 5000; private Duration poolTimeout = Duration.ofMillis(5000);
/** /**
* Heartbeat interval (in seconds) after which a message is sent on an idle * Heartbeat interval after which a message is sent on an idle connection to make
* connection to make sure it's still alive. * sure it's still alive. If a duration suffix is not specified, seconds will be
* used.
*/ */
private int heartbeatInterval = 30; @DurationUnit(ChronoUnit.SECONDS)
private Duration heartbeatInterval = Duration.ofSeconds(30);
/** /**
* Maximum number of requests that get enqueued if no connection is available. * Maximum number of requests that get enqueued if no connection is available.
*/ */
private int maxQueueSize = 256; private int maxQueueSize = 256;
public int getIdleTimeout() { public Duration getIdleTimeout() {
return this.idleTimeout; return this.idleTimeout;
} }
public void setIdleTimeout(int idleTimeout) { public void setIdleTimeout(Duration idleTimeout) {
this.idleTimeout = idleTimeout; this.idleTimeout = idleTimeout;
} }
public int getPoolTimeout() { public Duration getPoolTimeout() {
return this.poolTimeout; return this.poolTimeout;
} }
public void setPoolTimeout(int poolTimeout) { public void setPoolTimeout(Duration poolTimeout) {
this.poolTimeout = poolTimeout; this.poolTimeout = poolTimeout;
} }
public int getHeartbeatInterval() { public Duration getHeartbeatInterval() {
return this.heartbeatInterval; return this.heartbeatInterval;
} }
public void setHeartbeatInterval(int heartbeatInterval) { public void setHeartbeatInterval(Duration heartbeatInterval) {
this.heartbeatInterval = heartbeatInterval; this.heartbeatInterval = heartbeatInterval;
} }
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
package org.springframework.boot.autoconfigure.context; package org.springframework.boot.autoconfigure.context;
import java.time.Duration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionMessage; import org.springframework.boot.autoconfigure.condition.ConditionMessage;
...@@ -73,7 +75,9 @@ public class MessageSourceAutoConfiguration { ...@@ -73,7 +75,9 @@ public class MessageSourceAutoConfiguration {
messageSource.setDefaultEncoding(properties.getEncoding().name()); messageSource.setDefaultEncoding(properties.getEncoding().name());
} }
messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale()); messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
messageSource.setCacheSeconds(properties.getCacheSeconds()); Duration cacheDuration = properties.getCacheDuration();
messageSource.setCacheSeconds(
cacheDuration == null ? -1 : (int) cacheDuration.getSeconds());
messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat()); messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage()); messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
return messageSource; return messageSource;
......
...@@ -18,6 +18,7 @@ package org.springframework.boot.autoconfigure.context; ...@@ -18,6 +18,7 @@ package org.springframework.boot.autoconfigure.context;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Duration;
/** /**
* Configuration properties for Message Source. * Configuration properties for Message Source.
...@@ -41,10 +42,10 @@ public class MessageSourceProperties { ...@@ -41,10 +42,10 @@ public class MessageSourceProperties {
private Charset encoding = StandardCharsets.UTF_8; private Charset encoding = StandardCharsets.UTF_8;
/** /**
* Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles * Loaded resource bundle files cache expiration, in seconds. When not set, bundles
* are cached forever. * are cached forever.
*/ */
private int cacheSeconds = -1; private Duration cacheDuration;
/** /**
* Set whether to fall back to the system Locale if no files for a specific Locale * Set whether to fall back to the system Locale if no files for a specific Locale
...@@ -81,12 +82,12 @@ public class MessageSourceProperties { ...@@ -81,12 +82,12 @@ public class MessageSourceProperties {
this.encoding = encoding; this.encoding = encoding;
} }
public int getCacheSeconds() { public Duration getCacheDuration() {
return this.cacheSeconds; return this.cacheDuration;
} }
public void setCacheSeconds(int cacheSeconds) { public void setCacheDuration(Duration cacheDuration) {
this.cacheSeconds = cacheSeconds; this.cacheDuration = cacheDuration;
} }
public boolean isFallbackToSystemLocale() { public boolean isFallbackToSystemLocale() {
......
...@@ -98,13 +98,26 @@ public class CouchbaseAutoConfiguration { ...@@ -98,13 +98,26 @@ public class CouchbaseAutoConfiguration {
CouchbaseProperties.Endpoints endpoints = properties.getEnv().getEndpoints(); CouchbaseProperties.Endpoints endpoints = properties.getEnv().getEndpoints();
CouchbaseProperties.Timeouts timeouts = properties.getEnv().getTimeouts(); CouchbaseProperties.Timeouts timeouts = properties.getEnv().getTimeouts();
DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment
.builder().connectTimeout(timeouts.getConnect()) .builder();
.kvEndpoints(endpoints.getKeyValue()) if (timeouts.getConnect() != null) {
.kvTimeout(timeouts.getKeyValue()) builder = builder.connectTimeout(timeouts.getConnect().toMillis());
.queryEndpoints(endpoints.getQuery()) }
.queryTimeout(timeouts.getQuery()).viewEndpoints(endpoints.getView()) builder = builder.kvEndpoints(endpoints.getKeyValue());
.socketConnectTimeout(timeouts.getSocketConnect()) if (timeouts.getKeyValue() != null) {
.viewTimeout(timeouts.getView()); builder = builder.kvTimeout(timeouts.getKeyValue().toMillis());
}
builder = builder.queryEndpoints(endpoints.getQuery());
if (timeouts.getQuery() != null) {
builder = builder.queryTimeout(timeouts.getQuery().toMillis())
.viewEndpoints(endpoints.getView());
}
if (timeouts.getSocketConnect() != null) {
builder = builder.socketConnectTimeout(
(int) timeouts.getSocketConnect().toMillis());
}
if (timeouts.getView() != null) {
builder = builder.viewTimeout(timeouts.getView().toMillis());
}
CouchbaseProperties.Ssl ssl = properties.getEnv().getSsl(); CouchbaseProperties.Ssl ssl = properties.getEnv().getSsl();
if (ssl.getEnabled()) { if (ssl.getEnabled()) {
builder.sslEnabled(true); builder.sslEnabled(true);
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.autoconfigure.couchbase; package org.springframework.boot.autoconfigure.couchbase;
import java.time.Duration;
import java.util.List; import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
...@@ -199,67 +200,67 @@ public class CouchbaseProperties { ...@@ -199,67 +200,67 @@ public class CouchbaseProperties {
public static class Timeouts { public static class Timeouts {
/** /**
* Bucket connections timeout in milliseconds. * Bucket connections timeout.
*/ */
private long connect = 5000; private Duration connect = Duration.ofMillis(5000);
/** /**
* Blocking operations performed on a specific key timeout in milliseconds. * Blocking operations performed on a specific key timeout.
*/ */
private long keyValue = 2500; private Duration keyValue = Duration.ofMillis(2500);
/** /**
* N1QL query operations timeout in milliseconds. * N1QL query operations timeout.
*/ */
private long query = 7500; private Duration query = Duration.ofMillis(7500);
/** /**
* Socket connect connections timeout in milliseconds. * Socket connect connections timeout.
*/ */
private int socketConnect = 1000; private Duration socketConnect = Duration.ofMillis(1000);
/** /**
* Regular and geospatial view operations timeout in milliseconds. * Regular and geospatial view operations timeout.
*/ */
private long view = 7500; private Duration view = Duration.ofMillis(7500);
public long getConnect() { public Duration getConnect() {
return this.connect; return this.connect;
} }
public void setConnect(long connect) { public void setConnect(Duration connect) {
this.connect = connect; this.connect = connect;
} }
public long getKeyValue() { public Duration getKeyValue() {
return this.keyValue; return this.keyValue;
} }
public void setKeyValue(long keyValue) { public void setKeyValue(Duration keyValue) {
this.keyValue = keyValue; this.keyValue = keyValue;
} }
public long getQuery() { public Duration getQuery() {
return this.query; return this.query;
} }
public void setQuery(long query) { public void setQuery(Duration query) {
this.query = query; this.query = query;
} }
public int getSocketConnect() { public Duration getSocketConnect() {
return this.socketConnect; return this.socketConnect;
} }
public void setSocketConnect(int socketConnect) { public void setSocketConnect(Duration socketConnect) {
this.socketConnect = socketConnect; this.socketConnect = socketConnect;
} }
public long getView() { public Duration getView() {
return this.view; return this.view;
} }
public void setView(long view) { public void setView(Duration view) {
this.view = view; this.view = view;
} }
......
...@@ -100,8 +100,8 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { ...@@ -100,8 +100,8 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration {
if (this.properties.isSsl()) { if (this.properties.isSsl()) {
builder.useSsl(); builder.useSsl();
} }
if (this.properties.getTimeout() != 0) { if (this.properties.getTimeout() != null) {
Duration timeout = Duration.ofMillis(this.properties.getTimeout()); Duration timeout = this.properties.getTimeout();
builder.readTimeout(timeout).connectTimeout(timeout); builder.readTimeout(timeout).connectTimeout(timeout);
} }
return builder; return builder;
...@@ -117,7 +117,9 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { ...@@ -117,7 +117,9 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration {
config.setMaxTotal(pool.getMaxActive()); config.setMaxTotal(pool.getMaxActive());
config.setMaxIdle(pool.getMaxIdle()); config.setMaxIdle(pool.getMaxIdle());
config.setMinIdle(pool.getMinIdle()); config.setMinIdle(pool.getMinIdle());
config.setMaxWaitMillis(pool.getMaxWait()); if (pool.getMaxWait() != null) {
config.setMaxWaitMillis(pool.getMaxWait().toMillis());
}
return config; return config;
} }
......
...@@ -17,7 +17,6 @@ ...@@ -17,7 +17,6 @@
package org.springframework.boot.autoconfigure.data.redis; package org.springframework.boot.autoconfigure.data.redis;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.time.Duration;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
...@@ -116,14 +115,15 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { ...@@ -116,14 +115,15 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
if (this.properties.isSsl()) { if (this.properties.isSsl()) {
builder.useSsl(); builder.useSsl();
} }
if (this.properties.getTimeout() != 0) { if (this.properties.getTimeout() != null) {
builder.commandTimeout(Duration.ofMillis(this.properties.getTimeout())); builder.commandTimeout(this.properties.getTimeout());
} }
if (this.properties.getLettuce() != null) { if (this.properties.getLettuce() != null) {
RedisProperties.Lettuce lettuce = this.properties.getLettuce(); RedisProperties.Lettuce lettuce = this.properties.getLettuce();
if (lettuce.getShutdownTimeout() >= 0) { if (lettuce.getShutdownTimeout() != null
builder.shutdownTimeout(Duration && !lettuce.getShutdownTimeout().isZero()) {
.ofMillis(this.properties.getLettuce().getShutdownTimeout())); builder.shutdownTimeout(
this.properties.getLettuce().getShutdownTimeout());
} }
} }
return builder; return builder;
...@@ -159,7 +159,9 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { ...@@ -159,7 +159,9 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
config.setMaxTotal(properties.getMaxActive()); config.setMaxTotal(properties.getMaxActive());
config.setMaxIdle(properties.getMaxIdle()); config.setMaxIdle(properties.getMaxIdle());
config.setMinIdle(properties.getMinIdle()); config.setMinIdle(properties.getMinIdle());
config.setMaxWaitMillis(properties.getMaxWait()); if (properties.getMaxWait() != null) {
config.setMaxWaitMillis(properties.getMaxWait().toMillis());
}
return config; return config;
} }
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.autoconfigure.data.redis; package org.springframework.boot.autoconfigure.data.redis;
import java.time.Duration;
import java.util.List; import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
...@@ -64,9 +65,9 @@ public class RedisProperties { ...@@ -64,9 +65,9 @@ public class RedisProperties {
private boolean ssl; private boolean ssl;
/** /**
* Connection timeout in milliseconds. * Connection timeout.
*/ */
private int timeout; private Duration timeout;
private Sentinel sentinel; private Sentinel sentinel;
...@@ -124,11 +125,11 @@ public class RedisProperties { ...@@ -124,11 +125,11 @@ public class RedisProperties {
this.ssl = ssl; this.ssl = ssl;
} }
public void setTimeout(int timeout) { public void setTimeout(Duration timeout) {
this.timeout = timeout; this.timeout = timeout;
} }
public int getTimeout() { public Duration getTimeout() {
return this.timeout; return this.timeout;
} }
...@@ -180,11 +181,11 @@ public class RedisProperties { ...@@ -180,11 +181,11 @@ public class RedisProperties {
private int maxActive = 8; private int maxActive = 8;
/** /**
* Maximum amount of time (in milliseconds) a connection allocation should block * Maximum amount of time a connection allocation should block before throwing an
* before throwing an exception when the pool is exhausted. Use a negative value * exception when the pool is exhausted. Use a negative value to block
* to block indefinitely. * indefinitely.
*/ */
private int maxWait = -1; private Duration maxWait = Duration.ofMillis(-1);
public int getMaxIdle() { public int getMaxIdle() {
return this.maxIdle; return this.maxIdle;
...@@ -210,11 +211,11 @@ public class RedisProperties { ...@@ -210,11 +211,11 @@ public class RedisProperties {
this.maxActive = maxActive; this.maxActive = maxActive;
} }
public int getMaxWait() { public Duration getMaxWait() {
return this.maxWait; return this.maxWait;
} }
public void setMaxWait(int maxWait) { public void setMaxWait(Duration maxWait) {
this.maxWait = maxWait; this.maxWait = maxWait;
} }
...@@ -314,20 +315,20 @@ public class RedisProperties { ...@@ -314,20 +315,20 @@ public class RedisProperties {
public static class Lettuce { public static class Lettuce {
/** /**
* Shutdown timeout in milliseconds. * Shutdown timeout.
*/ */
private int shutdownTimeout = 100; private Duration shutdownTimeout = Duration.ofMillis(100);
/** /**
* Lettuce pool configuration. * Lettuce pool configuration.
*/ */
private Pool pool; private Pool pool;
public int getShutdownTimeout() { public Duration getShutdownTimeout() {
return this.shutdownTimeout; return this.shutdownTimeout;
} }
public void setShutdownTimeout(int shutdownTimeout) { public void setShutdownTimeout(Duration shutdownTimeout) {
this.shutdownTimeout = shutdownTimeout; this.shutdownTimeout = shutdownTimeout;
} }
......
...@@ -87,8 +87,12 @@ public class JestAutoConfiguration { ...@@ -87,8 +87,12 @@ public class JestAutoConfiguration {
builder.gson(gson); builder.gson(gson);
} }
builder.multiThreaded(this.properties.isMultiThreaded()); builder.multiThreaded(this.properties.isMultiThreaded());
builder.connTimeout(this.properties.getConnectionTimeout()) if (this.properties.getConnectionTimeout() != null) {
.readTimeout(this.properties.getReadTimeout()); builder.connTimeout((int) this.properties.getConnectionTimeout().toMillis());
}
if (this.properties.getReadTimeout() != null) {
builder.readTimeout((int) this.properties.getReadTimeout().toMillis());
}
customize(builder); customize(builder);
return builder.build(); return builder.build();
} }
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.autoconfigure.elasticsearch.jest; package org.springframework.boot.autoconfigure.elasticsearch.jest;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
...@@ -53,14 +54,14 @@ public class JestProperties { ...@@ -53,14 +54,14 @@ public class JestProperties {
private boolean multiThreaded = true; private boolean multiThreaded = true;
/** /**
* Connection timeout in milliseconds. * Connection timeout.
*/ */
private int connectionTimeout = 3000; private Duration connectionTimeout = Duration.ofSeconds(3);
/** /**
* Read timeout in milliseconds. * Read timeout.
*/ */
private int readTimeout = 3000; private Duration readTimeout = Duration.ofSeconds(3);
/** /**
* Proxy settings. * Proxy settings.
...@@ -99,19 +100,19 @@ public class JestProperties { ...@@ -99,19 +100,19 @@ public class JestProperties {
this.multiThreaded = multiThreaded; this.multiThreaded = multiThreaded;
} }
public int getConnectionTimeout() { public Duration getConnectionTimeout() {
return this.connectionTimeout; return this.connectionTimeout;
} }
public void setConnectionTimeout(int connectionTimeout) { public void setConnectionTimeout(Duration connectionTimeout) {
this.connectionTimeout = connectionTimeout; this.connectionTimeout = connectionTimeout;
} }
public int getReadTimeout() { public Duration getReadTimeout() {
return this.readTimeout; return this.readTimeout;
} }
public void setReadTimeout(int readTimeout) { public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout; this.readTimeout = readTimeout;
} }
......
...@@ -16,7 +16,11 @@ ...@@ -16,7 +16,11 @@
package org.springframework.boot.autoconfigure.jdbc; package org.springframework.boot.autoconfigure.jdbc;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.convert.DurationUnit;
/** /**
* Configuration properties for JDBC. * Configuration properties for JDBC.
...@@ -51,10 +55,11 @@ public class JdbcProperties { ...@@ -51,10 +55,11 @@ public class JdbcProperties {
private int maxRows = -1; private int maxRows = -1;
/** /**
* Query timeout in seconds. Use -1 to use the JDBC driver's default * Query timeout. Default is to use the JDBC driver's default configuration. If a
* configuration. * duration suffix is not specified, seconds will be used.
*/ */
private int queryTimeout = -1; @DurationUnit(ChronoUnit.SECONDS)
private Duration queryTimeout;
public int getFetchSize() { public int getFetchSize() {
return this.fetchSize; return this.fetchSize;
...@@ -72,11 +77,11 @@ public class JdbcProperties { ...@@ -72,11 +77,11 @@ public class JdbcProperties {
this.maxRows = maxRows; this.maxRows = maxRows;
} }
public int getQueryTimeout() { public Duration getQueryTimeout() {
return this.queryTimeout; return this.queryTimeout;
} }
public void setQueryTimeout(int queryTimeout) { public void setQueryTimeout(Duration queryTimeout) {
this.queryTimeout = queryTimeout; this.queryTimeout = queryTimeout;
} }
......
...@@ -70,7 +70,10 @@ public class JdbcTemplateAutoConfiguration { ...@@ -70,7 +70,10 @@ public class JdbcTemplateAutoConfiguration {
JdbcProperties.Template template = this.properties.getTemplate(); JdbcProperties.Template template = this.properties.getTemplate();
jdbcTemplate.setFetchSize(template.getFetchSize()); jdbcTemplate.setFetchSize(template.getFetchSize());
jdbcTemplate.setMaxRows(template.getMaxRows()); jdbcTemplate.setMaxRows(template.getMaxRows());
jdbcTemplate.setQueryTimeout(template.getQueryTimeout()); if (template.getQueryTimeout() != null) {
jdbcTemplate
.setQueryTimeout((int) template.getQueryTimeout().getSeconds());
}
return jdbcTemplate; return jdbcTemplate;
} }
......
...@@ -84,7 +84,7 @@ public class JmsAutoConfiguration { ...@@ -84,7 +84,7 @@ public class JmsAutoConfiguration {
jmsTemplate.setDefaultDestinationName(template.getDefaultDestination()); jmsTemplate.setDefaultDestinationName(template.getDefaultDestination());
} }
if (template.getDeliveryDelay() != null) { if (template.getDeliveryDelay() != null) {
jmsTemplate.setDeliveryDelay(template.getDeliveryDelay()); jmsTemplate.setDeliveryDelay(template.getDeliveryDelay().toMillis());
} }
jmsTemplate.setExplicitQosEnabled(template.determineQosEnabled()); jmsTemplate.setExplicitQosEnabled(template.determineQosEnabled());
if (template.getDeliveryMode() != null) { if (template.getDeliveryMode() != null) {
...@@ -94,10 +94,10 @@ public class JmsAutoConfiguration { ...@@ -94,10 +94,10 @@ public class JmsAutoConfiguration {
jmsTemplate.setPriority(template.getPriority()); jmsTemplate.setPriority(template.getPriority());
} }
if (template.getTimeToLive() != null) { if (template.getTimeToLive() != null) {
jmsTemplate.setTimeToLive(template.getTimeToLive()); jmsTemplate.setTimeToLive(template.getTimeToLive().toMillis());
} }
if (template.getReceiveTimeout() != null) { if (template.getReceiveTimeout() != null) {
jmsTemplate.setReceiveTimeout(template.getReceiveTimeout()); jmsTemplate.setReceiveTimeout(template.getReceiveTimeout().toMillis());
} }
return jmsTemplate; return jmsTemplate;
} }
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
package org.springframework.boot.autoconfigure.jms; package org.springframework.boot.autoconfigure.jms;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
/** /**
...@@ -142,9 +144,9 @@ public class JmsProperties { ...@@ -142,9 +144,9 @@ public class JmsProperties {
private String defaultDestination; private String defaultDestination;
/** /**
* Delivery delay to use for send calls in milliseconds. * Delivery delay to use for send calls.
*/ */
private Long deliveryDelay; private Duration deliveryDelay;
/** /**
* Delivery mode. Enable QoS when set. * Delivery mode. Enable QoS when set.
...@@ -157,9 +159,9 @@ public class JmsProperties { ...@@ -157,9 +159,9 @@ public class JmsProperties {
private Integer priority; private Integer priority;
/** /**
* Time-to-live of a message when sending in milliseconds. Enable QoS when set. * Time-to-live of a message when sending. Enable QoS when set.
*/ */
private Long timeToLive; private Duration timeToLive;
/** /**
* Enable explicit QoS when sending a message. When enabled, the delivery mode, * Enable explicit QoS when sending a message. When enabled, the delivery mode,
...@@ -169,9 +171,9 @@ public class JmsProperties { ...@@ -169,9 +171,9 @@ public class JmsProperties {
private Boolean qosEnabled; private Boolean qosEnabled;
/** /**
* Timeout to use for receive calls in milliseconds. * Timeout to use for receive calls.
*/ */
private Long receiveTimeout; private Duration receiveTimeout;
public String getDefaultDestination() { public String getDefaultDestination() {
return this.defaultDestination; return this.defaultDestination;
...@@ -181,11 +183,11 @@ public class JmsProperties { ...@@ -181,11 +183,11 @@ public class JmsProperties {
this.defaultDestination = defaultDestination; this.defaultDestination = defaultDestination;
} }
public Long getDeliveryDelay() { public Duration getDeliveryDelay() {
return this.deliveryDelay; return this.deliveryDelay;
} }
public void setDeliveryDelay(Long deliveryDelay) { public void setDeliveryDelay(Duration deliveryDelay) {
this.deliveryDelay = deliveryDelay; this.deliveryDelay = deliveryDelay;
} }
...@@ -205,11 +207,11 @@ public class JmsProperties { ...@@ -205,11 +207,11 @@ public class JmsProperties {
this.priority = priority; this.priority = priority;
} }
public Long getTimeToLive() { public Duration getTimeToLive() {
return this.timeToLive; return this.timeToLive;
} }
public void setTimeToLive(Long timeToLive) { public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive; this.timeToLive = timeToLive;
} }
...@@ -229,11 +231,11 @@ public class JmsProperties { ...@@ -229,11 +231,11 @@ public class JmsProperties {
this.qosEnabled = qosEnabled; this.qosEnabled = qosEnabled;
} }
public Long getReceiveTimeout() { public Duration getReceiveTimeout() {
return this.receiveTimeout; return this.receiveTimeout;
} }
public void setReceiveTimeout(Long receiveTimeout) { public void setReceiveTimeout(Duration receiveTimeout) {
this.receiveTimeout = receiveTimeout; this.receiveTimeout = receiveTimeout;
} }
......
...@@ -67,19 +67,29 @@ class ActiveMQConnectionFactoryConfiguration { ...@@ -67,19 +67,29 @@ class ActiveMQConnectionFactoryConfiguration {
ActiveMQConnectionFactory.class)); ActiveMQConnectionFactory.class));
ActiveMQProperties.Pool pool = properties.getPool(); ActiveMQProperties.Pool pool = properties.getPool();
pooledConnectionFactory.setBlockIfSessionPoolIsFull(pool.isBlockIfFull()); pooledConnectionFactory.setBlockIfSessionPoolIsFull(pool.isBlockIfFull());
pooledConnectionFactory if (pool.getBlockIfFullTimeout() != null) {
.setBlockIfSessionPoolIsFullTimeout(pool.getBlockIfFullTimeout()); pooledConnectionFactory.setBlockIfSessionPoolIsFullTimeout(
pool.getBlockIfFullTimeout().toMillis());
}
pooledConnectionFactory pooledConnectionFactory
.setCreateConnectionOnStartup(pool.isCreateConnectionOnStartup()); .setCreateConnectionOnStartup(pool.isCreateConnectionOnStartup());
pooledConnectionFactory.setExpiryTimeout(pool.getExpiryTimeout()); if (pool.getExpiryTimeout() != null) {
pooledConnectionFactory.setIdleTimeout(pool.getIdleTimeout()); pooledConnectionFactory
.setExpiryTimeout(pool.getExpiryTimeout().toMillis());
}
if (pool.getIdleTimeout() != null) {
pooledConnectionFactory
.setIdleTimeout((int) pool.getIdleTimeout().toMillis());
}
pooledConnectionFactory.setMaxConnections(pool.getMaxConnections()); pooledConnectionFactory.setMaxConnections(pool.getMaxConnections());
pooledConnectionFactory.setMaximumActiveSessionPerConnection( pooledConnectionFactory.setMaximumActiveSessionPerConnection(
pool.getMaximumActiveSessionPerConnection()); pool.getMaximumActiveSessionPerConnection());
pooledConnectionFactory pooledConnectionFactory
.setReconnectOnException(pool.isReconnectOnException()); .setReconnectOnException(pool.isReconnectOnException());
pooledConnectionFactory.setTimeBetweenExpirationCheckMillis( if (pool.getTimeBetweenExpirationCheck() != null) {
pool.getTimeBetweenExpirationCheck()); pooledConnectionFactory.setTimeBetweenExpirationCheckMillis(
pool.getTimeBetweenExpirationCheck().toMillis());
}
pooledConnectionFactory pooledConnectionFactory
.setUseAnonymousProducers(pool.isUseAnonymousProducers()); .setUseAnonymousProducers(pool.isUseAnonymousProducers());
return pooledConnectionFactory; return pooledConnectionFactory;
......
...@@ -66,9 +66,13 @@ class ActiveMQConnectionFactoryFactory { ...@@ -66,9 +66,13 @@ class ActiveMQConnectionFactoryFactory {
private <T extends ActiveMQConnectionFactory> T doCreateConnectionFactory( private <T extends ActiveMQConnectionFactory> T doCreateConnectionFactory(
Class<T> factoryClass) throws Exception { Class<T> factoryClass) throws Exception {
T factory = createConnectionFactoryInstance(factoryClass); T factory = createConnectionFactoryInstance(factoryClass);
factory.setCloseTimeout(this.properties.getCloseTimeout()); if (this.properties.getCloseTimeout() != null) {
factory.setCloseTimeout((int) this.properties.getCloseTimeout().toMillis());
}
factory.setNonBlockingRedelivery(this.properties.isNonBlockingRedelivery()); factory.setNonBlockingRedelivery(this.properties.isNonBlockingRedelivery());
factory.setSendTimeout(this.properties.getSendTimeout()); if (this.properties.getSendTimeout() != null) {
factory.setSendTimeout((int) this.properties.getSendTimeout().toMillis());
}
Packages packages = this.properties.getPackages(); Packages packages = this.properties.getPackages();
if (packages.getTrustAll() != null) { if (packages.getTrustAll() != null) {
factory.setTrustAllPackages(packages.getTrustAll()); factory.setTrustAllPackages(packages.getTrustAll());
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.autoconfigure.jms.activemq; package org.springframework.boot.autoconfigure.jms.activemq;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -54,9 +55,9 @@ public class ActiveMQProperties { ...@@ -54,9 +55,9 @@ public class ActiveMQProperties {
private String password; private String password;
/** /**
* Time to wait, in milliseconds, before considering a close complete. * Time to wait before considering a close complete.
*/ */
private int closeTimeout = 15000; private Duration closeTimeout = Duration.ofSeconds(15);
/** /**
* Do not stop message delivery before re-delivering messages from a rolled back * Do not stop message delivery before re-delivering messages from a rolled back
...@@ -66,10 +67,10 @@ public class ActiveMQProperties { ...@@ -66,10 +67,10 @@ public class ActiveMQProperties {
private boolean nonBlockingRedelivery = false; private boolean nonBlockingRedelivery = false;
/** /**
* Time to wait, in milliseconds, on Message sends for a response. Set it to 0 to * Time to wait on Message sends for a response. Set it to 0 to indicate to wait
* indicate to wait forever. * forever.
*/ */
private int sendTimeout = 0; private Duration sendTimeout = Duration.ofMillis(0);
private Pool pool = new Pool(); private Pool pool = new Pool();
...@@ -107,11 +108,11 @@ public class ActiveMQProperties { ...@@ -107,11 +108,11 @@ public class ActiveMQProperties {
this.password = password; this.password = password;
} }
public int getCloseTimeout() { public Duration getCloseTimeout() {
return this.closeTimeout; return this.closeTimeout;
} }
public void setCloseTimeout(int closeTimeout) { public void setCloseTimeout(Duration closeTimeout) {
this.closeTimeout = closeTimeout; this.closeTimeout = closeTimeout;
} }
...@@ -123,11 +124,11 @@ public class ActiveMQProperties { ...@@ -123,11 +124,11 @@ public class ActiveMQProperties {
this.nonBlockingRedelivery = nonBlockingRedelivery; this.nonBlockingRedelivery = nonBlockingRedelivery;
} }
public int getSendTimeout() { public Duration getSendTimeout() {
return this.sendTimeout; return this.sendTimeout;
} }
public void setSendTimeout(int sendTimeout) { public void setSendTimeout(Duration sendTimeout) {
this.sendTimeout = sendTimeout; this.sendTimeout = sendTimeout;
} }
...@@ -158,10 +159,9 @@ public class ActiveMQProperties { ...@@ -158,10 +159,9 @@ public class ActiveMQProperties {
private boolean blockIfFull = true; private boolean blockIfFull = true;
/** /**
* Blocking period, in milliseconds, before throwing an exception if the pool is * Blocking period, before throwing an exception if the pool is still full.
* still full.
*/ */
private long blockIfFullTimeout = -1; private Duration blockIfFullTimeout = Duration.ofMillis(-1);
/** /**
* Create a connection on startup. Can be used to warm-up the pool on startup. * Create a connection on startup. Can be used to warm-up the pool on startup.
...@@ -169,14 +169,14 @@ public class ActiveMQProperties { ...@@ -169,14 +169,14 @@ public class ActiveMQProperties {
private boolean createConnectionOnStartup = true; private boolean createConnectionOnStartup = true;
/** /**
* Connection expiration timeout in milliseconds. * Connection expiration timeout.
*/ */
private long expiryTimeout = 0; private Duration expiryTimeout = Duration.ofMillis(0);
/** /**
* Connection idle timeout in milliseconds. * Connection idle timeout.
*/ */
private int idleTimeout = 30000; private Duration idleTimeout = Duration.ofSeconds(30);
/** /**
* Maximum number of pooled connections. * Maximum number of pooled connections.
...@@ -194,10 +194,10 @@ public class ActiveMQProperties { ...@@ -194,10 +194,10 @@ public class ActiveMQProperties {
private boolean reconnectOnException = true; private boolean reconnectOnException = true;
/** /**
* Time to sleep, in milliseconds, between runs of the idle connection eviction * Time to sleep between runs of the idle connection eviction thread. When
* thread. When negative, no idle connection eviction thread runs. * negative, no idle connection eviction thread runs.
*/ */
private long timeBetweenExpirationCheck = -1; private Duration timeBetweenExpirationCheck = Duration.ofMillis(-1);
/** /**
* Use only one anonymous "MessageProducer" instance. Set it to false to create * Use only one anonymous "MessageProducer" instance. Set it to false to create
...@@ -221,11 +221,11 @@ public class ActiveMQProperties { ...@@ -221,11 +221,11 @@ public class ActiveMQProperties {
this.blockIfFull = blockIfFull; this.blockIfFull = blockIfFull;
} }
public long getBlockIfFullTimeout() { public Duration getBlockIfFullTimeout() {
return this.blockIfFullTimeout; return this.blockIfFullTimeout;
} }
public void setBlockIfFullTimeout(long blockIfFullTimeout) { public void setBlockIfFullTimeout(Duration blockIfFullTimeout) {
this.blockIfFullTimeout = blockIfFullTimeout; this.blockIfFullTimeout = blockIfFullTimeout;
} }
...@@ -237,19 +237,19 @@ public class ActiveMQProperties { ...@@ -237,19 +237,19 @@ public class ActiveMQProperties {
this.createConnectionOnStartup = createConnectionOnStartup; this.createConnectionOnStartup = createConnectionOnStartup;
} }
public long getExpiryTimeout() { public Duration getExpiryTimeout() {
return this.expiryTimeout; return this.expiryTimeout;
} }
public void setExpiryTimeout(long expiryTimeout) { public void setExpiryTimeout(Duration expiryTimeout) {
this.expiryTimeout = expiryTimeout; this.expiryTimeout = expiryTimeout;
} }
public int getIdleTimeout() { public Duration getIdleTimeout() {
return this.idleTimeout; return this.idleTimeout;
} }
public void setIdleTimeout(int idleTimeout) { public void setIdleTimeout(Duration idleTimeout) {
this.idleTimeout = idleTimeout; this.idleTimeout = idleTimeout;
} }
...@@ -278,11 +278,11 @@ public class ActiveMQProperties { ...@@ -278,11 +278,11 @@ public class ActiveMQProperties {
this.reconnectOnException = reconnectOnException; this.reconnectOnException = reconnectOnException;
} }
public long getTimeBetweenExpirationCheck() { public Duration getTimeBetweenExpirationCheck() {
return this.timeBetweenExpirationCheck; return this.timeBetweenExpirationCheck;
} }
public void setTimeBetweenExpirationCheck(long timeBetweenExpirationCheck) { public void setTimeBetweenExpirationCheck(Duration timeBetweenExpirationCheck) {
this.timeBetweenExpirationCheck = timeBetweenExpirationCheck; this.timeBetweenExpirationCheck = timeBetweenExpirationCheck;
} }
......
...@@ -89,10 +89,10 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer { ...@@ -89,10 +89,10 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer {
containerProperties.setAckCount(container.getAckCount()); containerProperties.setAckCount(container.getAckCount());
} }
if (container.getAckTime() != null) { if (container.getAckTime() != null) {
containerProperties.setAckTime(container.getAckTime()); containerProperties.setAckTime(container.getAckTime().toMillis());
} }
if (container.getPollTimeout() != null) { if (container.getPollTimeout() != null) {
containerProperties.setPollTimeout(container.getPollTimeout()); containerProperties.setPollTimeout(container.getPollTimeout().toMillis());
} }
if (container.getConcurrency() != null) { if (container.getConcurrency() != null) {
listenerContainerFactory.setConcurrency(container.getConcurrency()); listenerContainerFactory.setConcurrency(container.getConcurrency());
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
package org.springframework.boot.autoconfigure.kafka; package org.springframework.boot.autoconfigure.kafka;
import java.io.IOException; import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
...@@ -222,10 +223,10 @@ public class KafkaProperties { ...@@ -222,10 +223,10 @@ public class KafkaProperties {
private final Ssl ssl = new Ssl(); private final Ssl ssl = new Ssl();
/** /**
* Frequency in milliseconds that the consumer offsets are auto-committed to Kafka * Frequency that the consumer offsets are auto-committed to Kafka if
* if 'enable.auto.commit' true. * 'enable.auto.commit' true.
*/ */
private Integer autoCommitInterval; private Duration autoCommitInterval;
/** /**
* What to do when there is no initial offset in Kafka or if the current offset * What to do when there is no initial offset in Kafka or if the current offset
...@@ -250,11 +251,11 @@ public class KafkaProperties { ...@@ -250,11 +251,11 @@ public class KafkaProperties {
private Boolean enableAutoCommit; private Boolean enableAutoCommit;
/** /**
* Maximum amount of time in milliseconds the server will block before answering * Maximum amount of time the server will block before answering the fetch request
* the fetch request if there isn't sufficient data to immediately satisfy the * if there isn't sufficient data to immediately satisfy the requirement given by
* requirement given by "fetch.min.bytes". * "fetch.min.bytes".
*/ */
private Integer fetchMaxWait; private Duration fetchMaxWait;
/** /**
* Minimum amount of data the server should return for a fetch request in bytes. * Minimum amount of data the server should return for a fetch request in bytes.
...@@ -267,9 +268,9 @@ public class KafkaProperties { ...@@ -267,9 +268,9 @@ public class KafkaProperties {
private String groupId; private String groupId;
/** /**
* Expected time in milliseconds between heartbeats to the consumer coordinator. * Expected time between heartbeats to the consumer coordinator.
*/ */
private Integer heartbeatInterval; private Duration heartbeatInterval;
/** /**
* Deserializer class for keys. * Deserializer class for keys.
...@@ -295,11 +296,11 @@ public class KafkaProperties { ...@@ -295,11 +296,11 @@ public class KafkaProperties {
return this.ssl; return this.ssl;
} }
public Integer getAutoCommitInterval() { public Duration getAutoCommitInterval() {
return this.autoCommitInterval; return this.autoCommitInterval;
} }
public void setAutoCommitInterval(Integer autoCommitInterval) { public void setAutoCommitInterval(Duration autoCommitInterval) {
this.autoCommitInterval = autoCommitInterval; this.autoCommitInterval = autoCommitInterval;
} }
...@@ -335,11 +336,11 @@ public class KafkaProperties { ...@@ -335,11 +336,11 @@ public class KafkaProperties {
this.enableAutoCommit = enableAutoCommit; this.enableAutoCommit = enableAutoCommit;
} }
public Integer getFetchMaxWait() { public Duration getFetchMaxWait() {
return this.fetchMaxWait; return this.fetchMaxWait;
} }
public void setFetchMaxWait(Integer fetchMaxWait) { public void setFetchMaxWait(Duration fetchMaxWait) {
this.fetchMaxWait = fetchMaxWait; this.fetchMaxWait = fetchMaxWait;
} }
...@@ -359,11 +360,11 @@ public class KafkaProperties { ...@@ -359,11 +360,11 @@ public class KafkaProperties {
this.groupId = groupId; this.groupId = groupId;
} }
public Integer getHeartbeatInterval() { public Duration getHeartbeatInterval() {
return this.heartbeatInterval; return this.heartbeatInterval;
} }
public void setHeartbeatInterval(Integer heartbeatInterval) { public void setHeartbeatInterval(Duration heartbeatInterval) {
this.heartbeatInterval = heartbeatInterval; this.heartbeatInterval = heartbeatInterval;
} }
...@@ -399,7 +400,7 @@ public class KafkaProperties { ...@@ -399,7 +400,7 @@ public class KafkaProperties {
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
if (this.autoCommitInterval != null) { if (this.autoCommitInterval != null) {
properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,
this.autoCommitInterval); (int) this.autoCommitInterval.toMillis());
} }
if (this.autoOffsetReset != null) { if (this.autoOffsetReset != null) {
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,
...@@ -418,7 +419,7 @@ public class KafkaProperties { ...@@ -418,7 +419,7 @@ public class KafkaProperties {
} }
if (this.fetchMaxWait != null) { if (this.fetchMaxWait != null) {
properties.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, properties.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG,
this.fetchMaxWait); (int) this.fetchMaxWait.toMillis());
} }
if (this.fetchMinSize != null) { if (this.fetchMinSize != null) {
properties.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, this.fetchMinSize); properties.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, this.fetchMinSize);
...@@ -428,7 +429,7 @@ public class KafkaProperties { ...@@ -428,7 +429,7 @@ public class KafkaProperties {
} }
if (this.heartbeatInterval != null) { if (this.heartbeatInterval != null) {
properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG,
this.heartbeatInterval); (int) this.heartbeatInterval.toMillis());
} }
if (this.keyDeserializer != null) { if (this.keyDeserializer != null) {
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
...@@ -800,9 +801,9 @@ public class KafkaProperties { ...@@ -800,9 +801,9 @@ public class KafkaProperties {
private Integer concurrency; private Integer concurrency;
/** /**
* Timeout in milliseconds to use when polling the consumer. * Timeout to use when polling the consumer.
*/ */
private Long pollTimeout; private Duration pollTimeout;
/** /**
* Number of records between offset commits when ackMode is "COUNT" or * Number of records between offset commits when ackMode is "COUNT" or
...@@ -811,10 +812,9 @@ public class KafkaProperties { ...@@ -811,10 +812,9 @@ public class KafkaProperties {
private Integer ackCount; private Integer ackCount;
/** /**
* Time in milliseconds between offset commits when ackMode is "TIME" or * Time between offset commits when ackMode is "TIME" or "COUNT_TIME".
* "COUNT_TIME".
*/ */
private Long ackTime; private Duration ackTime;
public Type getType() { public Type getType() {
return this.type; return this.type;
...@@ -840,11 +840,11 @@ public class KafkaProperties { ...@@ -840,11 +840,11 @@ public class KafkaProperties {
this.concurrency = concurrency; this.concurrency = concurrency;
} }
public Long getPollTimeout() { public Duration getPollTimeout() {
return this.pollTimeout; return this.pollTimeout;
} }
public void setPollTimeout(Long pollTimeout) { public void setPollTimeout(Duration pollTimeout) {
this.pollTimeout = pollTimeout; this.pollTimeout = pollTimeout;
} }
...@@ -856,11 +856,11 @@ public class KafkaProperties { ...@@ -856,11 +856,11 @@ public class KafkaProperties {
this.ackCount = ackCount; this.ackCount = ackCount;
} }
public Long getAckTime() { public Duration getAckTime() {
return this.ackTime; return this.ackTime;
} }
public void setAckTime(Long ackTime) { public void setAckTime(Duration ackTime) {
this.ackTime = ackTime; this.ackTime = ackTime;
} }
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
package org.springframework.boot.autoconfigure.session; package org.springframework.boot.autoconfigure.session;
import java.time.Duration;
import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstance;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -52,9 +54,9 @@ class HazelcastSessionConfiguration { ...@@ -52,9 +54,9 @@ class HazelcastSessionConfiguration {
@Autowired @Autowired
public void customize(SessionProperties sessionProperties, public void customize(SessionProperties sessionProperties,
HazelcastSessionProperties hazelcastSessionProperties) { HazelcastSessionProperties hazelcastSessionProperties) {
Integer timeout = sessionProperties.getTimeout(); Duration timeout = sessionProperties.getTimeout();
if (timeout != null) { if (timeout != null) {
setMaxInactiveIntervalInSeconds(timeout); setMaxInactiveIntervalInSeconds((int) timeout.getSeconds());
} }
setSessionMapName(hazelcastSessionProperties.getMapName()); setSessionMapName(hazelcastSessionProperties.getMapName());
setHazelcastFlushMode(hazelcastSessionProperties.getFlushMode()); setHazelcastFlushMode(hazelcastSessionProperties.getFlushMode());
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
package org.springframework.boot.autoconfigure.session; package org.springframework.boot.autoconfigure.session;
import java.time.Duration;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -63,9 +65,9 @@ class JdbcSessionConfiguration { ...@@ -63,9 +65,9 @@ class JdbcSessionConfiguration {
@Autowired @Autowired
public void customize(SessionProperties sessionProperties, public void customize(SessionProperties sessionProperties,
JdbcSessionProperties jdbcSessionProperties) { JdbcSessionProperties jdbcSessionProperties) {
Integer timeout = sessionProperties.getTimeout(); Duration timeout = sessionProperties.getTimeout();
if (timeout != null) { if (timeout != null) {
setMaxInactiveIntervalInSeconds(timeout); setMaxInactiveIntervalInSeconds((int) timeout.getSeconds());
} }
setTableName(jdbcSessionProperties.getTableName()); setTableName(jdbcSessionProperties.getTableName());
setCleanupCron(jdbcSessionProperties.getCleanupCron()); setCleanupCron(jdbcSessionProperties.getCleanupCron());
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
package org.springframework.boot.autoconfigure.session; package org.springframework.boot.autoconfigure.session;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
...@@ -47,9 +49,9 @@ class MongoReactiveSessionConfiguration { ...@@ -47,9 +49,9 @@ class MongoReactiveSessionConfiguration {
@Autowired @Autowired
public void customize(SessionProperties sessionProperties, public void customize(SessionProperties sessionProperties,
MongoSessionProperties mongoSessionProperties) { MongoSessionProperties mongoSessionProperties) {
Integer timeout = sessionProperties.getTimeout(); Duration timeout = sessionProperties.getTimeout();
if (timeout != null) { if (timeout != null) {
setMaxInactiveIntervalInSeconds(timeout); setMaxInactiveIntervalInSeconds((int) timeout.getSeconds());
} }
setCollectionName(mongoSessionProperties.getCollectionName()); setCollectionName(mongoSessionProperties.getCollectionName());
} }
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
package org.springframework.boot.autoconfigure.session; package org.springframework.boot.autoconfigure.session;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
...@@ -48,9 +50,9 @@ class MongoSessionConfiguration { ...@@ -48,9 +50,9 @@ class MongoSessionConfiguration {
@Autowired @Autowired
public void customize(SessionProperties sessionProperties, public void customize(SessionProperties sessionProperties,
MongoSessionProperties mongoSessionProperties) { MongoSessionProperties mongoSessionProperties) {
Integer timeout = sessionProperties.getTimeout(); Duration timeout = sessionProperties.getTimeout();
if (timeout != null) { if (timeout != null) {
setMaxInactiveIntervalInSeconds(timeout); setMaxInactiveIntervalInSeconds((int) timeout.getSeconds());
} }
setCollectionName(mongoSessionProperties.getCollectionName()); setCollectionName(mongoSessionProperties.getCollectionName());
} }
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
package org.springframework.boot.autoconfigure.session; package org.springframework.boot.autoconfigure.session;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
...@@ -52,9 +54,9 @@ class RedisReactiveSessionConfiguration { ...@@ -52,9 +54,9 @@ class RedisReactiveSessionConfiguration {
public void customize(SessionProperties sessionProperties, public void customize(SessionProperties sessionProperties,
RedisSessionProperties redisSessionProperties) { RedisSessionProperties redisSessionProperties) {
this.sessionProperties = sessionProperties; this.sessionProperties = sessionProperties;
Integer timeout = this.sessionProperties.getTimeout(); Duration timeout = this.sessionProperties.getTimeout();
if (timeout != null) { if (timeout != null) {
setMaxInactiveIntervalInSeconds(timeout); setMaxInactiveIntervalInSeconds((int) timeout.getSeconds());
} }
setRedisNamespace(redisSessionProperties.getNamespace()); setRedisNamespace(redisSessionProperties.getNamespace());
setRedisFlushMode(redisSessionProperties.getFlushMode()); setRedisFlushMode(redisSessionProperties.getFlushMode());
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
package org.springframework.boot.autoconfigure.session; package org.springframework.boot.autoconfigure.session;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
...@@ -56,9 +58,9 @@ class RedisSessionConfiguration { ...@@ -56,9 +58,9 @@ class RedisSessionConfiguration {
public void customize(SessionProperties sessionProperties, public void customize(SessionProperties sessionProperties,
RedisSessionProperties redisSessionProperties) { RedisSessionProperties redisSessionProperties) {
this.sessionProperties = sessionProperties; this.sessionProperties = sessionProperties;
Integer timeout = this.sessionProperties.getTimeout(); Duration timeout = this.sessionProperties.getTimeout();
if (timeout != null) { if (timeout != null) {
setMaxInactiveIntervalInSeconds(timeout); setMaxInactiveIntervalInSeconds((int) timeout.getSeconds());
} }
setRedisNamespace(redisSessionProperties.getNamespace()); setRedisNamespace(redisSessionProperties.getNamespace());
setRedisFlushMode(redisSessionProperties.getFlushMode()); setRedisFlushMode(redisSessionProperties.getFlushMode());
......
...@@ -16,12 +16,14 @@ ...@@ -16,12 +16,14 @@
package org.springframework.boot.autoconfigure.session; package org.springframework.boot.autoconfigure.session;
import java.time.Duration;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties.Session;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.DispatcherType; import org.springframework.boot.web.servlet.DispatcherType;
import org.springframework.session.web.http.SessionRepositoryFilter; import org.springframework.session.web.http.SessionRepositoryFilter;
...@@ -42,13 +44,17 @@ public class SessionProperties { ...@@ -42,13 +44,17 @@ public class SessionProperties {
*/ */
private StoreType storeType; private StoreType storeType;
private final Integer timeout; /**
* Session timeout.
*/
private final Duration timeout;
private Servlet servlet = new Servlet(); private Servlet servlet = new Servlet();
public SessionProperties(ObjectProvider<ServerProperties> serverProperties) { public SessionProperties(ObjectProvider<ServerProperties> serverProperties) {
ServerProperties properties = serverProperties.getIfUnique(); ServerProperties properties = serverProperties.getIfUnique();
this.timeout = (properties != null ? properties.getSession().getTimeout() : null); Session session = (properties == null ? null : properties.getSession());
this.timeout = (session == null ? null : session.getTimeout());
} }
public StoreType getStoreType() { public StoreType getStoreType() {
...@@ -60,11 +66,11 @@ public class SessionProperties { ...@@ -60,11 +66,11 @@ public class SessionProperties {
} }
/** /**
* Return the session timeout in seconds. * Return the session timeout.
* @return the session timeout in seconds * @return the session timeout
* @see ServerProperties#getSession() * @see ServerProperties#getSession()
*/ */
public Integer getTimeout() { public Duration getTimeout() {
return this.timeout; return this.timeout;
} }
......
...@@ -16,7 +16,11 @@ ...@@ -16,7 +16,11 @@
package org.springframework.boot.autoconfigure.transaction; package org.springframework.boot.autoconfigure.transaction;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.convert.DurationUnit;
import org.springframework.transaction.support.AbstractPlatformTransactionManager; import org.springframework.transaction.support.AbstractPlatformTransactionManager;
/** /**
...@@ -32,20 +36,22 @@ public class TransactionProperties implements ...@@ -32,20 +36,22 @@ public class TransactionProperties implements
PlatformTransactionManagerCustomizer<AbstractPlatformTransactionManager> { PlatformTransactionManagerCustomizer<AbstractPlatformTransactionManager> {
/** /**
* Default transaction timeout in seconds. * Default transaction timeout. If a duration suffix is not specified, seconds will be
* used.
*/ */
private Integer defaultTimeout; @DurationUnit(ChronoUnit.SECONDS)
private Duration defaultTimeout;
/** /**
* Perform the rollback on commit failures. * Perform the rollback on commit failures.
*/ */
private Boolean rollbackOnCommitFailure; private Boolean rollbackOnCommitFailure;
public Integer getDefaultTimeout() { public Duration getDefaultTimeout() {
return this.defaultTimeout; return this.defaultTimeout;
} }
public void setDefaultTimeout(Integer defaultTimeout) { public void setDefaultTimeout(Duration defaultTimeout) {
this.defaultTimeout = defaultTimeout; this.defaultTimeout = defaultTimeout;
} }
...@@ -60,7 +66,7 @@ public class TransactionProperties implements ...@@ -60,7 +66,7 @@ public class TransactionProperties implements
@Override @Override
public void customize(AbstractPlatformTransactionManager transactionManager) { public void customize(AbstractPlatformTransactionManager transactionManager) {
if (this.defaultTimeout != null) { if (this.defaultTimeout != null) {
transactionManager.setDefaultTimeout(this.defaultTimeout); transactionManager.setDefaultTimeout((int) this.defaultTimeout.getSeconds());
} }
if (this.rollbackOnCommitFailure != null) { if (this.rollbackOnCommitFailure != null) {
transactionManager.setRollbackOnCommitFailure(this.rollbackOnCommitFailure); transactionManager.setRollbackOnCommitFailure(this.rollbackOnCommitFailure);
......
...@@ -16,7 +16,11 @@ ...@@ -16,7 +16,11 @@
package org.springframework.boot.autoconfigure.web; package org.springframework.boot.autoconfigure.web;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.convert.DurationUnit;
/** /**
* Properties used to configure resource handling. * Properties used to configure resource handling.
...@@ -41,9 +45,11 @@ public class ResourceProperties { ...@@ -41,9 +45,11 @@ public class ResourceProperties {
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS; private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
/** /**
* Cache period for the resources served by the resource handler, in seconds. * Cache period for the resources served by the resource handler. If a duration suffix
* is not specified, seconds will be used.
*/ */
private Integer cachePeriod; @DurationUnit(ChronoUnit.SECONDS)
private Duration cachePeriod;
/** /**
* Enable default resource handling. * Enable default resource handling.
...@@ -69,11 +75,11 @@ public class ResourceProperties { ...@@ -69,11 +75,11 @@ public class ResourceProperties {
return normalized; return normalized;
} }
public Integer getCachePeriod() { public Duration getCachePeriod() {
return this.cachePeriod; return this.cachePeriod;
} }
public void setCachePeriod(Integer cachePeriod) { public void setCachePeriod(Duration cachePeriod) {
this.cachePeriod = cachePeriod; this.cachePeriod = cachePeriod;
} }
......
...@@ -19,6 +19,8 @@ package org.springframework.boot.autoconfigure.web; ...@@ -19,6 +19,8 @@ package org.springframework.boot.autoconfigure.web;
import java.io.File; import java.io.File;
import java.net.InetAddress; import java.net.InetAddress;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
...@@ -30,6 +32,7 @@ import java.util.TimeZone; ...@@ -30,6 +32,7 @@ import java.util.TimeZone;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.boot.context.properties.bind.convert.DurationUnit;
import org.springframework.boot.web.server.Compression; import org.springframework.boot.web.server.Compression;
import org.springframework.boot.web.server.Http2; import org.springframework.boot.web.server.Http2;
import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.Ssl;
...@@ -89,11 +92,11 @@ public class ServerProperties { ...@@ -89,11 +92,11 @@ public class ServerProperties {
private int maxHttpHeaderSize = 0; // bytes private int maxHttpHeaderSize = 0; // bytes
/** /**
* Time in milliseconds that connectors will wait for another HTTP request before * Time that connectors will wait for another HTTP request before closing the
* closing the connection. When not set, the connector's server-specific default will * connection. When not set, the connector's server-specific default will be used. Use
* be used. Use a value of -1 to indicate no (i.e. infinite) timeout. * a value of -1 to indicate no (i.e. infinite) timeout.
*/ */
private Integer connectionTimeout; private Duration connectionTimeout;
private Session session = new Session(); private Session session = new Session();
...@@ -162,11 +165,11 @@ public class ServerProperties { ...@@ -162,11 +165,11 @@ public class ServerProperties {
this.maxHttpHeaderSize = maxHttpHeaderSize; this.maxHttpHeaderSize = maxHttpHeaderSize;
} }
public Integer getConnectionTimeout() { public Duration getConnectionTimeout() {
return this.connectionTimeout; return this.connectionTimeout;
} }
public void setConnectionTimeout(Integer connectionTimeout) { public void setConnectionTimeout(Duration connectionTimeout) {
this.connectionTimeout = connectionTimeout; this.connectionTimeout = connectionTimeout;
} }
...@@ -335,9 +338,10 @@ public class ServerProperties { ...@@ -335,9 +338,10 @@ public class ServerProperties {
public static class Session { public static class Session {
/** /**
* Session timeout in seconds. * Session timeout. If a duration suffix is not specified, seconds will be used.
*/ */
private Integer timeout; @DurationUnit(ChronoUnit.SECONDS)
private Duration timeout;
/** /**
* Session tracking modes (one or more of the following: "cookie", "url", "ssl"). * Session tracking modes (one or more of the following: "cookie", "url", "ssl").
...@@ -360,12 +364,12 @@ public class ServerProperties { ...@@ -360,12 +364,12 @@ public class ServerProperties {
return this.cookie; return this.cookie;
} }
public Integer getTimeout() { public Duration getTimeout() {
return this.timeout; return this.timeout;
} }
public void setTimeout(Integer sessionTimeout) { public void setTimeout(Duration timeout) {
this.timeout = sessionTimeout; this.timeout = timeout;
} }
public Set<SessionTrackingMode> getTrackingModes() { public Set<SessionTrackingMode> getTrackingModes() {
...@@ -428,9 +432,10 @@ public class ServerProperties { ...@@ -428,9 +432,10 @@ public class ServerProperties {
private Boolean secure; private Boolean secure;
/** /**
* Maximum age of the session cookie in seconds. * Maximum age of the session cookie.
*/ */
private Integer maxAge; @DurationUnit(ChronoUnit.SECONDS)
private Duration maxAge;
public String getName() { public String getName() {
return this.name; return this.name;
...@@ -480,11 +485,11 @@ public class ServerProperties { ...@@ -480,11 +485,11 @@ public class ServerProperties {
this.secure = secure; this.secure = secure;
} }
public Integer getMaxAge() { public Duration getMaxAge() {
return this.maxAge; return this.maxAge;
} }
public void setMaxAge(Integer maxAge) { public void setMaxAge(Duration maxAge) {
this.maxAge = maxAge; this.maxAge = maxAge;
} }
...@@ -562,29 +567,31 @@ public class ServerProperties { ...@@ -562,29 +567,31 @@ public class ServerProperties {
private File basedir; private File basedir;
/** /**
* Delay in seconds between the invocation of backgroundProcess methods. * Delay between the invocation of backgroundProcess methods. If a duration suffix
* is not specified, seconds will be used.
*/ */
private int backgroundProcessorDelay = 30; // seconds @DurationUnit(ChronoUnit.SECONDS)
private Duration backgroundProcessorDelay = Duration.ofSeconds(30);
/** /**
* Maximum amount of worker threads. * Maximum amount of worker threads.
*/ */
private int maxThreads = 0; // Number of threads in protocol handler private int maxThreads = 0;
/** /**
* Minimum amount of worker threads. * Minimum amount of worker threads.
*/ */
private int minSpareThreads = 0; // Minimum spare threads in protocol handler private int minSpareThreads = 0;
/** /**
* Maximum size in bytes of the HTTP post content. * Maximum size in bytes of the HTTP post content.
*/ */
private int maxHttpPostSize = 0; // bytes private int maxHttpPostSize = 0;
/** /**
* Maximum size in bytes of the HTTP message header. * Maximum size in bytes of the HTTP message header.
*/ */
private int maxHttpHeaderSize = 0; // bytes private int maxHttpHeaderSize = 0;
/** /**
* Whether requests to the context root should be redirected by appending a / to * Whether requests to the context root should be redirected by appending a / to
...@@ -650,11 +657,11 @@ public class ServerProperties { ...@@ -650,11 +657,11 @@ public class ServerProperties {
return this.accesslog; return this.accesslog;
} }
public int getBackgroundProcessorDelay() { public Duration getBackgroundProcessorDelay() {
return this.backgroundProcessorDelay; return this.backgroundProcessorDelay;
} }
public void setBackgroundProcessorDelay(int backgroundProcessorDelay) { public void setBackgroundProcessorDelay(Duration backgroundProcessorDelay) {
this.backgroundProcessorDelay = backgroundProcessorDelay; this.backgroundProcessorDelay = backgroundProcessorDelay;
} }
...@@ -903,15 +910,15 @@ public class ServerProperties { ...@@ -903,15 +910,15 @@ public class ServerProperties {
public static class Resource { public static class Resource {
/** /**
* Time-to-live in milliseconds of the static resource cache. * Time-to-live of the static resource cache.
*/ */
private Long cacheTtl; private Duration cacheTtl;
public Long getCacheTtl() { public Duration getCacheTtl() {
return this.cacheTtl; return this.cacheTtl;
} }
public void setCacheTtl(Long cacheTtl) { public void setCacheTtl(Duration cacheTtl) {
this.cacheTtl = cacheTtl; this.cacheTtl = cacheTtl;
} }
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.autoconfigure.web.reactive; package org.springframework.boot.autoconfigure.web.reactive;
import java.time.Duration;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
...@@ -145,14 +146,14 @@ public class WebFluxAutoConfiguration { ...@@ -145,14 +146,14 @@ public class WebFluxAutoConfiguration {
logger.debug("Default resource handling disabled"); logger.debug("Default resource handling disabled");
return; return;
} }
Integer cachePeriod = this.resourceProperties.getCachePeriod(); Duration cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) { if (!registry.hasMappingForPattern("/webjars/**")) {
ResourceHandlerRegistration registration = registry ResourceHandlerRegistration registration = registry
.addResourceHandler("/webjars/**") .addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/"); .addResourceLocations("classpath:/META-INF/resources/webjars/");
if (cachePeriod != null) { if (cachePeriod != null) {
registration.setCacheControl( registration.setCacheControl(CacheControl
CacheControl.maxAge(cachePeriod, TimeUnit.SECONDS)); .maxAge(cachePeriod.toMillis(), TimeUnit.MILLISECONDS));
} }
customizeResourceHandlerRegistration(registration); customizeResourceHandlerRegistration(registration);
} }
...@@ -162,8 +163,8 @@ public class WebFluxAutoConfiguration { ...@@ -162,8 +163,8 @@ public class WebFluxAutoConfiguration {
.addResourceHandler(staticPathPattern).addResourceLocations( .addResourceHandler(staticPathPattern).addResourceLocations(
this.resourceProperties.getStaticLocations()); this.resourceProperties.getStaticLocations());
if (cachePeriod != null) { if (cachePeriod != null) {
registration.setCacheControl( registration.setCacheControl(CacheControl
CacheControl.maxAge(cachePeriod, TimeUnit.SECONDS)); .maxAge(cachePeriod.toMillis(), TimeUnit.MILLISECONDS));
} }
customizeResourceHandlerRegistration(registration); customizeResourceHandlerRegistration(registration);
} }
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.autoconfigure.web.servlet; package org.springframework.boot.autoconfigure.web.servlet;
import java.time.Duration;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
...@@ -195,7 +196,7 @@ public class DefaultServletWebServerFactoryCustomizer ...@@ -195,7 +196,7 @@ public class DefaultServletWebServerFactoryCustomizer
config.setSecure(cookie.getSecure()); config.setSecure(cookie.getSecure());
} }
if (cookie.getMaxAge() != null) { if (cookie.getMaxAge() != null) {
config.setMaxAge(cookie.getMaxAge()); config.setMaxAge((int) cookie.getMaxAge().getSeconds());
} }
} }
...@@ -217,13 +218,14 @@ public class DefaultServletWebServerFactoryCustomizer ...@@ -217,13 +218,14 @@ public class DefaultServletWebServerFactoryCustomizer
public static void customizeTomcat(ServerProperties serverProperties, public static void customizeTomcat(ServerProperties serverProperties,
Environment environment, TomcatServletWebServerFactory factory) { Environment environment, TomcatServletWebServerFactory factory) {
ServerProperties.Tomcat tomcatProperties = serverProperties.getTomcat(); ServerProperties.Tomcat tomcatProperties = serverProperties.getTomcat();
if (tomcatProperties.getBasedir() != null) { if (tomcatProperties.getBasedir() != null) {
factory.setBaseDirectory(tomcatProperties.getBasedir()); factory.setBaseDirectory(tomcatProperties.getBasedir());
} }
factory.setBackgroundProcessorDelay( if (tomcatProperties.getBackgroundProcessorDelay() != null) {
tomcatProperties.getBackgroundProcessorDelay()); factory.setBackgroundProcessorDelay((int) tomcatProperties
.getBackgroundProcessorDelay().getSeconds());
}
customizeRemoteIpValve(serverProperties, environment, factory); customizeRemoteIpValve(serverProperties, environment, factory);
if (tomcatProperties.getMaxThreads() > 0) { if (tomcatProperties.getMaxThreads() > 0) {
customizeMaxThreads(factory, tomcatProperties.getMaxThreads()); customizeMaxThreads(factory, tomcatProperties.getMaxThreads());
...@@ -290,12 +292,12 @@ public class DefaultServletWebServerFactoryCustomizer ...@@ -290,12 +292,12 @@ public class DefaultServletWebServerFactoryCustomizer
} }
private static void customizeConnectionTimeout( private static void customizeConnectionTimeout(
TomcatServletWebServerFactory factory, final int connectionTimeout) { TomcatServletWebServerFactory factory, Duration connectionTimeout) {
factory.addConnectorCustomizers((connector) -> { factory.addConnectorCustomizers((connector) -> {
ProtocolHandler handler = connector.getProtocolHandler(); ProtocolHandler handler = connector.getProtocolHandler();
if (handler instanceof AbstractProtocol) { if (handler instanceof AbstractProtocol) {
AbstractProtocol<?> protocol = (AbstractProtocol<?>) handler; AbstractProtocol<?> protocol = (AbstractProtocol<?>) handler;
protocol.setConnectionTimeout(connectionTimeout); protocol.setConnectionTimeout((int) connectionTimeout.toMillis());
} }
}); });
} }
...@@ -398,7 +400,8 @@ public class DefaultServletWebServerFactoryCustomizer ...@@ -398,7 +400,8 @@ public class DefaultServletWebServerFactoryCustomizer
factory.addContextCustomizers((context) -> { factory.addContextCustomizers((context) -> {
context.addLifecycleListener((event) -> { context.addLifecycleListener((event) -> {
if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) { if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
context.getResources().setCacheTtl(resource.getCacheTtl()); long ttl = resource.getCacheTtl().toMillis();
context.getResources().setCacheTtl(ttl);
} }
}); });
}); });
...@@ -453,9 +456,10 @@ public class DefaultServletWebServerFactoryCustomizer ...@@ -453,9 +456,10 @@ public class DefaultServletWebServerFactoryCustomizer
} }
private static void customizeConnectionTimeout( private static void customizeConnectionTimeout(
UndertowServletWebServerFactory factory, final int connectionTimeout) { UndertowServletWebServerFactory factory, Duration connectionTimeout) {
factory.addBuilderCustomizers((builder) -> builder.setSocketOption( factory.addBuilderCustomizers((builder) -> builder.setSocketOption(
UndertowOptions.NO_REQUEST_TIMEOUT, connectionTimeout)); UndertowOptions.NO_REQUEST_TIMEOUT,
(int) connectionTimeout.toMillis()));
} }
private static void customizeMaxHttpHeaderSize( private static void customizeMaxHttpHeaderSize(
...@@ -503,12 +507,13 @@ public class DefaultServletWebServerFactoryCustomizer ...@@ -503,12 +507,13 @@ public class DefaultServletWebServerFactoryCustomizer
} }
private static void customizeConnectionTimeout( private static void customizeConnectionTimeout(
JettyServletWebServerFactory factory, final int connectionTimeout) { JettyServletWebServerFactory factory, Duration connectionTimeout) {
factory.addServerCustomizers((server) -> { factory.addServerCustomizers((server) -> {
for (org.eclipse.jetty.server.Connector connector : server for (org.eclipse.jetty.server.Connector connector : server
.getConnectors()) { .getConnectors()) {
if (connector instanceof AbstractConnector) { if (connector instanceof AbstractConnector) {
((AbstractConnector) connector).setIdleTimeout(connectionTimeout); ((AbstractConnector) connector)
.setIdleTimeout(connectionTimeout.toMillis());
} }
} }
}); });
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.autoconfigure.web.servlet; package org.springframework.boot.autoconfigure.web.servlet;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
...@@ -207,9 +208,9 @@ public class WebMvcAutoConfiguration { ...@@ -207,9 +208,9 @@ public class WebMvcAutoConfiguration {
@Override @Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) { public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
Long timeout = this.mvcProperties.getAsync().getRequestTimeout(); Duration timeout = this.mvcProperties.getAsync().getRequestTimeout();
if (timeout != null) { if (timeout != null) {
configurer.setDefaultTimeout(timeout); configurer.setDefaultTimeout(timeout.toMillis());
} }
} }
...@@ -305,13 +306,13 @@ public class WebMvcAutoConfiguration { ...@@ -305,13 +306,13 @@ public class WebMvcAutoConfiguration {
logger.debug("Default resource handling disabled"); logger.debug("Default resource handling disabled");
return; return;
} }
Integer cachePeriod = this.resourceProperties.getCachePeriod(); Duration cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) { if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration( customizeResourceHandlerRegistration(
registry.addResourceHandler("/webjars/**") registry.addResourceHandler("/webjars/**")
.addResourceLocations( .addResourceLocations(
"classpath:/META-INF/resources/webjars/") "classpath:/META-INF/resources/webjars/")
.setCachePeriod(cachePeriod)); .setCachePeriod(getSeconds(cachePeriod)));
} }
String staticPathPattern = this.mvcProperties.getStaticPathPattern(); String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) { if (!registry.hasMappingForPattern(staticPathPattern)) {
...@@ -319,10 +320,14 @@ public class WebMvcAutoConfiguration { ...@@ -319,10 +320,14 @@ public class WebMvcAutoConfiguration {
registry.addResourceHandler(staticPathPattern) registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations( .addResourceLocations(getResourceLocations(
this.resourceProperties.getStaticLocations())) this.resourceProperties.getStaticLocations()))
.setCachePeriod(cachePeriod)); .setCachePeriod(getSeconds(cachePeriod)));
} }
} }
private Integer getSeconds(Duration cachePeriod) {
return (cachePeriod == null ? null : (int) cachePeriod.getSeconds());
}
@Bean @Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping() { public WelcomePageHandlerMapping welcomePageHandlerMapping() {
return new WelcomePageHandlerMapping(getWelcomePage(), return new WelcomePageHandlerMapping(getWelcomePage(),
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.autoconfigure.web.servlet; package org.springframework.boot.autoconfigure.web.servlet;
import java.time.Duration;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
...@@ -204,17 +205,17 @@ public class WebMvcProperties { ...@@ -204,17 +205,17 @@ public class WebMvcProperties {
public static class Async { public static class Async {
/** /**
* Amount of time (in milliseconds) before asynchronous request handling times * Amount of time before asynchronous request handling times out. If this value is
* out. If this value is not set, the default timeout of the underlying * not set, the default timeout of the underlying implementation is used, e.g. 10
* implementation is used, e.g. 10 seconds on Tomcat with Servlet 3. * seconds on Tomcat with Servlet 3.
*/ */
private Long requestTimeout; private Duration requestTimeout;
public Long getRequestTimeout() { public Duration getRequestTimeout() {
return this.requestTimeout; return this.requestTimeout;
} }
public void setRequestTimeout(Long requestTimeout) { public void setRequestTimeout(Duration requestTimeout) {
this.requestTimeout = requestTimeout; this.requestTimeout = requestTimeout;
} }
......
...@@ -1036,6 +1036,24 @@ ...@@ -1036,6 +1036,24 @@
"level": "error" "level": "error"
} }
}, },
{
"name": "spring.data.cassandra.connect-timeout-millis",
"type": "java.lang.Integer",
"description": "Socket option: connection time out.",
"deprecation": {
"replacement": "spring.data.cassandra.connect-timeout",
"level": "error"
}
},
{
"name": "spring.data.cassandra.read-timeout-millis",
"type": "java.lang.Integer",
"description": "Socket option: read time out.",
"deprecation": {
"replacement": "spring.data.cassandra.read-timeout",
"level": "error"
}
},
{ {
"name": "spring.data.neo4j.compiler", "name": "spring.data.neo4j.compiler",
"type": "java.lang.String", "type": "java.lang.String",
...@@ -1130,6 +1148,15 @@ ...@@ -1130,6 +1148,15 @@
"level": "error" "level": "error"
} }
}, },
{
"name": "spring.messages.cache-seconds",
"type": "java.lang.Integer",
"description": "Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever",
"deprecation": {
"replacement": "spring.messages.cache-duration",
"level": "error"
}
},
{ {
"name": "spring.redis.pool.max-active", "name": "spring.redis.pool.max-active",
"type": "java.lang.Integer", "type": "java.lang.Integer",
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
package org.springframework.boot.autoconfigure.jms; package org.springframework.boot.autoconfigure.jms;
import java.time.Duration;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
...@@ -72,7 +74,7 @@ public class JmsPropertiesTests { ...@@ -72,7 +74,7 @@ public class JmsPropertiesTests {
@Test @Test
public void setTimeToLiveEnablesQoS() { public void setTimeToLiveEnablesQoS() {
JmsProperties properties = new JmsProperties(); JmsProperties properties = new JmsProperties();
properties.getTemplate().setTimeToLive(5000L); properties.getTemplate().setTimeToLive(Duration.ofSeconds(5));
assertThat(properties.getTemplate().determineQosEnabled()).isTrue(); assertThat(properties.getTemplate().determineQosEnabled()).isTrue();
} }
......
...@@ -18,6 +18,7 @@ package org.springframework.boot.autoconfigure.web; ...@@ -18,6 +18,7 @@ package org.springframework.boot.autoconfigure.web;
import java.net.InetAddress; import java.net.InetAddress;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -72,8 +73,9 @@ public class ServerPropertiesTests { ...@@ -72,8 +73,9 @@ public class ServerPropertiesTests {
@Test @Test
public void testConnectionTimeout() throws Exception { public void testConnectionTimeout() throws Exception {
bind("server.connection-timeout", "60000"); bind("server.connection-timeout", "60s");
assertThat(this.properties.getConnectionTimeout()).isEqualTo(60000); assertThat(this.properties.getConnectionTimeout())
.isEqualTo(Duration.ofMillis(60000));
} }
@Test @Test
...@@ -115,7 +117,8 @@ public class ServerPropertiesTests { ...@@ -115,7 +117,8 @@ public class ServerPropertiesTests {
assertThat(tomcat.getProtocolHeader()).isEqualTo("X-Forwarded-Protocol"); assertThat(tomcat.getProtocolHeader()).isEqualTo("X-Forwarded-Protocol");
assertThat(tomcat.getInternalProxies()) assertThat(tomcat.getInternalProxies())
.isEqualTo("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); .isEqualTo("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
assertThat(tomcat.getBackgroundProcessorDelay()).isEqualTo(10); assertThat(tomcat.getBackgroundProcessorDelay())
.isEqualTo(Duration.ofSeconds(10));
} }
@Test @Test
......
...@@ -18,6 +18,7 @@ package org.springframework.boot.autoconfigure.web.servlet; ...@@ -18,6 +18,7 @@ package org.springframework.boot.autoconfigure.web.servlet;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.time.Duration;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
...@@ -212,7 +213,7 @@ public class DefaultServletWebServerFactoryCustomizerTests { ...@@ -212,7 +213,7 @@ public class DefaultServletWebServerFactoryCustomizerTests {
given(servletContext.getSessionCookieConfig()).willReturn(sessionCookieConfig); given(servletContext.getSessionCookieConfig()).willReturn(sessionCookieConfig);
this.customizer.customize(factory); this.customizer.customize(factory);
triggerInitializers(factory, servletContext); triggerInitializers(factory, servletContext);
verify(factory).setSessionTimeout(123); verify(factory).setSessionTimeout(Duration.ofSeconds(123));
verify(servletContext).setSessionTrackingModes( verify(servletContext).setSessionTrackingModes(
EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL)); EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL));
verify(sessionCookieConfig).setName("testname"); verify(sessionCookieConfig).setName("testname");
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
package org.springframework.boot.devtools.autoconfigure; package org.springframework.boot.devtools.autoconfigure;
import java.io.File; import java.io.File;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -62,10 +63,6 @@ public class DevToolsProperties { ...@@ -62,10 +63,6 @@ public class DevToolsProperties {
+ "META-INF/resources/**,resources/**,static/**,public/**,templates/**," + "META-INF/resources/**,resources/**,static/**,public/**,templates/**,"
+ "**/*Test.class,**/*Tests.class,git.properties,META-INF/build-info.properties"; + "**/*Test.class,**/*Tests.class,git.properties,META-INF/build-info.properties";
private static final long DEFAULT_RESTART_POLL_INTERVAL = 1000;
private static final long DEFAULT_RESTART_QUIET_PERIOD = 400;
/** /**
* Enable automatic restart. * Enable automatic restart.
*/ */
...@@ -82,15 +79,15 @@ public class DevToolsProperties { ...@@ -82,15 +79,15 @@ public class DevToolsProperties {
private String additionalExclude; private String additionalExclude;
/** /**
* Amount of time (in milliseconds) to wait between polling for classpath changes. * Amount of time to wait between polling for classpath changes.
*/ */
private long pollInterval = DEFAULT_RESTART_POLL_INTERVAL; private Duration pollInterval = Duration.ofSeconds(1);
/** /**
* Amount of quiet time (in milliseconds) required without any classpath changes * Amount of quiet time required without any classpath changes before a restart is
* before a restart is triggered. * triggered.
*/ */
private long quietPeriod = DEFAULT_RESTART_QUIET_PERIOD; private Duration quietPeriod = Duration.ofMillis(400);
/** /**
* Name of a specific file that when changed will trigger the restart check. If * Name of a specific file that when changed will trigger the restart check. If
...@@ -139,19 +136,19 @@ public class DevToolsProperties { ...@@ -139,19 +136,19 @@ public class DevToolsProperties {
this.additionalExclude = additionalExclude; this.additionalExclude = additionalExclude;
} }
public long getPollInterval() { public Duration getPollInterval() {
return this.pollInterval; return this.pollInterval;
} }
public void setPollInterval(long pollInterval) { public void setPollInterval(Duration pollInterval) {
this.pollInterval = pollInterval; this.pollInterval = pollInterval;
} }
public long getQuietPeriod() { public Duration getQuietPeriod() {
return this.quietPeriod; return this.quietPeriod;
} }
public void setQuietPeriod(long quietPeriod) { public void setQuietPeriod(Duration quietPeriod) {
this.quietPeriod = quietPeriod; this.quietPeriod = quietPeriod;
} }
......
...@@ -18,6 +18,7 @@ package org.springframework.boot.devtools.filewatch; ...@@ -18,6 +18,7 @@ package org.springframework.boot.devtools.filewatch;
import java.io.File; import java.io.File;
import java.io.FileFilter; import java.io.FileFilter;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
...@@ -41,9 +42,9 @@ import org.springframework.util.Assert; ...@@ -41,9 +42,9 @@ import org.springframework.util.Assert;
*/ */
public class FileSystemWatcher { public class FileSystemWatcher {
private static final long DEFAULT_POLL_INTERVAL = 1000; private static final Duration DEFAULT_POLL_INTERVAL = Duration.ofMillis(1000);
private static final long DEFAULT_QUIET_PERIOD = 400; private static final Duration DEFAULT_QUIET_PERIOD = Duration.ofMillis(400);
private final List<FileChangeListener> listeners = new ArrayList<>(); private final List<FileChangeListener> listeners = new ArrayList<>();
...@@ -77,14 +78,17 @@ public class FileSystemWatcher { ...@@ -77,14 +78,17 @@ public class FileSystemWatcher {
* @param quietPeriod the amount of time required after a change has been detected to * @param quietPeriod the amount of time required after a change has been detected to
* ensure that updates have completed * ensure that updates have completed
*/ */
public FileSystemWatcher(boolean daemon, long pollInterval, long quietPeriod) { public FileSystemWatcher(boolean daemon, Duration pollInterval,
Assert.isTrue(pollInterval > 0, "PollInterval must be positive"); Duration quietPeriod) {
Assert.isTrue(quietPeriod > 0, "QuietPeriod must be positive"); Assert.notNull(pollInterval, "PollInterval must not be null");
Assert.isTrue(pollInterval > quietPeriod, Assert.notNull(quietPeriod, "QuietPeriod must not be null");
Assert.isTrue(pollInterval.toMillis() > 0, "PollInterval must be positive");
Assert.isTrue(quietPeriod.toMillis() > 0, "QuietPeriod must be positive");
Assert.isTrue(pollInterval.toMillis() > quietPeriod.toMillis(),
"PollInterval must be greater than QuietPeriod"); "PollInterval must be greater than QuietPeriod");
this.daemon = daemon; this.daemon = daemon;
this.pollInterval = pollInterval; this.pollInterval = pollInterval.toMillis();
this.quietPeriod = quietPeriod; this.quietPeriod = quietPeriod.toMillis();
} }
/** /**
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
package org.springframework.boot.devtools.autoconfigure; package org.springframework.boot.devtools.autoconfigure;
import java.io.File; import java.io.File;
import java.time.Duration;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -120,7 +121,7 @@ public class LocalDevToolsAutoConfigurationTests { ...@@ -120,7 +121,7 @@ public class LocalDevToolsAutoConfigurationTests {
public void resourceCachePeriodIsZero() throws Exception { public void resourceCachePeriodIsZero() throws Exception {
this.context = initializeAndRun(WebResourcesConfig.class); this.context = initializeAndRun(WebResourcesConfig.class);
ResourceProperties properties = this.context.getBean(ResourceProperties.class); ResourceProperties properties = this.context.getBean(ResourceProperties.class);
assertThat(properties.getCachePeriod()).isEqualTo(0); assertThat(properties.getCachePeriod()).isEqualTo(Duration.ZERO);
} }
@Test @Test
......
...@@ -18,6 +18,7 @@ package org.springframework.boot.devtools.classpath; ...@@ -18,6 +18,7 @@ package org.springframework.boot.devtools.classpath;
import java.io.File; import java.io.File;
import java.net.URL; import java.net.URL;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
...@@ -104,7 +105,8 @@ public class ClassPathFileSystemWatcherTests { ...@@ -104,7 +105,8 @@ public class ClassPathFileSystemWatcherTests {
@Bean @Bean
public ClassPathFileSystemWatcher watcher() { public ClassPathFileSystemWatcher watcher() {
FileSystemWatcher watcher = new FileSystemWatcher(false, 100, 10); FileSystemWatcher watcher = new FileSystemWatcher(false,
Duration.ofMillis(100), Duration.ofMillis(10));
URL[] urls = this.environment.getProperty("urls", URL[].class); URL[] urls = this.environment.getProperty("urls", URL[].class);
return new ClassPathFileSystemWatcher( return new ClassPathFileSystemWatcher(
new MockFileSystemWatcherFactory(watcher), restartStrategy(), urls); new MockFileSystemWatcherFactory(watcher), restartStrategy(), urls);
......
...@@ -20,6 +20,7 @@ import java.io.File; ...@@ -20,6 +20,7 @@ import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
...@@ -66,21 +67,21 @@ public class FileSystemWatcherTests { ...@@ -66,21 +67,21 @@ public class FileSystemWatcherTests {
public void pollIntervalMustBePositive() throws Exception { public void pollIntervalMustBePositive() throws Exception {
this.thrown.expect(IllegalArgumentException.class); this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("PollInterval must be positive"); this.thrown.expectMessage("PollInterval must be positive");
new FileSystemWatcher(true, 0, 1); new FileSystemWatcher(true, Duration.ofMillis(0), Duration.ofMillis(1));
} }
@Test @Test
public void quietPeriodMustBePositive() throws Exception { public void quietPeriodMustBePositive() throws Exception {
this.thrown.expect(IllegalArgumentException.class); this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("QuietPeriod must be positive"); this.thrown.expectMessage("QuietPeriod must be positive");
new FileSystemWatcher(true, 1, 0); new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(0));
} }
@Test @Test
public void pollIntervalMustBeGreaterThanQuietPeriod() throws Exception { public void pollIntervalMustBeGreaterThanQuietPeriod() throws Exception {
this.thrown.expect(IllegalArgumentException.class); this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("PollInterval must be greater than QuietPeriod"); this.thrown.expectMessage("PollInterval must be greater than QuietPeriod");
new FileSystemWatcher(true, 1, 1); new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(1));
} }
@Test @Test
...@@ -272,7 +273,8 @@ public class FileSystemWatcherTests { ...@@ -272,7 +273,8 @@ public class FileSystemWatcherTests {
} }
private void setupWatcher(long pollingInterval, long quietPeriod) { private void setupWatcher(long pollingInterval, long quietPeriod) {
this.watcher = new FileSystemWatcher(false, pollingInterval, quietPeriod); this.watcher = new FileSystemWatcher(false, Duration.ofMillis(pollingInterval),
Duration.ofMillis(quietPeriod));
this.watcher.addListener( this.watcher.addListener(
(changeSet) -> FileSystemWatcherTests.this.changes.add(changeSet)); (changeSet) -> FileSystemWatcherTests.this.changes.add(changeSet));
} }
......
...@@ -107,7 +107,7 @@ public class BinderConversionService implements ConversionService { ...@@ -107,7 +107,7 @@ public class BinderConversionService implements ConversionService {
service.addConverter(new StringToInetAddressConverter()); service.addConverter(new StringToInetAddressConverter());
service.addConverter(new InetAddressToStringConverter()); service.addConverter(new InetAddressToStringConverter());
service.addConverter(new PropertyEditorConverter()); service.addConverter(new PropertyEditorConverter());
service.addConverter(new StringToDurationConverter()); service.addConverter(new DurationConverter());
DateFormatterRegistrar registrar = new DateFormatterRegistrar(); DateFormatterRegistrar registrar = new DateFormatterRegistrar();
DateFormatter formatter = new DateFormatter(); DateFormatter formatter = new DateFormatter();
formatter.setIso(DateTimeFormat.ISO.DATE_TIME); formatter.setIso(DateTimeFormat.ISO.DATE_TIME);
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.jta.atomikos; package org.springframework.boot.jta.atomikos;
import java.time.Duration;
import java.util.Properties; import java.util.Properties;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
...@@ -40,14 +41,14 @@ public class AtomikosProperties { ...@@ -40,14 +41,14 @@ public class AtomikosProperties {
private String service; private String service;
/** /**
* Maximum timeout (in milliseconds) that can be allowed for transactions. * Maximum timeout that can be allowed for transactions.
*/ */
private long maxTimeout = 300000; private Duration maxTimeout = Duration.ofMillis(300000);
/** /**
* Default timeout for JTA transactions. * Default timeout for JTA transactions.
*/ */
private long defaultJtaTimeout = 10000; private Duration defaultJtaTimeout = Duration.ofMillis(10000);
/** /**
* Maximum number of active transactions. * Maximum number of active transactions.
...@@ -122,17 +123,16 @@ public class AtomikosProperties { ...@@ -122,17 +123,16 @@ public class AtomikosProperties {
} }
/** /**
* Specifies the maximum timeout (in milliseconds) that can be allowed for * Specifies the maximum timeout that can be allowed for transactions. Defaults to
* transactions. Defaults to {@literal 300000}. This means that calls to * {@literal 300000}. This means that calls to UserTransaction.setTransactionTimeout()
* UserTransaction.setTransactionTimeout() with a value higher than configured here * with a value higher than configured here will be max'ed to this value.
* will be max'ed to this value.
* @param maxTimeout the max timeout * @param maxTimeout the max timeout
*/ */
public void setMaxTimeout(long maxTimeout) { public void setMaxTimeout(Duration maxTimeout) {
this.maxTimeout = maxTimeout; this.maxTimeout = maxTimeout;
} }
public long getMaxTimeout() { public Duration getMaxTimeout() {
return this.maxTimeout; return this.maxTimeout;
} }
...@@ -141,11 +141,11 @@ public class AtomikosProperties { ...@@ -141,11 +141,11 @@ public class AtomikosProperties {
* ms). * ms).
* @param defaultJtaTimeout the default JTA timeout * @param defaultJtaTimeout the default JTA timeout
*/ */
public void setDefaultJtaTimeout(long defaultJtaTimeout) { public void setDefaultJtaTimeout(Duration defaultJtaTimeout) {
this.defaultJtaTimeout = defaultJtaTimeout; this.defaultJtaTimeout = defaultJtaTimeout;
} }
public long getDefaultJtaTimeout() { public Duration getDefaultJtaTimeout() {
return this.defaultJtaTimeout; return this.defaultJtaTimeout;
} }
...@@ -332,10 +332,17 @@ public class AtomikosProperties { ...@@ -332,10 +332,17 @@ public class AtomikosProperties {
private void set(Properties properties, String key, Object value) { private void set(Properties properties, String key, Object value) {
String id = "com.atomikos.icatch." + key; String id = "com.atomikos.icatch." + key;
if (value != null && !properties.containsKey(id)) { if (value != null && !properties.containsKey(id)) {
properties.setProperty(id, value.toString()); properties.setProperty(id, asString(value));
} }
} }
private String asString(Object value) {
if (value instanceof Duration) {
return String.valueOf(((Duration) value).toMillis());
}
return value.toString();
}
/** /**
* Recovery specific settings. * Recovery specific settings.
*/ */
...@@ -344,12 +351,12 @@ public class AtomikosProperties { ...@@ -344,12 +351,12 @@ public class AtomikosProperties {
/** /**
* Delay after which recovery can cleanup pending ('orphaned') log entries. * Delay after which recovery can cleanup pending ('orphaned') log entries.
*/ */
private long forgetOrphanedLogEntriesDelay = 86400000; private Duration forgetOrphanedLogEntriesDelay = Duration.ofMillis(86400000);
/** /**
* Delay between two recovery scans. * Delay between two recovery scans.
*/ */
private long delay = 10000; private Duration delay = Duration.ofMillis(10000);
/** /**
* Number of retry attempts to commit the transaction before throwing an * Number of retry attempts to commit the transaction before throwing an
...@@ -360,21 +367,22 @@ public class AtomikosProperties { ...@@ -360,21 +367,22 @@ public class AtomikosProperties {
/** /**
* Delay between retry attempts. * Delay between retry attempts.
*/ */
private long retryInterval = 10000; private Duration retryInterval = Duration.ofMillis(10000);
public long getForgetOrphanedLogEntriesDelay() { public Duration getForgetOrphanedLogEntriesDelay() {
return this.forgetOrphanedLogEntriesDelay; return this.forgetOrphanedLogEntriesDelay;
} }
public void setForgetOrphanedLogEntriesDelay(long forgetOrphanedLogEntriesDelay) { public void setForgetOrphanedLogEntriesDelay(
Duration forgetOrphanedLogEntriesDelay) {
this.forgetOrphanedLogEntriesDelay = forgetOrphanedLogEntriesDelay; this.forgetOrphanedLogEntriesDelay = forgetOrphanedLogEntriesDelay;
} }
public long getDelay() { public Duration getDelay() {
return this.delay; return this.delay;
} }
public void setDelay(long delay) { public void setDelay(Duration delay) {
this.delay = delay; this.delay = delay;
} }
...@@ -386,11 +394,11 @@ public class AtomikosProperties { ...@@ -386,11 +394,11 @@ public class AtomikosProperties {
this.maxRetries = maxRetries; this.maxRetries = maxRetries;
} }
public long getRetryInterval() { public Duration getRetryInterval() {
return this.retryInterval; return this.retryInterval;
} }
public void setRetryInterval(long retryInterval) { public void setRetryInterval(Duration retryInterval) {
this.retryInterval = retryInterval; this.retryInterval = retryInterval;
} }
......
...@@ -52,9 +52,17 @@ public class NarayanaConfigurationBean implements InitializingBean { ...@@ -52,9 +52,17 @@ public class NarayanaConfigurationBean implements InitializingBean {
setNodeIdentifier(this.properties.getTransactionManagerId()); setNodeIdentifier(this.properties.getTransactionManagerId());
setObjectStoreDir(this.properties.getLogDir()); setObjectStoreDir(this.properties.getLogDir());
setCommitOnePhase(this.properties.isOnePhaseCommit()); setCommitOnePhase(this.properties.isOnePhaseCommit());
setDefaultTimeout(this.properties.getDefaultTimeout()); if (this.properties.getDefaultTimeout() != null) {
setPeriodicRecoveryPeriod(this.properties.getPeriodicRecoveryPeriod()); setDefaultTimeout((int) this.properties.getDefaultTimeout().getSeconds());
setRecoveryBackoffPeriod(this.properties.getRecoveryBackoffPeriod()); }
if (this.properties.getPeriodicRecoveryPeriod() != null) {
setPeriodicRecoveryPeriod(
(int) this.properties.getPeriodicRecoveryPeriod().getSeconds());
}
if (this.properties.getRecoveryBackoffPeriod() != null) {
setRecoveryBackoffPeriod(
(int) this.properties.getRecoveryBackoffPeriod().getSeconds());
}
setXaResourceOrphanFilters(this.properties.getXaResourceOrphanFilters()); setXaResourceOrphanFilters(this.properties.getXaResourceOrphanFilters());
setRecoveryModules(this.properties.getRecoveryModules()); setRecoveryModules(this.properties.getRecoveryModules());
setExpiryScanners(this.properties.getExpiryScanners()); setExpiryScanners(this.properties.getExpiryScanners());
......
...@@ -16,12 +16,15 @@ ...@@ -16,12 +16,15 @@
package org.springframework.boot.jta.narayana; package org.springframework.boot.jta.narayana;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.convert.DurationUnit;
/** /**
* Subset of Narayana properties which can be configured via Spring configuration. Use * Subset of Narayana properties which can be configured via Spring configuration. Use
...@@ -54,19 +57,24 @@ public class NarayanaProperties { ...@@ -54,19 +57,24 @@ public class NarayanaProperties {
private boolean onePhaseCommit = true; private boolean onePhaseCommit = true;
/** /**
* Transaction timeout in seconds. * Transaction timeout. If a duration suffix is not specified, seconds will be used.
*/ */
private int defaultTimeout = 60; @DurationUnit(ChronoUnit.SECONDS)
private Duration defaultTimeout = Duration.ofSeconds(60);
/** /**
* Interval in which periodic recovery scans are performed in seconds. * Interval in which periodic recovery scans are performed. If a duration suffix is
* not specified, seconds will be used.
*/ */
private int periodicRecoveryPeriod = 120; @DurationUnit(ChronoUnit.SECONDS)
private Duration periodicRecoveryPeriod = Duration.ofSeconds(120);
/** /**
* Back off period between first and second phases of the recovery scan in seconds. * Back off period between first and second phases of the recovery scan. If a duration
* suffix is not specified, seconds will be used.
*/ */
private int recoveryBackoffPeriod = 10; @DurationUnit(ChronoUnit.SECONDS)
private Duration recoveryBackoffPeriod = Duration.ofSeconds(10);
/** /**
* Database username to be used by recovery manager. * Database username to be used by recovery manager.
...@@ -132,30 +140,30 @@ public class NarayanaProperties { ...@@ -132,30 +140,30 @@ public class NarayanaProperties {
this.onePhaseCommit = onePhaseCommit; this.onePhaseCommit = onePhaseCommit;
} }
public int getDefaultTimeout() { public Duration getDefaultTimeout() {
return this.defaultTimeout; return this.defaultTimeout;
} }
public int getPeriodicRecoveryPeriod() { public void setDefaultTimeout(Duration defaultTimeout) {
this.defaultTimeout = defaultTimeout;
}
public Duration getPeriodicRecoveryPeriod() {
return this.periodicRecoveryPeriod; return this.periodicRecoveryPeriod;
} }
public void setPeriodicRecoveryPeriod(int periodicRecoveryPeriod) { public void setPeriodicRecoveryPeriod(Duration periodicRecoveryPeriod) {
this.periodicRecoveryPeriod = periodicRecoveryPeriod; this.periodicRecoveryPeriod = periodicRecoveryPeriod;
} }
public int getRecoveryBackoffPeriod() { public Duration getRecoveryBackoffPeriod() {
return this.recoveryBackoffPeriod; return this.recoveryBackoffPeriod;
} }
public void setRecoveryBackoffPeriod(int recoveryBackoffPeriod) { public void setRecoveryBackoffPeriod(Duration recoveryBackoffPeriod) {
this.recoveryBackoffPeriod = recoveryBackoffPeriod; this.recoveryBackoffPeriod = recoveryBackoffPeriod;
} }
public void setDefaultTimeout(int defaultTimeout) {
this.defaultTimeout = defaultTimeout;
}
public List<String> getXaResourceOrphanFilters() { public List<String> getXaResourceOrphanFilters() {
return this.xaResourceOrphanFilters; return this.xaResourceOrphanFilters;
} }
......
...@@ -246,7 +246,8 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor ...@@ -246,7 +246,8 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor
private void configureSession(WebAppContext context) { private void configureSession(WebAppContext context) {
SessionHandler handler = context.getSessionHandler(); SessionHandler handler = context.getSessionHandler();
handler.setMaxInactiveInterval( handler.setMaxInactiveInterval(
getSessionTimeout() > 0 ? getSessionTimeout() : -1); (getSessionTimeout() == null || getSessionTimeout().isNegative()) ? -1
: (int) getSessionTimeout().getSeconds());
if (isPersistSession()) { if (isPersistSession()) {
DefaultSessionCache cache = new DefaultSessionCache(handler); DefaultSessionCache cache = new DefaultSessionCache(handler);
FileSessionDataStore store = new FileSessionDataStore(); FileSessionDataStore store = new FileSessionDataStore();
......
...@@ -22,6 +22,7 @@ import java.lang.reflect.Method; ...@@ -22,6 +22,7 @@ import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
...@@ -32,7 +33,6 @@ import java.util.Locale; ...@@ -32,7 +33,6 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContainerInitializer;
...@@ -385,11 +385,12 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto ...@@ -385,11 +385,12 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto
} }
private long getSessionTimeoutInMinutes() { private long getSessionTimeoutInMinutes() {
long sessionTimeout = getSessionTimeout(); Duration sessionTimeout = getSessionTimeout();
if (sessionTimeout > 0) { if (sessionTimeout == null || sessionTimeout.isNegative()
sessionTimeout = Math.max(TimeUnit.SECONDS.toMinutes(sessionTimeout), 1L); || sessionTimeout.isZero()) {
return 0;
} }
return sessionTimeout; return Math.max(sessionTimeout.toMinutes(), 1);
} }
/** /**
......
...@@ -290,7 +290,9 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac ...@@ -290,7 +290,9 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac
DeploymentManager manager = Servlets.newContainer().addDeployment(deployment); DeploymentManager manager = Servlets.newContainer().addDeployment(deployment);
manager.deploy(); manager.deploy();
SessionManager sessionManager = manager.getDeployment().getSessionManager(); SessionManager sessionManager = manager.getDeployment().getSessionManager();
int sessionTimeout = (getSessionTimeout() > 0 ? getSessionTimeout() : -1); int sessionTimeout = (getSessionTimeout() == null || getSessionTimeout().isZero()
|| getSessionTimeout().isNegative() ? -1
: (int) getSessionTimeout().toMinutes());
sessionManager.setDefaultSessionTimeout(sessionTimeout); sessionManager.setDefaultSessionTimeout(sessionTimeout);
return manager; return manager;
} }
......
...@@ -19,13 +19,13 @@ package org.springframework.boot.web.servlet.server; ...@@ -19,13 +19,13 @@ package org.springframework.boot.web.servlet.server;
import java.io.File; import java.io.File;
import java.net.URL; import java.net.URL;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
...@@ -52,16 +52,13 @@ public abstract class AbstractServletWebServerFactory ...@@ -52,16 +52,13 @@ public abstract class AbstractServletWebServerFactory
extends AbstractConfigurableWebServerFactory extends AbstractConfigurableWebServerFactory
implements ConfigurableServletWebServerFactory { implements ConfigurableServletWebServerFactory {
private static final int DEFAULT_SESSION_TIMEOUT = (int) TimeUnit.MINUTES
.toSeconds(30);
protected final Log logger = LogFactory.getLog(getClass()); protected final Log logger = LogFactory.getLog(getClass());
private String contextPath = ""; private String contextPath = "";
private String displayName; private String displayName;
private int sessionTimeout = DEFAULT_SESSION_TIMEOUT; private Duration sessionTimeout = Duration.ofMinutes(30);
private boolean persistSession; private boolean persistSession;
...@@ -147,24 +144,18 @@ public abstract class AbstractServletWebServerFactory ...@@ -147,24 +144,18 @@ public abstract class AbstractServletWebServerFactory
} }
/** /**
* Return the session timeout in seconds. * Return the session timeout or {@code null}.
* @return the timeout in seconds * @return the session timeout
*/ */
public int getSessionTimeout() { public Duration getSessionTimeout() {
return this.sessionTimeout; return this.sessionTimeout;
} }
@Override @Override
public void setSessionTimeout(int sessionTimeout) { public void setSessionTimeout(Duration sessionTimeout) {
this.sessionTimeout = sessionTimeout; this.sessionTimeout = sessionTimeout;
} }
@Override
public void setSessionTimeout(int sessionTimeout, TimeUnit timeUnit) {
Assert.notNull(timeUnit, "TimeUnit must not be null");
this.sessionTimeout = (int) timeUnit.toSeconds(sessionTimeout);
}
public boolean isPersistSession() { public boolean isPersistSession() {
return this.persistSession; return this.persistSession;
} }
......
...@@ -18,10 +18,10 @@ package org.springframework.boot.web.servlet.server; ...@@ -18,10 +18,10 @@ package org.springframework.boot.web.servlet.server;
import java.io.File; import java.io.File;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.time.Duration;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.web.server.ConfigurableWebServerFactory; import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.MimeMappings; import org.springframework.boot.web.server.MimeMappings;
...@@ -59,19 +59,11 @@ public interface ConfigurableServletWebServerFactory ...@@ -59,19 +59,11 @@ public interface ConfigurableServletWebServerFactory
void setDisplayName(String displayName); void setDisplayName(String displayName);
/** /**
* The session timeout in seconds (default 30 minutes). If 0 or negative then sessions * The session timeout in seconds (default 30 minutes). If {@code null} then sessions
* never expire. * never expire.
* @param sessionTimeout the session timeout * @param sessionTimeout the session timeout
*/ */
void setSessionTimeout(int sessionTimeout); void setSessionTimeout(Duration sessionTimeout);
/**
* The session timeout in the specified {@link TimeUnit} (default 30 minutes). If 0 or
* negative then sessions never expire.
* @param sessionTimeout the session timeout
* @param timeUnit the time unit
*/
void setSessionTimeout(int sessionTimeout, TimeUnit timeUnit);
/** /**
* Sets if session data should be persisted between restarts. * Sets if session data should be persisted between restarts.
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.jta.atomikos; package org.springframework.boot.jta.atomikos;
import java.time.Duration;
import java.util.Properties; import java.util.Properties;
import org.assertj.core.data.MapEntry; import org.assertj.core.data.MapEntry;
...@@ -40,8 +41,8 @@ public class AtomikosPropertiesTests { ...@@ -40,8 +41,8 @@ public class AtomikosPropertiesTests {
@Test @Test
public void testProperties() { public void testProperties() {
this.properties.setService("service"); this.properties.setService("service");
this.properties.setMaxTimeout(1L); this.properties.setMaxTimeout(Duration.ofMillis(1));
this.properties.setDefaultJtaTimeout(2L); this.properties.setDefaultJtaTimeout(Duration.ofMillis(2));
this.properties.setMaxActives(3); this.properties.setMaxActives(3);
this.properties.setEnableLogging(true); this.properties.setEnableLogging(true);
this.properties.setTransactionManagerUniqueName("uniqueName"); this.properties.setTransactionManagerUniqueName("uniqueName");
...@@ -52,10 +53,11 @@ public class AtomikosPropertiesTests { ...@@ -52,10 +53,11 @@ public class AtomikosPropertiesTests {
this.properties.setLogBaseDir("logBaseDir"); this.properties.setLogBaseDir("logBaseDir");
this.properties.setCheckpointInterval(4); this.properties.setCheckpointInterval(4);
this.properties.setThreadedTwoPhaseCommit(true); this.properties.setThreadedTwoPhaseCommit(true);
this.properties.getRecovery().setForgetOrphanedLogEntriesDelay(2000); this.properties.getRecovery()
this.properties.getRecovery().setDelay(3000); .setForgetOrphanedLogEntriesDelay(Duration.ofMillis(2000));
this.properties.getRecovery().setDelay(Duration.ofMillis(3000));
this.properties.getRecovery().setMaxRetries(10); this.properties.getRecovery().setMaxRetries(10);
this.properties.getRecovery().setRetryInterval(4000); this.properties.getRecovery().setRetryInterval(Duration.ofMillis(4000));
assertThat(this.properties.asProperties().size()).isEqualTo(17); assertThat(this.properties.asProperties().size()).isEqualTo(17);
assertProperty("com.atomikos.icatch.service", "service"); assertProperty("com.atomikos.icatch.service", "service");
assertProperty("com.atomikos.icatch.max_timeout", "1"); assertProperty("com.atomikos.icatch.max_timeout", "1");
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.springframework.boot.jta.narayana; package org.springframework.boot.jta.narayana;
import java.time.Duration;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -100,9 +101,9 @@ public class NarayanaConfigurationBeanTests { ...@@ -100,9 +101,9 @@ public class NarayanaConfigurationBeanTests {
NarayanaProperties narayanaProperties = new NarayanaProperties(); NarayanaProperties narayanaProperties = new NarayanaProperties();
narayanaProperties.setTransactionManagerId("test-id"); narayanaProperties.setTransactionManagerId("test-id");
narayanaProperties.setLogDir("test-dir"); narayanaProperties.setLogDir("test-dir");
narayanaProperties.setDefaultTimeout(1); narayanaProperties.setDefaultTimeout(Duration.ofSeconds(1));
narayanaProperties.setPeriodicRecoveryPeriod(2); narayanaProperties.setPeriodicRecoveryPeriod(Duration.ofSeconds(2));
narayanaProperties.setRecoveryBackoffPeriod(3); narayanaProperties.setRecoveryBackoffPeriod(Duration.ofSeconds(3));
narayanaProperties.setOnePhaseCommit(false); narayanaProperties.setOnePhaseCommit(false);
narayanaProperties.setXaResourceOrphanFilters( narayanaProperties.setXaResourceOrphanFilters(
Arrays.asList("test-filter-1", "test-filter-2")); Arrays.asList("test-filter-1", "test-filter-2"));
......
...@@ -17,10 +17,10 @@ ...@@ -17,10 +17,10 @@
package org.springframework.boot.web.embedded.jetty; package org.springframework.boot.web.embedded.jetty;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.time.Duration;
import java.util.Arrays; import java.util.Arrays;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.jasper.servlet.JspServlet; import org.apache.jasper.servlet.JspServlet;
import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Handler;
...@@ -99,14 +99,14 @@ public class JettyServletWebServerFactoryTests ...@@ -99,14 +99,14 @@ public class JettyServletWebServerFactoryTests
@Test @Test
public void sessionTimeout() throws Exception { public void sessionTimeout() throws Exception {
JettyServletWebServerFactory factory = getFactory(); JettyServletWebServerFactory factory = getFactory();
factory.setSessionTimeout(10); factory.setSessionTimeout(Duration.ofSeconds(10));
assertTimeout(factory, 10); assertTimeout(factory, 10);
} }
@Test @Test
public void sessionTimeoutInMins() throws Exception { public void sessionTimeoutInMins() throws Exception {
JettyServletWebServerFactory factory = getFactory(); JettyServletWebServerFactory factory = getFactory();
factory.setSessionTimeout(1, TimeUnit.MINUTES); factory.setSessionTimeout(Duration.ofMinutes(1));
assertTimeout(factory, 60); assertTimeout(factory, 60);
} }
......
...@@ -20,11 +20,11 @@ import java.io.File; ...@@ -20,11 +20,11 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays; import java.util.Arrays;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.naming.InitialContext; import javax.naming.InitialContext;
import javax.naming.NamingException; import javax.naming.NamingException;
...@@ -187,21 +187,21 @@ public class TomcatServletWebServerFactoryTests ...@@ -187,21 +187,21 @@ public class TomcatServletWebServerFactoryTests
@Test @Test
public void sessionTimeout() throws Exception { public void sessionTimeout() throws Exception {
TomcatServletWebServerFactory factory = getFactory(); TomcatServletWebServerFactory factory = getFactory();
factory.setSessionTimeout(10); factory.setSessionTimeout(Duration.ofSeconds(10));
assertTimeout(factory, 1); assertTimeout(factory, 1);
} }
@Test @Test
public void sessionTimeoutInMins() throws Exception { public void sessionTimeoutInMins() throws Exception {
TomcatServletWebServerFactory factory = getFactory(); TomcatServletWebServerFactory factory = getFactory();
factory.setSessionTimeout(1, TimeUnit.MINUTES); factory.setSessionTimeout(Duration.ofMinutes(1));
assertTimeout(factory, 1); assertTimeout(factory, 1);
} }
@Test @Test
public void noSessionTimeout() throws Exception { public void noSessionTimeout() throws Exception {
TomcatServletWebServerFactory factory = getFactory(); TomcatServletWebServerFactory factory = getFactory();
factory.setSessionTimeout(0); factory.setSessionTimeout(null);
assertTimeout(factory, -1); assertTimeout(factory, -1);
} }
......
...@@ -35,6 +35,7 @@ import java.security.KeyStoreException; ...@@ -35,6 +35,7 @@ import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
...@@ -712,7 +713,7 @@ public abstract class AbstractServletWebServerFactoryTests { ...@@ -712,7 +713,7 @@ public abstract class AbstractServletWebServerFactoryTests {
@Test @Test
public void defaultSessionTimeout() throws Exception { public void defaultSessionTimeout() throws Exception {
assertThat(getFactory().getSessionTimeout()).isEqualTo(30 * 60); assertThat(getFactory().getSessionTimeout()).isEqualTo(Duration.ofMinutes(30));
} }
@Test @Test
......
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