Avoid java.util.Optional signatures for simple field access

Issue: SPR-15576
This commit is contained in:
Juergen Hoeller
2017-05-23 22:05:15 +02:00
parent ce5e2b94c4
commit db69a082d9
62 changed files with 467 additions and 549 deletions

View File

@@ -17,13 +17,12 @@
package org.springframework.http;
import java.time.Duration;
import java.util.Optional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* An {@code HttpCookie} sub-class with the additional attributes allowed in
* An {@code HttpCookie} subclass with the additional attributes allowed in
* the "Set-Cookie" response header. To build an instance use the {@link #from}
* static method.
*
@@ -35,9 +34,9 @@ public final class ResponseCookie extends HttpCookie {
private final Duration maxAge;
private final Optional<String> domain;
private final String domain;
private final Optional<String> path;
private final String path;
private final boolean secure;
@@ -53,8 +52,8 @@ public final class ResponseCookie extends HttpCookie {
super(name, value);
Assert.notNull(maxAge, "Max age must not be null");
this.maxAge = maxAge;
this.domain = Optional.ofNullable(domain);
this.path = Optional.ofNullable(path);
this.domain = domain;
this.path = path;
this.secure = secure;
this.httpOnly = httpOnly;
}
@@ -72,16 +71,16 @@ public final class ResponseCookie extends HttpCookie {
}
/**
* Return the cookie "Domain" attribute.
* Return the cookie "Domain" attribute, or {@code null} if not set.
*/
public Optional<String> getDomain() {
public String getDomain() {
return this.domain;
}
/**
* Return the cookie "Path" attribute.
* Return the cookie "Path" attribute, or {@code null} if not set.
*/
public Optional<String> getPath() {
public String getPath() {
return this.path;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,21 +17,21 @@
package org.springframework.http.codec;
import java.time.Duration;
import java.util.Optional;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
/**
* Representation for a Server-Sent Event for use with Spring's reactive Web
* support. {@code Flux<ServerSentEvent>} or {@code Observable<ServerSentEvent>} is the
* Representation for a Server-Sent Event for use with Spring's reactive Web support.
* {@code Flux<ServerSentEvent>} or {@code Observable<ServerSentEvent>} is the
* reactive equivalent to Spring MVC's {@code SseEmitter}.
*
* @param <T> the type of data that this event contains
*
* @author Sebastien Deleuze
* @author Arjen Poutsma
* @since 5.0
* @see ServerSentEventHttpMessageWriter
* @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommendation</a>
* @since 5.0
*/
public class ServerSentEvent<T> {
@@ -54,68 +54,69 @@ public class ServerSentEvent<T> {
this.comment = comment;
}
/**
* Return a builder for a {@code SseEvent}.
*
* @param <T> the type of data that this event contains
* @return the builder
*/
public static <T> Builder<T> builder() {
return new BuilderImpl<>();
}
/**
* Return a builder for a {@code SseEvent}, populated with the give {@linkplain #data() data}.
*
* @param <T> the type of data that this event contains
* @return the builder
*/
public static <T> Builder<T> builder(T data) {
return new BuilderImpl<>(data);
}
/**
* Return the {@code id} field of this event, if available.
*/
public Optional<String> id() {
return Optional.ofNullable(this.id);
public String id() {
return this.id;
}
/**
* Return the {@code event} field of this event, if available.
*/
public Optional<String> event() {
return Optional.ofNullable(this.event);
public String event() {
return this.event;
}
/**
* Return the {@code data} field of this event, if available.
*/
public Optional<T> data() {
return Optional.ofNullable(this.data);
public T data() {
return this.data;
}
/**
* Return the {@code retry} field of this event, if available.
*/
public Optional<Duration> retry() {
return Optional.ofNullable(this.retry);
public Duration retry() {
return this.retry;
}
/**
* Return the comment of this event, if available.
*/
public Optional<String> comment() {
return Optional.ofNullable(this.comment);
public String comment() {
return this.comment;
}
@Override
public String toString() {
return "ServerSentEvent [id = '" + id + '\'' + ", event='" + event + '\'' +
", data=" + data + ", retry=" + retry + ", comment='" + comment + '\'' +
']';
return ("ServerSentEvent [id = '" + this.id + '\'' + ", event='" + this.event + '\'' +
", data=" + this.data + ", retry=" + this.retry + ", comment='" + this.comment + '\'' + ']');
}
/**
* Return a builder for a {@code SseEvent}.
* @param <T> the type of data that this event contains
* @return the builder
*/
public static <T> Builder<T> builder() {
return new BuilderImpl<>();
}
/**
* Return a builder for a {@code SseEvent}, populated with the give {@linkplain #data() data}.
* @param <T> the type of data that this event contains
* @return the builder
*/
public static <T> Builder<T> builder(T data) {
return new BuilderImpl<>(data);
}
/**
* A mutable builder for a {@code SseEvent}.
*

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,8 +62,9 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
}
/**
* Constructor with JSON {@code Encoder} for encoding objects. Support for
* {@code String} event data is built-in.
* Constructor with JSON {@code Encoder} for encoding objects.
* Support for {@code String} event data is built-in.
* @param encoder the Encoder to use (may be {@code null})
*/
public ServerSentEventHttpMessageWriter(Encoder<?> encoder) {
this.encoder = encoder;
@@ -71,7 +72,7 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
/**
* Return the configured {@code Encoder}, possibly {@code null}.
* Return the configured {@code Encoder}, if any.
*/
public Encoder<?> getEncoder() {
return this.encoder;
@@ -85,8 +86,8 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
@Override
public boolean canWrite(ResolvableType elementType, MediaType mediaType) {
return mediaType == null || MediaType.TEXT_EVENT_STREAM.includes(mediaType) ||
ServerSentEvent.class.isAssignableFrom(elementType.resolve(Object.class));
return (mediaType == null || MediaType.TEXT_EVENT_STREAM.includes(mediaType) ||
ServerSentEvent.class.isAssignableFrom(elementType.resolve(Object.class)));
}
@Override
@@ -100,23 +101,33 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
private Flux<Publisher<DataBuffer>> encode(Publisher<?> input, DataBufferFactory factory,
ResolvableType elementType, Map<String, Object> hints) {
ResolvableType valueType = ServerSentEvent.class.isAssignableFrom(elementType.getRawClass()) ?
elementType.getGeneric(0) : elementType;
ResolvableType valueType = (ServerSentEvent.class.isAssignableFrom(elementType.getRawClass()) ?
elementType.getGeneric() : elementType);
return Flux.from(input).map(element -> {
ServerSentEvent<?> sse = element instanceof ServerSentEvent ?
(ServerSentEvent<?>) element : ServerSentEvent.builder().data(element).build();
ServerSentEvent<?> sse = (element instanceof ServerSentEvent ?
(ServerSentEvent<?>) element : ServerSentEvent.builder().data(element).build());
StringBuilder sb = new StringBuilder();
sse.id().ifPresent(v -> writeField("id", v, sb));
sse.event().ifPresent(v -> writeField("event", v, sb));
sse.retry().ifPresent(v -> writeField("retry", v.toMillis(), sb));
sse.comment().ifPresent(v -> sb.append(':').append(v.replaceAll("\\n", "\n:")).append("\n"));
sse.data().ifPresent(v -> sb.append("data:"));
if (sse.id() != null) {
writeField("id", sse.id(), sb);
}
if (sse.event() != null) {
writeField("event", sse.event(), sb);
}
if (sse.retry() != null) {
writeField("retry", sse.retry().toMillis(), sb);
}
if (sse.comment() != null) {
sb.append(':').append(sse.comment().replaceAll("\\n", "\n:")).append("\n");
}
if (sse.data() != null) {
sb.append("data:");
}
return Flux.concat(encodeText(sb, factory),
encodeData(sse, valueType, factory, hints),
encodeData(sse.data(), valueType, factory, hints),
encodeText("\n", factory));
});
}
@@ -129,10 +140,9 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
}
@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodeData(ServerSentEvent<?> event, ResolvableType valueType,
private <T> Flux<DataBuffer> encodeData(T data, ResolvableType valueType,
DataBufferFactory factory, Map<String, Object> hints) {
Object data = event.data().orElse(null);
if (data == null) {
return Flux.empty();
}
@@ -147,7 +157,7 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
}
return ((Encoder<T>) this.encoder)
.encode(Mono.just((T) data), factory, valueType, MediaType.TEXT_EVENT_STREAM, hints)
.encode(Mono.just(data), factory, valueType, MediaType.TEXT_EVENT_STREAM, hints)
.concatWith(encodeText("\n", factory));
}

View File

@@ -19,7 +19,6 @@ package org.springframework.http.server.reactive;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
import io.netty.handler.codec.http.cookie.Cookie;
import reactor.core.publisher.Flux;
@@ -100,8 +99,8 @@ public class ReactorServerHttpRequest extends AbstractServerHttpRequest {
}
@Override
public Optional<InetSocketAddress> getRemoteAddress() {
return Optional.ofNullable(this.request.remoteAddress());
public InetSocketAddress getRemoteAddress() {
return this.request.remoteAddress();
}
@Override

View File

@@ -42,15 +42,14 @@ import org.springframework.util.Assert;
* @author Rossen Stoyanchev
* @since 5.0
*/
public class ReactorServerHttpResponse extends AbstractServerHttpResponse
implements ZeroCopyHttpOutputMessage {
public class ReactorServerHttpResponse extends AbstractServerHttpResponse implements ZeroCopyHttpOutputMessage {
private final HttpServerResponse response;
public ReactorServerHttpResponse(HttpServerResponse response, DataBufferFactory bufferFactory) {
super(bufferFactory);
Assert.notNull(response, "'response' must not be null.");
Assert.notNull(response, "HttpServerResponse must not be null");
this.response = response;
}
@@ -98,8 +97,12 @@ public class ReactorServerHttpResponse extends AbstractServerHttpResponse
if (!httpCookie.getMaxAge().isNegative()) {
cookie.setMaxAge(httpCookie.getMaxAge().getSeconds());
}
httpCookie.getDomain().ifPresent(cookie::setDomain);
httpCookie.getPath().ifPresent(cookie::setPath);
if (httpCookie.getDomain() != null) {
cookie.setDomain(httpCookie.getDomain());
}
if (httpCookie.getPath() != null) {
cookie.setPath(httpCookie.getPath());
}
cookie.setSecure(httpCookie.isSecure());
cookie.setHttpOnly(httpCookie.isHttpOnly());
this.response.addCookie(cookie);
@@ -116,6 +119,4 @@ public class ReactorServerHttpResponse extends AbstractServerHttpResponse
return Flux.from(dataBuffers).map(NettyDataBufferFactory::toByteBuf);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package org.springframework.http.server.reactive;
import java.net.InetSocketAddress;
import java.util.Optional;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod;
@@ -35,11 +34,10 @@ import org.springframework.util.MultiValueMap;
public interface ServerHttpRequest extends HttpRequest, ReactiveHttpInputMessage {
/**
* Returns the portion of the URL path that represents the context path for
* the current {@link HttpHandler}. The context path is always at the
* beginning of the request path. It starts with "/" but but does not end
* with "/". This method may return an empty string if no context path is
* configured.
* Returns the portion of the URL path that represents the context path for the
* current {@link HttpHandler}. The context path is always at the beginning of
* the request path. It starts with "/" but but does not end with "/".
* <p>This method may return an empty string if no context path is configured.
* @return the context path (not decoded) or an empty string
*/
default String getContextPath() {
@@ -57,10 +55,9 @@ public interface ServerHttpRequest extends HttpRequest, ReactiveHttpInputMessage
MultiValueMap<String, HttpCookie> getCookies();
/**
* Returns the remote address where this request is connected to.
* @return remote address if available
* Return the remote address where this request is connected to, if available.
*/
Optional<InetSocketAddress> getRemoteAddress();
InetSocketAddress getRemoteAddress();
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.server.reactive;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Optional;
import reactor.core.publisher.Flux;
@@ -79,7 +79,7 @@ public class ServerHttpRequestDecorator implements ServerHttpRequest {
}
@Override
public Optional<InetSocketAddress> getRemoteAddress() {
public InetSocketAddress getRemoteAddress() {
return getDelegate().getRemoteAddress();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Map;
import java.util.Optional;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
@@ -32,10 +31,10 @@ import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import reactor.core.publisher.Flux;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpCookie;
@@ -178,9 +177,8 @@ public class ServletServerHttpRequest extends AbstractServerHttpRequest {
}
@Override
public Optional<InetSocketAddress> getRemoteAddress() {
return Optional.of(new InetSocketAddress(
this.request.getRemoteHost(), this.request.getRemotePort()));
public InetSocketAddress getRemoteAddress() {
return new InetSocketAddress(this.request.getRemoteHost(), this.request.getRemotePort());
}
@Override
@@ -231,13 +229,12 @@ public class ServletServerHttpRequest extends AbstractServerHttpRequest {
}
}
private class RequestBodyPublisher extends AbstractListenerReadPublisher<DataBuffer> {
private final ServletInputStream inputStream;
public RequestBodyPublisher(ServletInputStream inputStream) {
this.inputStream = inputStream;
}
@@ -260,6 +257,7 @@ public class ServletServerHttpRequest extends AbstractServerHttpRequest {
return null;
}
private class RequestBodyPublisherReadListener implements ReadListener {
@Override

View File

@@ -117,8 +117,12 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons
if (!httpCookie.getMaxAge().isNegative()) {
cookie.setMaxAge((int) httpCookie.getMaxAge().getSeconds());
}
httpCookie.getDomain().ifPresent(cookie::setDomain);
httpCookie.getPath().ifPresent(cookie::setPath);
if (httpCookie.getDomain() != null) {
cookie.setDomain(httpCookie.getDomain());
}
if (httpCookie.getPath() != null) {
cookie.setPath(httpCookie.getPath());
}
cookie.setSecure(httpCookie.isSecure());
cookie.setHttpOnly(httpCookie.isHttpOnly());
this.response.addCookie(cookie);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +20,6 @@ import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Optional;
import io.undertow.connector.ByteBufferPool;
import io.undertow.connector.PooledByteBuffer;
@@ -100,8 +99,8 @@ public class UndertowServerHttpRequest extends AbstractServerHttpRequest {
}
@Override
public Optional<InetSocketAddress> getRemoteAddress() {
return Optional.ofNullable(this.exchange.getSourceAddress());
public InetSocketAddress getRemoteAddress() {
return this.exchange.getSourceAddress();
}
@Override

View File

@@ -60,7 +60,7 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon
public UndertowServerHttpResponse(HttpServerExchange exchange, DataBufferFactory bufferFactory) {
super(bufferFactory);
Assert.notNull(exchange, "HttpServerExchange is required");
Assert.notNull(exchange, "HttpServerExchange must not be null");
this.exchange = exchange;
}
@@ -120,8 +120,12 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon
if (!httpCookie.getMaxAge().isNegative()) {
cookie.setMaxAge((int) httpCookie.getMaxAge().getSeconds());
}
httpCookie.getDomain().ifPresent(cookie::setDomain);
httpCookie.getPath().ifPresent(cookie::setPath);
if (httpCookie.getDomain() != null) {
cookie.setDomain(httpCookie.getDomain());
}
if (httpCookie.getPath() != null) {
cookie.setPath(httpCookie.getPath());
}
cookie.setSecure(httpCookie.isSecure());
cookie.setHttpOnly(httpCookie.isHttpOnly());
this.exchange.getResponseCookies().putIfAbsent(name, cookie);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -263,9 +263,8 @@ public class WebExchangeBindException extends ServerWebInputException implements
* Returns diagnostic information about the errors held in this object.
*/
@Override
@SuppressWarnings("OptionalGetWithoutIsPresent")
public String getMessage() {
MethodParameter parameter = getMethodParameter().get();
MethodParameter parameter = getMethodParameter();
StringBuilder sb = new StringBuilder("Validation failed for argument at index ")
.append(parameter.getParameterIndex()).append(" in method: ")
.append(parameter.getMethod().toGenericString())

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,6 @@
package org.springframework.web.server;
import java.util.Optional;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
@@ -61,8 +59,8 @@ public class ServerErrorException extends ResponseStatusException {
/**
* Return the {@code MethodParameter} associated with this error, if any.
*/
public Optional<MethodParameter> getMethodParameter() {
return Optional.ofNullable(this.parameter);
public MethodParameter getMethodParameter() {
return this.parameter;
}
}

View File

@@ -126,12 +126,10 @@ public interface ServerWebExchange {
* status, and adding "ETag" and "Last-Modified" headers when applicable.
* This method works with conditional GET/HEAD requests as well as with
* conditional POST/PUT/DELETE requests.
*
* <p><strong>Note:</strong> The HTTP specification recommends setting both
* ETag and Last-Modified values, but you can also use
* {@code #checkNotModified(String)} or
* {@link #checkNotModified(Instant)}.
*
* @param etag the entity tag that the application determined for the
* underlying resource. This parameter will be padded with quotes (")
* if necessary.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,6 @@
package org.springframework.web.server;
import java.util.Optional;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
@@ -61,8 +59,8 @@ public class ServerWebInputException extends ResponseStatusException {
/**
* Return the {@code MethodParameter} associated with this error, if any.
*/
public Optional<MethodParameter> getMethodParameter() {
return Optional.ofNullable(this.parameter);
public MethodParameter getMethodParameter() {
return this.parameter;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.web.server;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -57,10 +56,11 @@ public class UnsupportedMediaTypeStatusException extends ResponseStatusException
/**
* Return the request Content-Type header if it was parsed successfully.
* Return the request Content-Type header if it was parsed successfully,
* or {@code null} otherwise.
*/
public Optional<MediaType> getContentType() {
return Optional.ofNullable(this.contentType);
public MediaType getContentType() {
return this.contentType;
}
/**