Rossen Stoyanchev
2017-10-20 16:41:40 -04:00
parent 8ad212dae2
commit 1cc5afe24b
197 changed files with 1688 additions and 994 deletions

View File

@@ -236,7 +236,9 @@ public class MappingJackson2MessageConverter extends AbstractMessageConverter {
@Override
@Nullable
protected Object convertToInternal(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
protected Object convertToInternal(Object payload, @Nullable MessageHeaders headers,
@Nullable Object conversionHint) {
try {
Class<?> view = getSerializationView(conversionHint);
if (byte[].class == getSerializedPayloadClass()) {

View File

@@ -166,7 +166,9 @@ public class MarshallingMessageConverter extends AbstractMessageConverter {
@Override
@Nullable
protected Object convertToInternal(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
protected Object convertToInternal(Object payload, @Nullable MessageHeaders headers,
@Nullable Object conversionHint) {
Assert.notNull(this.marshaller, "Property 'marshaller' is required");
try {
if (byte[].class == getSerializedPayloadClass()) {

View File

@@ -122,12 +122,16 @@ public abstract class AbstractMessageSendingTemplate<D> implements MessageSendin
}
@Override
public void convertAndSend(D destination, Object payload, @Nullable Map<String, Object> headers) throws MessagingException {
public void convertAndSend(D destination, Object payload, @Nullable Map<String, Object> headers)
throws MessagingException {
convertAndSend(destination, payload, headers, null);
}
@Override
public void convertAndSend(Object payload, @Nullable MessagePostProcessor postProcessor) throws MessagingException {
public void convertAndSend(Object payload, @Nullable MessagePostProcessor postProcessor)
throws MessagingException {
convertAndSend(getRequiredDefaultDestination(), payload, postProcessor);
}

View File

@@ -104,7 +104,7 @@ public interface MessageSendingOperations<D> {
* @param headers headers for the message to send
* @param postProcessor the post processor to apply to the message
*/
void convertAndSend(D destination, Object payload, @Nullable Map<String, Object> headers, @Nullable MessagePostProcessor postProcessor)
throws MessagingException;
void convertAndSend(D destination, Object payload, @Nullable Map<String, Object> headers,
@Nullable MessagePostProcessor postProcessor) throws MessagingException;
}

View File

@@ -39,7 +39,8 @@ import org.springframework.util.StringUtils;
* @author Rossen Stoyanchev
* @since 4.0
*/
public class DestinationPatternsMessageCondition extends AbstractMessageCondition<DestinationPatternsMessageCondition> {
public class DestinationPatternsMessageCondition
extends AbstractMessageCondition<DestinationPatternsMessageCondition> {
public static final String LOOKUP_DESTINATION_HEADER = "lookupDestination";

View File

@@ -76,7 +76,9 @@ public abstract class AbstractNamedValueMethodArgumentResolver implements Handle
* and {@code #{...}} SpEL expressions in default values, or {@code null} if default
* values are not expected to contain expressions
*/
protected AbstractNamedValueMethodArgumentResolver(ConversionService cs, @Nullable ConfigurableBeanFactory beanFactory) {
protected AbstractNamedValueMethodArgumentResolver(ConversionService cs,
@Nullable ConfigurableBeanFactory beanFactory) {
this.conversionService = (cs != null ? cs : DefaultConversionService.getSharedInstance());
this.configurableBeanFactory = beanFactory;
this.expressionContext = (beanFactory != null ? new BeanExpressionContext(beanFactory, null) : null);

View File

@@ -55,7 +55,8 @@ import org.springframework.validation.Validator;
* @see #setValidator
* @see #setCustomArgumentResolvers
*/
public class DefaultMessageHandlerMethodFactory implements MessageHandlerMethodFactory, BeanFactoryAware, InitializingBean {
public class DefaultMessageHandlerMethodFactory
implements MessageHandlerMethodFactory, BeanFactoryAware, InitializingBean {
private ConversionService conversionService = new DefaultFormattingConversionService();

View File

@@ -68,7 +68,9 @@ public class HandlerMethodArgumentResolverComposite implements HandlerMethodArgu
/**
* Add the given {@link HandlerMethodArgumentResolver}s.
*/
public HandlerMethodArgumentResolverComposite addResolvers(@Nullable List<? extends HandlerMethodArgumentResolver> argumentResolvers) {
public HandlerMethodArgumentResolverComposite addResolvers(
@Nullable List<? extends HandlerMethodArgumentResolver> argumentResolvers) {
if (argumentResolvers != null) {
for (HandlerMethodArgumentResolver resolver : argumentResolvers) {
this.argumentResolvers.add(resolver);

View File

@@ -43,7 +43,8 @@ public class SimpAttributes {
public static final String SESSION_COMPLETED_NAME = SimpAttributes.class.getName() + ".COMPLETED";
/** Prefix for the name of session attributes used to store destruction callbacks. */
public static final String DESTRUCTION_CALLBACK_NAME_PREFIX = SimpAttributes.class.getName() + ".DESTRUCTION_CALLBACK.";
public static final String DESTRUCTION_CALLBACK_NAME_PREFIX =
SimpAttributes.class.getName() + ".DESTRUCTION_CALLBACK.";
private static final Log logger = LogFactory.getLog(SimpAttributes.class);

View File

@@ -88,7 +88,9 @@ public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
* A constructor for creating new message headers.
* This constructor is protected. See factory methods in this and sub-classes.
*/
protected SimpMessageHeaderAccessor(SimpMessageType messageType, @Nullable Map<String, List<String>> externalSourceHeaders) {
protected SimpMessageHeaderAccessor(SimpMessageType messageType,
@Nullable Map<String, List<String>> externalSourceHeaders) {
super(externalSourceHeaders);
Assert.notNull(messageType, "MessageType must not be null");
setHeader(MESSAGE_TYPE_HEADER, messageType);

View File

@@ -231,7 +231,7 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate<String
/**
* Creates a new map and puts the given headers under the key
* {@link org.springframework.messaging.support.NativeMessageHeaderAccessor#NATIVE_HEADERS NATIVE_HEADERS NATIVE_HEADERS NATIVE_HEADERS}.
* {@link NativeMessageHeaderAccessor#NATIVE_HEADERS NATIVE_HEADERS NATIVE_HEADERS NATIVE_HEADERS}.
* effectively treats the input header map as headers to be sent out to the
* destination.
* <p>However if the given headers already contain the key

View File

@@ -433,7 +433,9 @@ public class DefaultSubscriptionRegistry extends AbstractSubscriptionRegistry {
@Nullable
public Subscription getSubscription(String subscriptionId) {
for (Map.Entry<String, Set<DefaultSubscriptionRegistry.Subscription>> destinationEntry : this.destinationLookup.entrySet()) {
for (Map.Entry<String, Set<DefaultSubscriptionRegistry.Subscription>> destinationEntry :
this.destinationLookup.entrySet()) {
Set<Subscription> subs = destinationEntry.getValue();
if (subs != null) {
for (Subscription sub : subs) {

View File

@@ -106,7 +106,9 @@ public class StompDecoder {
* @return the decoded messages, or an empty list if none
* @throws StompConversionException raised in case of decoding issues
*/
public List<Message<byte[]>> decode(ByteBuffer byteBuffer, @Nullable MultiValueMap<String, String> partialMessageHeaders) {
public List<Message<byte[]>> decode(ByteBuffer byteBuffer,
@Nullable MultiValueMap<String, String> partialMessageHeaders) {
List<Message<byte[]>> messages = new ArrayList<>();
while (byteBuffer.hasRemaining()) {
Message<byte[]> message = decodeMessage(byteBuffer, partialMessageHeaders);

View File

@@ -179,7 +179,9 @@ public abstract class AbstractMessageChannel implements MessageChannel, Intercep
}
}
public void triggerAfterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, @Nullable Exception ex) {
public void triggerAfterSendCompletion(Message<?> message, MessageChannel channel,
boolean sent, @Nullable Exception ex) {
for (int i = this.sendInterceptorIndex; i >= 0; i--) {
ChannelInterceptor interceptor = interceptors.get(i);
try {

View File

@@ -47,8 +47,10 @@ public class MappingJackson2MessageConverterTests {
@Test
public void defaultConstructor() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
assertThat(converter.getSupportedMimeTypes(), contains(new MimeType("application", "json", StandardCharsets.UTF_8)));
assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
assertThat(converter.getSupportedMimeTypes(),
contains(new MimeType("application", "json", StandardCharsets.UTF_8)));
assertFalse(converter.getObjectMapper().getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
@Test // SPR-12724
@@ -56,7 +58,8 @@ public class MappingJackson2MessageConverterTests {
MimeType mimetype = new MimeType("application", "xml", StandardCharsets.UTF_8);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(mimetype);
assertThat(converter.getSupportedMimeTypes(), contains(mimetype));
assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
assertFalse(converter.getObjectMapper().getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
@Test // SPR-12724
@@ -65,13 +68,20 @@ public class MappingJackson2MessageConverterTests {
MimeType xmlMimetype = new MimeType("application", "xml", StandardCharsets.UTF_8);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(jsonMimetype, xmlMimetype);
assertThat(converter.getSupportedMimeTypes(), contains(jsonMimetype, xmlMimetype));
assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
assertFalse(converter.getObjectMapper().getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
@Test
public void fromMessage() throws Exception {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
String payload = "{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}";
String payload = "{" +
"\"bytes\":\"AQI=\"," +
"\"array\":[\"Foo\",\"Bar\"]," +
"\"number\":42," +
"\"string\":\"Foo\"," +
"\"bool\":true," +
"\"fraction\":42.0}";
Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build();
MyBean actual = (MyBean) converter.fromMessage(message, MyBean.class);

View File

@@ -157,12 +157,16 @@ public class MessageConverterTests {
}
@Override
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) {
protected Object convertFromInternal(Message<?> message, Class<?> targetClass,
@Nullable Object conversionHint) {
return "success-from";
}
@Override
protected Object convertToInternal(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
protected Object convertToInternal(Object payload, @Nullable MessageHeaders headers,
@Nullable Object conversionHint) {
return "success-to";
}
}

View File

@@ -32,25 +32,25 @@ public class CachingDestinationResolverTests {
@Test
public void cachedDestination() {
@SuppressWarnings("unchecked")
DestinationResolver<String> destinationResolver = mock(DestinationResolver.class);
CachingDestinationResolverProxy<String> cachingDestinationResolver = new CachingDestinationResolverProxy<>(destinationResolver);
DestinationResolver<String> resolver = mock(DestinationResolver.class);
CachingDestinationResolverProxy<String> resolverProxy = new CachingDestinationResolverProxy<>(resolver);
given(destinationResolver.resolveDestination("abcd")).willReturn("dcba");
given(destinationResolver.resolveDestination("1234")).willReturn("4321");
given(resolver.resolveDestination("abcd")).willReturn("dcba");
given(resolver.resolveDestination("1234")).willReturn("4321");
assertEquals("dcba", cachingDestinationResolver.resolveDestination("abcd"));
assertEquals("4321", cachingDestinationResolver.resolveDestination("1234"));
assertEquals("4321", cachingDestinationResolver.resolveDestination("1234"));
assertEquals("dcba", cachingDestinationResolver.resolveDestination("abcd"));
assertEquals("dcba", resolverProxy.resolveDestination("abcd"));
assertEquals("4321", resolverProxy.resolveDestination("1234"));
assertEquals("4321", resolverProxy.resolveDestination("1234"));
assertEquals("dcba", resolverProxy.resolveDestination("abcd"));
verify(destinationResolver, times(1)).resolveDestination("abcd");
verify(destinationResolver, times(1)).resolveDestination("1234");
verify(resolver, times(1)).resolveDestination("abcd");
verify(resolver, times(1)).resolveDestination("1234");
}
@Test(expected = IllegalArgumentException.class)
public void noTargetSet() {
CachingDestinationResolverProxy<String> cachingDestinationResolver = new CachingDestinationResolverProxy<>();
cachingDestinationResolver.afterPropertiesSet();
CachingDestinationResolverProxy<String> resolverProxy = new CachingDestinationResolverProxy<>();
resolverProxy.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)

View File

@@ -37,56 +37,53 @@ import static org.junit.Assert.*;
*/
public class AnnotationExceptionHandlerMethodResolverTests {
private final AnnotationExceptionHandlerMethodResolver resolver =
new AnnotationExceptionHandlerMethodResolver(ExceptionController.class);
@Test
public void resolveMethodFromAnnotation() {
AnnotationExceptionHandlerMethodResolver resolver = new AnnotationExceptionHandlerMethodResolver(ExceptionController.class);
IOException exception = new IOException();
assertEquals("handleIOException", resolver.resolveMethod(exception).getName());
assertEquals("handleIOException", this.resolver.resolveMethod(exception).getName());
}
@Test
public void resolveMethodFromArgument() {
AnnotationExceptionHandlerMethodResolver resolver = new AnnotationExceptionHandlerMethodResolver(ExceptionController.class);
IllegalArgumentException exception = new IllegalArgumentException();
assertEquals("handleIllegalArgumentException", resolver.resolveMethod(exception).getName());
assertEquals("handleIllegalArgumentException", this.resolver.resolveMethod(exception).getName());
}
@Test
public void resolveMethodFromArgumentWithErrorType() {
AnnotationExceptionHandlerMethodResolver resolver = new AnnotationExceptionHandlerMethodResolver(ExceptionController.class);
AssertionError exception = new AssertionError();
assertEquals("handleAssertionError", resolver.resolveMethod(new IllegalStateException(exception)).getName());
assertEquals("handleAssertionError", this.resolver.resolveMethod(new IllegalStateException(exception)).getName());
}
@Test
public void resolveMethodExceptionSubType() {
AnnotationExceptionHandlerMethodResolver resolver = new AnnotationExceptionHandlerMethodResolver(ExceptionController.class);
IOException ioException = new FileNotFoundException();
assertEquals("handleIOException", resolver.resolveMethod(ioException).getName());
assertEquals("handleIOException", this.resolver.resolveMethod(ioException).getName());
SocketException bindException = new BindException();
assertEquals("handleSocketException", resolver.resolveMethod(bindException).getName());
assertEquals("handleSocketException", this.resolver.resolveMethod(bindException).getName());
}
@Test
public void resolveMethodBestMatch() {
AnnotationExceptionHandlerMethodResolver resolver = new AnnotationExceptionHandlerMethodResolver(ExceptionController.class);
SocketException exception = new SocketException();
assertEquals("handleSocketException", resolver.resolveMethod(exception).getName());
assertEquals("handleSocketException", this.resolver.resolveMethod(exception).getName());
}
@Test
public void resolveMethodNoMatch() {
AnnotationExceptionHandlerMethodResolver resolver = new AnnotationExceptionHandlerMethodResolver(ExceptionController.class);
Exception exception = new Exception();
assertNull("1st lookup", resolver.resolveMethod(exception));
assertNull("2nd lookup from cache", resolver.resolveMethod(exception));
assertNull("1st lookup", this.resolver.resolveMethod(exception));
assertNull("2nd lookup from cache", this.resolver.resolveMethod(exception));
}
@Test
public void resolveMethodInherited() {
AnnotationExceptionHandlerMethodResolver resolver = new AnnotationExceptionHandlerMethodResolver(InheritedController.class);
IOException exception = new IOException();
assertEquals("handleIOException", resolver.resolveMethod(exception).getName());
assertEquals("handleIOException", this.resolver.resolveMethod(exception).getName());
}
@Test(expected = IllegalStateException.class)
@@ -101,6 +98,7 @@ public class AnnotationExceptionHandlerMethodResolverTests {
@Controller
@SuppressWarnings("unused")
static class ExceptionController {
public void handle() {}

View File

@@ -32,14 +32,17 @@ public class SimpMessageTypeMessageConditionTests {
@Test
public void combine() {
SimpMessageType actual = condition(SimpMessageType.MESSAGE).combine(condition(SimpMessageType.SUBSCRIBE)).getMessageType();
assertEquals(SimpMessageType.SUBSCRIBE, actual);
SimpMessageType messageType = SimpMessageType.MESSAGE;
SimpMessageType subscribeType = SimpMessageType.SUBSCRIBE;
actual = condition(SimpMessageType.MESSAGE).combine(condition(SimpMessageType.MESSAGE)).getMessageType();
assertEquals(SimpMessageType.MESSAGE, actual);
SimpMessageType actual = condition(messageType).combine(condition(subscribeType)).getMessageType();
assertEquals(subscribeType, actual);
actual = condition(SimpMessageType.SUBSCRIBE).combine(condition(SimpMessageType.SUBSCRIBE)).getMessageType();
assertEquals(SimpMessageType.SUBSCRIBE, actual);
actual = condition(messageType).combine(condition(messageType)).getMessageType();
assertEquals(messageType, actual);
actual = condition(subscribeType).combine(condition(subscribeType)).getMessageType();
assertEquals(subscribeType, actual);
}
@Test

View File

@@ -67,6 +67,7 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.PathMatcher;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean;
@@ -132,7 +133,8 @@ public class MessageBrokerConfigurationTests {
@Test
public void clientOutboundChannelUsedByAnnotatedMethod() {
TestChannel channel = this.simpleBrokerContext.getBean("clientOutboundChannel", TestChannel.class);
SimpAnnotationMethodMessageHandler messageHandler = this.simpleBrokerContext.getBean(SimpAnnotationMethodMessageHandler.class);
SimpAnnotationMethodMessageHandler messageHandler =
this.simpleBrokerContext.getBean(SimpAnnotationMethodMessageHandler.class);
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
headers.setSessionId("sess1");
@@ -327,7 +329,8 @@ public class MessageBrokerConfigurationTests {
@Test
public void customArgumentAndReturnValueTypes() throws Exception {
SimpAnnotationMethodMessageHandler handler = this.customContext.getBean(SimpAnnotationMethodMessageHandler.class);
SimpAnnotationMethodMessageHandler handler =
this.customContext.getBean(SimpAnnotationMethodMessageHandler.class);
List<HandlerMethodArgumentResolver> customResolvers = handler.getCustomArgumentResolvers();
assertEquals(1, customResolvers.size());
@@ -385,8 +388,10 @@ public class MessageBrokerConfigurationTests {
DefaultSubscriptionRegistry registry = (DefaultSubscriptionRegistry) broker.getSubscriptionRegistry();
assertEquals("a.a", registry.getPathMatcher().combine("a", "a"));
SimpAnnotationMethodMessageHandler handler = this.customContext.getBean(SimpAnnotationMethodMessageHandler.class);
assertEquals("a.a", handler.getPathMatcher().combine("a", "a"));
PathMatcher pathMatcher =
this.customContext.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher();
assertEquals("a.a", pathMatcher.combine("a", "a"));
DefaultUserDestinationResolver resolver = this.customContext.getBean(DefaultUserDestinationResolver.class);
assertNotNull(resolver);
@@ -536,7 +541,8 @@ public class MessageBrokerConfigurationTests {
@Override
protected void configureMessageBroker(MessageBrokerRegistry registry) {
registry.configureBrokerChannel().interceptors(this.interceptor, this.interceptor, this.interceptor);
registry.configureBrokerChannel().taskExecutor().corePoolSize(31).maxPoolSize(32).keepAliveSeconds(33).queueCapacity(34);
registry.configureBrokerChannel().taskExecutor()
.corePoolSize(31).maxPoolSize(32).keepAliveSeconds(33).queueCapacity(34);
registry.setPathMatcher(new AntPathMatcher(".")).enableSimpleBroker("/topic", "/queue");
registry.setCacheLimit(8192);
}

View File

@@ -217,7 +217,8 @@ public class DefaultStompSessionTests {
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(this.sessionHandler.getPayloadType(stompHeaders)).thenReturn(String.class);
this.session.handleMessage(MessageBuilder.createMessage(payload.getBytes(StandardCharsets.UTF_8), accessor.getMessageHeaders()));
this.session.handleMessage(MessageBuilder.createMessage(
payload.getBytes(StandardCharsets.UTF_8), accessor.getMessageHeaders()));
verify(this.sessionHandler).getPayloadType(stompHeaders);
verify(this.sessionHandler).handleFrame(stompHeaders, payload);

View File

@@ -49,7 +49,9 @@ import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.Assert;
import org.springframework.util.SocketUtils;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Integration tests for {@link StompBrokerRelayMessageHandler} running against ActiveMQ.
@@ -509,7 +511,9 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
@Override
protected boolean matchInternal(StompHeaderAccessor headers, Object payload) {
if (!this.subscriptionId.equals(headers.getSubscriptionId()) || !this.destination.equals(headers.getDestination())) {
if (!this.subscriptionId.equals(headers.getSubscriptionId()) ||
!this.destination.equals(headers.getDestination())) {
return false;
}
if (payload instanceof byte[] && this.payload instanceof byte[]) {

View File

@@ -31,8 +31,15 @@ import org.springframework.messaging.MessageHeaders;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.SerializationTestUtils;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Test fixture for {@link MessageHeaderAccessor}.
@@ -314,9 +321,10 @@ public class MessageHeaderAccessorTests {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setContentType(MimeTypeUtils.TEXT_PLAIN);
assertEquals("headers={contentType=text/plain} payload=p", accessor.getShortLogMessage("p"));
assertEquals("headers={contentType=text/plain} payload=p", accessor.getShortLogMessage("p".getBytes(StandardCharsets.UTF_8)));
assertEquals("headers={contentType=text/plain} payload=p", accessor.getShortLogMessage(new Object() {
String expected = "headers={contentType=text/plain} payload=p";
assertEquals(expected, accessor.getShortLogMessage("p"));
assertEquals(expected, accessor.getShortLogMessage("p".getBytes(StandardCharsets.UTF_8)));
assertEquals(expected, accessor.getShortLogMessage(new Object() {
@Override
public String toString() {
return "p";
@@ -349,9 +357,10 @@ public class MessageHeaderAccessorTests {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setContentType(MimeTypeUtils.TEXT_PLAIN);
assertEquals("headers={contentType=text/plain} payload=p", accessor.getDetailedLogMessage("p"));
assertEquals("headers={contentType=text/plain} payload=p", accessor.getDetailedLogMessage("p".getBytes(StandardCharsets.UTF_8)));
assertEquals("headers={contentType=text/plain} payload=p", accessor.getDetailedLogMessage(new Object() {
String expected = "headers={contentType=text/plain} payload=p";
assertEquals(expected, accessor.getDetailedLogMessage("p"));
assertEquals(expected, accessor.getDetailedLogMessage("p".getBytes(StandardCharsets.UTF_8)));
assertEquals(expected, accessor.getDetailedLogMessage(new Object() {
@Override
public String toString() {
return "p";

View File

@@ -216,36 +216,42 @@ public enum HttpStatus {
CONFLICT(409, "Conflict"),
/**
* {@code 410 Gone}.
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.9">HTTP/1.1: Semantics and Content, section 6.5.9</a>
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.9">
* HTTP/1.1: Semantics and Content, section 6.5.9</a>
*/
GONE(410, "Gone"),
/**
* {@code 411 Length Required}.
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.10">HTTP/1.1: Semantics and Content, section 6.5.10</a>
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.10">
* HTTP/1.1: Semantics and Content, section 6.5.10</a>
*/
LENGTH_REQUIRED(411, "Length Required"),
/**
* {@code 412 Precondition failed}.
* @see <a href="http://tools.ietf.org/html/rfc7232#section-4.2">HTTP/1.1: Conditional Requests, section 4.2</a>
* @see <a href="http://tools.ietf.org/html/rfc7232#section-4.2">
* HTTP/1.1: Conditional Requests, section 4.2</a>
*/
PRECONDITION_FAILED(412, "Precondition Failed"),
/**
* {@code 413 Payload Too Large}.
* @since 4.1
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.11">HTTP/1.1: Semantics and Content, section 6.5.11</a>
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.11">
* HTTP/1.1: Semantics and Content, section 6.5.11</a>
*/
PAYLOAD_TOO_LARGE(413, "Payload Too Large"),
/**
* {@code 413 Request Entity Too Large}.
* @see <a href="http://tools.ietf.org/html/rfc2616#section-10.4.14">HTTP/1.1, section 10.4.14</a>
* @deprecated in favor of {@link #PAYLOAD_TOO_LARGE} which will be returned from {@code HttpStatus.valueOf(413)}
* @deprecated in favor of {@link #PAYLOAD_TOO_LARGE} which will be
* returned from {@code HttpStatus.valueOf(413)}
*/
@Deprecated
REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
/**
* {@code 414 URI Too Long}.
* @since 4.1
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.12">HTTP/1.1: Semantics and Content, section 6.5.12</a>
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.12">
* HTTP/1.1: Semantics and Content, section 6.5.12</a>
*/
URI_TOO_LONG(414, "URI Too Long"),
/**
@@ -257,7 +263,8 @@ public enum HttpStatus {
REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"),
/**
* {@code 415 Unsupported Media Type}.
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.13">HTTP/1.1: Semantics and Content, section 6.5.13</a>
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.13">
* HTTP/1.1: Semantics and Content, section 6.5.13</a>
*/
UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
/**
@@ -267,7 +274,8 @@ public enum HttpStatus {
REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested range not satisfiable"),
/**
* {@code 417 Expectation Failed}.
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.14">HTTP/1.1: Semantics and Content, section 6.5.14</a>
* @see <a href="http://tools.ietf.org/html/rfc7231#section-6.5.14">
* HTTP/1.1: Semantics and Content, section 6.5.14</a>
*/
EXPECTATION_FAILED(417, "Expectation Failed"),
/**
@@ -276,17 +284,23 @@ public enum HttpStatus {
*/
I_AM_A_TEAPOT(418, "I'm a teapot"),
/**
* @deprecated See <a href="http://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt">WebDAV Draft Changes</a>
* @deprecated See
* <a href="http://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt">
* WebDAV Draft Changes</a>
*/
@Deprecated
INSUFFICIENT_SPACE_ON_RESOURCE(419, "Insufficient Space On Resource"),
/**
* @deprecated See <a href="http://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt">WebDAV Draft Changes</a>
* @deprecated See
* <a href="http://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt">
* WebDAV Draft Changes</a>
*/
@Deprecated
METHOD_FAILURE(420, "Method Failure"),
/**
* @deprecated See <a href="http://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt">WebDAV Draft Changes</a>
* @deprecated
* See <a href="http://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt">
* WebDAV Draft Changes</a>
*/
@Deprecated
DESTINATION_LOCKED(421, "Destination Locked"),

View File

@@ -45,7 +45,8 @@ import org.springframework.util.StringUtils;
* @author Sebastien Deleuze
* @author Kazuki Shimizu
* @since 3.0
* @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.1.1">HTTP 1.1: Semantics and Content, section 3.1.1.1</a>
* @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.1.1">
* HTTP 1.1: Semantics and Content, section 3.1.1.1</a>
*/
public class MediaType extends MimeType implements Serializable {
@@ -699,7 +700,8 @@ public class MediaType extends MimeType implements Serializable {
else {
int paramsSize1 = mediaType1.getParameters().size();
int paramsSize2 = mediaType2.getParameters().size();
return (paramsSize2 < paramsSize1 ? -1 : (paramsSize2 == paramsSize1 ? 0 : 1)); // audio/basic;level=1 < audio/basic
// audio/basic;level=1 < audio/basic
return (paramsSize2 < paramsSize1 ? -1 : (paramsSize2 == paramsSize1 ? 0 : 1));
}
}
};

View File

@@ -33,7 +33,10 @@ import org.springframework.util.ObjectUtils;
* {@link org.springframework.web.client.RestTemplate#exchange(RequestEntity, Class) exchange()}:
* <pre class="code">
* MyRequest body = ...
* RequestEntity&lt;MyRequest&gt; request = RequestEntity.post(new URI(&quot;http://example.com/bar&quot;)).accept(MediaType.APPLICATION_JSON).body(body);
* RequestEntity&lt;MyRequest&gt; request = RequestEntity
* .post(new URI(&quot;http://example.com/bar&quot;))
* .accept(MediaType.APPLICATION_JSON)
* .body(body);
* ResponseEntity&lt;MyResponse&gt; response = template.exchange(request, MyResponse.class);
* </pre>
*

View File

@@ -31,7 +31,8 @@ import org.springframework.util.concurrent.ListenableFuture;
* @author Rossen Stoyanchev
* @since 4.3
* @see AsyncClientHttpRequestInterceptor
* @deprecated as of Spring 5.0, in favor of {@link org.springframework.web.reactive.function.client.ExchangeFilterFunction}
* @deprecated as of Spring 5.0, in favor of
* {@link org.springframework.web.reactive.function.client.ExchangeFilterFunction}
*/
@Deprecated
public interface AsyncClientHttpRequestExecution {

View File

@@ -36,7 +36,8 @@ import org.springframework.util.concurrent.ListenableFuture;
* @since 4.3
* @see org.springframework.web.client.AsyncRestTemplate
* @see org.springframework.http.client.support.InterceptingAsyncHttpAccessor
* @deprecated as of Spring 5.0, in favor of {@link org.springframework.web.reactive.function.client.ExchangeFilterFunction}
* @deprecated as of Spring 5.0, in favor of
* {@link org.springframework.web.reactive.function.client.ExchangeFilterFunction}
*/
@Deprecated
public interface AsyncClientHttpRequestInterceptor {

View File

@@ -21,12 +21,14 @@ import java.io.IOException;
import org.springframework.http.HttpRequest;
/**
* Intercepts client-side HTTP requests. Implementations of this interface can be {@linkplain
* org.springframework.web.client.RestTemplate#setInterceptors(java.util.List) registered} with the
* {@link org.springframework.web.client.RestTemplate RestTemplate}, as to modify the outgoing {@link ClientHttpRequest}
* and/or the incoming {@link ClientHttpResponse}.
* Intercepts client-side HTTP requests. Implementations of this interface can be
* {@linkplain org.springframework.web.client.RestTemplate#setInterceptors(java.util.List)
* registered} with the {@link org.springframework.web.client.RestTemplate RestTemplate},
* as to modify the outgoing {@link ClientHttpRequest} and/or the incoming
* {@link ClientHttpResponse}.
*
* <p>The main entry point for interceptors is {@link #intercept(HttpRequest, byte[], ClientHttpRequestExecution)}.
* <p>The main entry point for interceptors is
* {@link #intercept(HttpRequest, byte[], ClientHttpRequestExecution)}.
*
* @author Arjen Poutsma
* @since 3.1
@@ -35,17 +37,20 @@ import org.springframework.http.HttpRequest;
public interface ClientHttpRequestInterceptor {
/**
* Intercept the given request, and return a response. The given {@link ClientHttpRequestExecution} allows
* the interceptor to pass on the request and response to the next entity in the chain.
* Intercept the given request, and return a response. The given
* {@link ClientHttpRequestExecution} allows the interceptor to pass on the
* request and response to the next entity in the chain.
*
* <p>A typical implementation of this method would follow the following pattern:
* <ol>
* <li>Examine the {@linkplain HttpRequest request} and body</li>
* <li>Optionally {@linkplain org.springframework.http.client.support.HttpRequestWrapper wrap} the request to filter HTTP attributes.</li>
* <li>Optionally {@linkplain org.springframework.http.client.support.HttpRequestWrapper
* wrap} the request to filter HTTP attributes.</li>
* <li>Optionally modify the body of the request.</li>
* <li><strong>Either</strong>
* <ul>
* <li>execute the request using {@link ClientHttpRequestExecution#execute(org.springframework.http.HttpRequest, byte[])},</li>
* <li>execute the request using
* {@link ClientHttpRequestExecution#execute(org.springframework.http.HttpRequest, byte[])},</li>
* <strong>or</strong>
* <li>do not execute the request to block the execution altogether.</li>
* </ul>

View File

@@ -160,7 +160,9 @@ final class HttpComponentsAsyncClientHttpRequest extends AbstractBufferingAsyncC
}
@Override
public void addCallback(SuccessCallback<? super ClientHttpResponse> successCallback, FailureCallback failureCallback) {
public void addCallback(SuccessCallback<? super ClientHttpResponse> successCallback,
FailureCallback failureCallback) {
this.callback.addSuccessCallback(successCallback);
this.callback.addFailureCallback(failureCallback);
}

View File

@@ -50,7 +50,8 @@ import org.springframework.util.concurrent.SettableListenableFuture;
* @author Rossen Stoyanchev
* @author Brian Clozel
* @since 4.1.2
* @deprecated as of Spring 5.0, in favor of {@link org.springframework.http.client.reactive.ReactorClientHttpConnector}
* @deprecated as of Spring 5.0, in favor of
* {@link org.springframework.http.client.reactive.ReactorClientHttpConnector}
*/
@Deprecated
class Netty4ClientHttpRequest extends AbstractAsyncClientHttpRequest implements ClientHttpRequest {

View File

@@ -57,7 +57,8 @@ import org.springframework.util.Assert;
* @author Brian Clozel
* @author Mark Paluch
* @since 4.1.2
* @deprecated as of Spring 5.0, in favor of {@link org.springframework.http.client.reactive.ReactorClientHttpConnector}
* @deprecated as of Spring 5.0, in favor of
* {@link org.springframework.http.client.reactive.ReactorClientHttpConnector}
*/
@Deprecated
public class Netty4ClientHttpRequestFactory implements ClientHttpRequestFactory,

View File

@@ -33,7 +33,8 @@ import org.springframework.util.Assert;
*
* @author Arjen Poutsma
* @since 4.1.2
* @deprecated as of Spring 5.0, in favor of {@link org.springframework.http.client.reactive.ReactorClientHttpConnector}
* @deprecated as of Spring 5.0, in favor of
* {@link org.springframework.http.client.reactive.ReactorClientHttpConnector}
*/
@Deprecated
class Netty4ClientHttpResponse extends AbstractClientHttpResponse {

View File

@@ -54,7 +54,9 @@ public class AsyncHttpAccessor {
* Set the request factory that this accessor uses for obtaining {@link
* org.springframework.http.client.ClientHttpRequest HttpRequests}.
*/
public void setAsyncRequestFactory(org.springframework.http.client.AsyncClientHttpRequestFactory asyncRequestFactory) {
public void setAsyncRequestFactory(
org.springframework.http.client.AsyncClientHttpRequestFactory asyncRequestFactory) {
Assert.notNull(asyncRequestFactory, "AsyncClientHttpRequestFactory must not be null");
this.asyncRequestFactory = asyncRequestFactory;
}

View File

@@ -99,7 +99,7 @@ public abstract class AbstractJackson2Encoder extends Jackson2CodecSupport imple
return Flux.from(inputStream).map(value ->
encodeValue(value, mimeType, bufferFactory, elementType, hints));
}
else if (this.streamingMediaTypes.stream().anyMatch(streamingMediaType -> streamingMediaType.isCompatibleWith(mimeType))) {
else if (this.streamingMediaTypes.stream().anyMatch(mediaType -> mediaType.isCompatibleWith(mimeType))) {
return Flux.from(inputStream).map(value -> {
DataBuffer buffer = encodeValue(value, mimeType, bufferFactory, elementType, hints);
buffer.write(new byte[]{'\n'});

View File

@@ -79,8 +79,8 @@ public abstract class AbstractGenericHttpMessageConverter<T> extends AbstractHtt
* This implementation sets the default headers by calling {@link #addDefaultHeaders},
* and then calls {@link #writeInternal}.
*/
public final void write(final T t, @Nullable final Type type, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
public final void write(final T t, @Nullable final Type type, @Nullable MediaType contentType,
HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
final HttpHeaders headers = outputMessage.getHeaders();
addDefaultHeaders(headers, t, contentType);

View File

@@ -332,7 +332,9 @@ public class FormHttpMessageConverter implements HttpMessageConverter<MultiValue
}
}
private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage) throws IOException {
private void writeMultipart(final MultiValueMap<String, Object> parts,
HttpOutputMessage outputMessage) throws IOException {
final byte[] boundary = generateMultipartBoundary();
Map<String, String> parameters = new HashMap<>(2);
parameters.put("boundary", new String(boundary, "US-ASCII"));

View File

@@ -49,7 +49,8 @@ import org.springframework.util.StringUtils;
* @see AtomFeedHttpMessageConverter
* @see RssChannelHttpMessageConverter
*/
public abstract class AbstractWireFeedHttpMessageConverter<T extends WireFeed> extends AbstractHttpMessageConverter<T> {
public abstract class AbstractWireFeedHttpMessageConverter<T extends WireFeed>
extends AbstractHttpMessageConverter<T> {
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

View File

@@ -76,10 +76,14 @@ import org.springframework.util.xml.StaxUtils;
* <p>It also automatically registers the following well-known modules if they are
* detected on the classpath:
* <ul>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jdk8">jackson-datatype-jdk8</a>: support for other Java 8 types like {@link java.util.Optional}</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jsr310">jackson-datatype-jsr310</a>: support for Java 8 Date & Time API types</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-joda">jackson-datatype-joda</a>: support for Joda-Time types</li>
* <li><a href="https://github.com/FasterXML/jackson-module-kotlin">jackson-module-kotlin</a>: support for Kotlin classes and data classes</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jdk8">jackson-datatype-jdk8</a>:
* support for other Java 8 types like {@link java.util.Optional}</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jsr310">jackson-datatype-jsr310</a>:
* support for Java 8 Date & Time API types</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-joda">jackson-datatype-joda</a>:
* support for Joda-Time types</li>
* <li><a href="https://github.com/FasterXML/jackson-module-kotlin">jackson-module-kotlin</a>:
* support for Kotlin classes and data classes</li>
* </ul>
*
* <p>Compatible with Jackson 2.6 and higher, as of Spring 4.3.
@@ -766,11 +770,13 @@ public class Jackson2ObjectMapperBuilder {
if (KotlinDetector.isKotlinPresent()) {
try {
Class<? extends Module> kotlinModule = (Class<? extends Module>)
ClassUtils.forName("com.fasterxml.jackson.module.kotlin.KotlinModule", this.moduleClassLoader);
ClassUtils.forName("com.fasterxml.jackson.module.kotlin.KotlinModule",
this.moduleClassLoader);
objectMapper.registerModule(BeanUtils.instantiateClass(kotlinModule));
}
catch (ClassNotFoundException ex) {
logger.warn("For Jackson Kotlin classes support please add \"com.fasterxml.jackson.module:jackson-module-kotlin\" to the classpath");
logger.warn("For Jackson Kotlin classes support please add " +
"\"com.fasterxml.jackson.module:jackson-module-kotlin\" to the classpath");
}
}
}

View File

@@ -114,11 +114,16 @@ import org.springframework.lang.Nullable;
* <p>It also automatically registers the following well-known modules if they are
* detected on the classpath:
* <ul>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jdk7">jackson-datatype-jdk7</a>: support for Java 7 types like {@link java.nio.file.Path}</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jdk8">jackson-datatype-jdk8</a>: support for other Java 8 types like {@link java.util.Optional}</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jsr310">jackson-datatype-jsr310</a>: support for Java 8 Date & Time API types</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-joda">jackson-datatype-joda</a>: support for Joda-Time types</li>
* <li><a href="https://github.com/FasterXML/jackson-module-kotlin">jackson-module-kotlin</a>: support for Kotlin classes and data classes</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jdk7">jackson-datatype-jdk7</a>:
* support for Java 7 types like {@link java.nio.file.Path}</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jdk8">jackson-datatype-jdk8</a>:
* support for other Java 8 types like {@link java.util.Optional}</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jsr310">jackson-datatype-jsr310</a>:
* support for Java 8 Date & Time API types</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-joda">jackson-datatype-joda</a>:
* support for Joda-Time types</li>
* <li><a href="https://github.com/FasterXML/jackson-module-kotlin">jackson-module-kotlin</a>:
* support for Kotlin classes and data classes</li>
* </ul>
*
* <p>In case you want to configure Jackson's {@link ObjectMapper} with a custom {@link Module},

View File

@@ -70,22 +70,30 @@ public class SpringHandlerInstantiator extends HandlerInstantiator {
@Override
public JsonDeserializer<?> deserializerInstance(DeserializationConfig config, Annotated annotated, Class<?> implClass) {
public JsonDeserializer<?> deserializerInstance(DeserializationConfig config,
Annotated annotated, Class<?> implClass) {
return (JsonDeserializer<?>) this.beanFactory.createBean(implClass);
}
@Override
public KeyDeserializer keyDeserializerInstance(DeserializationConfig config, Annotated annotated, Class<?> implClass) {
public KeyDeserializer keyDeserializerInstance(DeserializationConfig config,
Annotated annotated, Class<?> implClass) {
return (KeyDeserializer) this.beanFactory.createBean(implClass);
}
@Override
public JsonSerializer<?> serializerInstance(SerializationConfig config, Annotated annotated, Class<?> implClass) {
public JsonSerializer<?> serializerInstance(SerializationConfig config,
Annotated annotated, Class<?> implClass) {
return (JsonSerializer<?>) this.beanFactory.createBean(implClass);
}
@Override
public TypeResolverBuilder<?> typeResolverBuilderInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
public TypeResolverBuilder<?> typeResolverBuilderInstance(MapperConfig<?> config,
Annotated annotated, Class<?> implClass) {
return (TypeResolverBuilder<?>) this.beanFactory.createBean(implClass);
}
@@ -96,31 +104,41 @@ public class SpringHandlerInstantiator extends HandlerInstantiator {
/** @since 4.3 */
@Override
public ValueInstantiator valueInstantiatorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
public ValueInstantiator valueInstantiatorInstance(MapperConfig<?> config,
Annotated annotated, Class<?> implClass) {
return (ValueInstantiator) this.beanFactory.createBean(implClass);
}
/** @since 4.3 */
@Override
public ObjectIdGenerator<?> objectIdGeneratorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
public ObjectIdGenerator<?> objectIdGeneratorInstance(MapperConfig<?> config,
Annotated annotated, Class<?> implClass) {
return (ObjectIdGenerator<?>) this.beanFactory.createBean(implClass);
}
/** @since 4.3 */
@Override
public ObjectIdResolver resolverIdGeneratorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
public ObjectIdResolver resolverIdGeneratorInstance(MapperConfig<?> config,
Annotated annotated, Class<?> implClass) {
return (ObjectIdResolver) this.beanFactory.createBean(implClass);
}
/** @since 4.3 */
@Override
public PropertyNamingStrategy namingStrategyInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
public PropertyNamingStrategy namingStrategyInstance(MapperConfig<?> config,
Annotated annotated, Class<?> implClass) {
return (PropertyNamingStrategy) this.beanFactory.createBean(implClass);
}
/** @since 4.3 */
@Override
public Converter<?, ?> converterInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
public Converter<?, ?> converterInstance(MapperConfig<?> config,
Annotated annotated, Class<?> implClass) {
return (Converter<?, ?>) this.beanFactory.createBean(implClass);
}

View File

@@ -40,20 +40,26 @@ public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConv
ClassUtils.isPresent("javax.xml.bind.Binder", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
private static final boolean jackson2Present =
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader()) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper",
AllEncompassingFormHttpMessageConverter.class.getClassLoader()) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator",
AllEncompassingFormHttpMessageConverter.class.getClassLoader());
private static final boolean jackson2XmlPresent =
ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper",
AllEncompassingFormHttpMessageConverter.class.getClassLoader());
private static final boolean jackson2SmilePresent =
ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory",
AllEncompassingFormHttpMessageConverter.class.getClassLoader());
private static final boolean gsonPresent =
ClassUtils.isPresent("com.google.gson.Gson", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
ClassUtils.isPresent("com.google.gson.Gson",
AllEncompassingFormHttpMessageConverter.class.getClassLoader());
private static final boolean jsonbPresent =
ClassUtils.isPresent("javax.json.bind.Jsonb", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
ClassUtils.isPresent("javax.json.bind.Jsonb",
AllEncompassingFormHttpMessageConverter.class.getClassLoader());
public AllEncompassingFormHttpMessageConverter() {

View File

@@ -50,7 +50,8 @@ public class HttpMediaTypeNotSupportedException extends HttpMediaTypeException {
* @param supportedMediaTypes the list of supported media types
*/
public HttpMediaTypeNotSupportedException(@Nullable MediaType contentType, List<MediaType> supportedMediaTypes) {
this(contentType, supportedMediaTypes, "Content type '" + (contentType != null ? contentType : "") + "' not supported");
this(contentType, supportedMediaTypes, "Content type '" +
(contentType != null ? contentType : "") + "' not supported");
}
/**
@@ -59,7 +60,9 @@ public class HttpMediaTypeNotSupportedException extends HttpMediaTypeException {
* @param supportedMediaTypes the list of supported media types
* @param msg the detail message
*/
public HttpMediaTypeNotSupportedException(@Nullable MediaType contentType, List<MediaType> supportedMediaTypes, String msg) {
public HttpMediaTypeNotSupportedException(@Nullable MediaType contentType,
List<MediaType> supportedMediaTypes, String msg) {
super(msg, supportedMediaTypes);
this.contentType = contentType;
}

View File

@@ -110,7 +110,9 @@ public class EscapedErrors implements Errors {
}
@Override
public void rejectValue(@Nullable String field, String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
public void rejectValue(@Nullable String field, String errorCode, @Nullable Object[] errorArgs,
@Nullable String defaultMessage) {
this.source.rejectValue(field, errorCode, errorArgs, defaultMessage);
}

View File

@@ -19,15 +19,18 @@ package org.springframework.web.client;
import java.io.IOException;
/**
* Callback interface for code that operates on an {@link org.springframework.http.client.AsyncClientHttpRequest}. Allows
* to manipulate the request headers, and write to the request body.
* Callback interface for code that operates on an
* {@link org.springframework.http.client.AsyncClientHttpRequest}. Allows to
* manipulate the request headers, and write to the request body.
*
* <p>Used internally by the {@link AsyncRestTemplate}, but also useful for application code.
* <p>Used internally by the {@link AsyncRestTemplate}, but also useful for
* application code.
*
* @author Arjen Poutsma
* @see org.springframework.web.client.AsyncRestTemplate#execute
* @since 4.0
* @deprecated as of Spring 5.0, in favor of {@link org.springframework.web.reactive.function.client.ExchangeFilterFunction}
* @deprecated as of Spring 5.0, in favor of
* {@link org.springframework.web.reactive.function.client.ExchangeFilterFunction}
*/
@FunctionalInterface
@Deprecated

View File

@@ -347,8 +347,11 @@ public interface AsyncRestOperations {
* The given {@link ParameterizedTypeReference} is used to pass generic type
* information:
* <pre class="code">
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean =
* new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
*
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response =
* template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* </pre>
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
@@ -368,8 +371,11 @@ public interface AsyncRestOperations {
* The given {@link ParameterizedTypeReference} is used to pass generic type
* information:
* <pre class="code">
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean =
* new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
*
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response =
* template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* </pre>
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
@@ -389,8 +395,11 @@ public interface AsyncRestOperations {
* The given {@link ParameterizedTypeReference} is used to pass generic type
* information:
* <pre class="code">
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean =
* new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
*
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response =
* template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* </pre>
* @param url the URL
* @param method the HTTP method (GET, POST, etc)

View File

@@ -67,7 +67,8 @@ import org.springframework.web.util.UriTemplateHandler;
* @deprecated as of Spring 5.0, in favor of {@link org.springframework.web.reactive.function.client.WebClient}
*/
@Deprecated
public class AsyncRestTemplate extends org.springframework.http.client.support.InterceptingAsyncHttpAccessor implements AsyncRestOperations {
public class AsyncRestTemplate extends org.springframework.http.client.support.InterceptingAsyncHttpAccessor
implements AsyncRestOperations {
private final RestTemplate syncTemplate;
@@ -114,8 +115,8 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
* @param asyncRequestFactory the asynchronous request factory
* @param syncRequestFactory the synchronous request factory
*/
public AsyncRestTemplate(
org.springframework.http.client.AsyncClientHttpRequestFactory asyncRequestFactory, ClientHttpRequestFactory syncRequestFactory) {
public AsyncRestTemplate(org.springframework.http.client.AsyncClientHttpRequestFactory asyncRequestFactory,
ClientHttpRequestFactory syncRequestFactory) {
this(asyncRequestFactory, new RestTemplate(syncRequestFactory));
}
@@ -126,7 +127,9 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
* @param requestFactory the asynchronous request factory to use
* @param restTemplate the synchronous template to use
*/
public AsyncRestTemplate(org.springframework.http.client.AsyncClientHttpRequestFactory requestFactory, RestTemplate restTemplate) {
public AsyncRestTemplate(org.springframework.http.client.AsyncClientHttpRequestFactory requestFactory,
RestTemplate restTemplate) {
Assert.notNull(restTemplate, "RestTemplate must not be null");
this.syncTemplate = restTemplate;
setAsyncRequestFactory(requestFactory);
@@ -236,7 +239,9 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public <T> ListenableFuture<ResponseEntity<T>> getForEntity(URI url, Class<T> responseType) throws RestClientException {
public <T> ListenableFuture<ResponseEntity<T>> getForEntity(URI url, Class<T> responseType)
throws RestClientException {
AsyncRequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor);
@@ -246,13 +251,17 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
// HEAD
@Override
public ListenableFuture<HttpHeaders> headForHeaders(String url, Object... uriVariables) throws RestClientException {
public ListenableFuture<HttpHeaders> headForHeaders(String url, Object... uriVariables)
throws RestClientException {
ResponseExtractor<HttpHeaders> headersExtractor = headersExtractor();
return execute(url, HttpMethod.HEAD, null, headersExtractor, uriVariables);
}
@Override
public ListenableFuture<HttpHeaders> headForHeaders(String url, Map<String, ?> uriVariables) throws RestClientException {
public ListenableFuture<HttpHeaders> headForHeaders(String url, Map<String, ?> uriVariables)
throws RestClientException {
ResponseExtractor<HttpHeaders> headersExtractor = headersExtractor();
return execute(url, HttpMethod.HEAD, null, headersExtractor, uriVariables);
}
@@ -287,7 +296,9 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public ListenableFuture<URI> postForLocation(URI url, @Nullable HttpEntity<?> request) throws RestClientException {
public ListenableFuture<URI> postForLocation(URI url, @Nullable HttpEntity<?> request)
throws RestClientException {
AsyncRequestCallback callback = httpEntityCallback(request);
ResponseExtractor<HttpHeaders> extractor = headersExtractor();
ListenableFuture<HttpHeaders> future = execute(url, HttpMethod.POST, callback, extractor);
@@ -323,8 +334,8 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public <T> ListenableFuture<ResponseEntity<T>> postForEntity(URI url, @Nullable HttpEntity<?> request, Class<T> responseType)
throws RestClientException {
public <T> ListenableFuture<ResponseEntity<T>> postForEntity(URI url,
@Nullable HttpEntity<?> request, Class<T> responseType) throws RestClientException {
AsyncRequestCallback requestCallback = httpEntityCallback(request, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
@@ -335,15 +346,19 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
// PUT
@Override
public ListenableFuture<?> put(String url, @Nullable HttpEntity<?> request, Object... uriVariables) throws RestClientException {
public ListenableFuture<?> put(String url, @Nullable HttpEntity<?> request, Object... uriVars)
throws RestClientException {
AsyncRequestCallback requestCallback = httpEntityCallback(request);
return execute(url, HttpMethod.PUT, requestCallback, null, uriVariables);
return execute(url, HttpMethod.PUT, requestCallback, null, uriVars);
}
@Override
public ListenableFuture<?> put(String url, @Nullable HttpEntity<?> request, Map<String, ?> uriVariables) throws RestClientException {
public ListenableFuture<?> put(String url, @Nullable HttpEntity<?> request, Map<String, ?> uriVars)
throws RestClientException {
AsyncRequestCallback requestCallback = httpEntityCallback(request);
return execute(url, HttpMethod.PUT, requestCallback, null, uriVariables);
return execute(url, HttpMethod.PUT, requestCallback, null, uriVars);
}
@Override
@@ -374,14 +389,18 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
// OPTIONS
@Override
public ListenableFuture<Set<HttpMethod>> optionsForAllow(String url, Object... uriVars) throws RestClientException {
public ListenableFuture<Set<HttpMethod>> optionsForAllow(String url, Object... uriVars)
throws RestClientException {
ResponseExtractor<HttpHeaders> extractor = headersExtractor();
ListenableFuture<HttpHeaders> future = execute(url, HttpMethod.OPTIONS, null, extractor, uriVars);
return adaptToAllowHeader(future);
}
@Override
public ListenableFuture<Set<HttpMethod>> optionsForAllow(String url, Map<String, ?> uriVars) throws RestClientException {
public ListenableFuture<Set<HttpMethod>> optionsForAllow(String url, Map<String, ?> uriVars)
throws RestClientException {
ResponseExtractor<HttpHeaders> extractor = headersExtractor();
ListenableFuture<HttpHeaders> future = execute(url, HttpMethod.OPTIONS, null, extractor, uriVars);
return adaptToAllowHeader(future);
@@ -406,8 +425,9 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
// exchange
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
Class<T> responseType, Object... uriVariables) throws RestClientException {
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method,
@Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
throws RestClientException {
AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
@@ -415,8 +435,9 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method,
@Nullable HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException {
AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
@@ -424,8 +445,8 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
Class<T> responseType) throws RestClientException {
public <T> ListenableFuture<ResponseEntity<T>> exchange(URI url, HttpMethod method,
@Nullable HttpEntity<?> requestEntity, Class<T> responseType) throws RestClientException {
AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
@@ -433,8 +454,9 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException {
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method,
@Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
Object... uriVariables) throws RestClientException {
Type type = responseType.getType();
AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, type);
@@ -443,8 +465,9 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method,
@Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
Map<String, ?> uriVariables) throws RestClientException {
Type type = responseType.getType();
AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, type);
@@ -453,8 +476,9 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType) throws RestClientException {
public <T> ListenableFuture<ResponseEntity<T>> exchange(URI url, HttpMethod method,
@Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
throws RestClientException {
Type type = responseType.getType();
AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, type);
@@ -474,15 +498,17 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public <T> ListenableFuture<T> execute(String url, HttpMethod method, @Nullable AsyncRequestCallback requestCallback,
@Nullable ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables) throws RestClientException {
public <T> ListenableFuture<T> execute(String url, HttpMethod method,
@Nullable AsyncRequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor,
Map<String, ?> uriVariables) throws RestClientException {
URI expanded = getUriTemplateHandler().expand(url, uriVariables);
return doExecute(expanded, method, requestCallback, responseExtractor);
}
@Override
public <T> ListenableFuture<T> execute(URI url, HttpMethod method, @Nullable AsyncRequestCallback requestCallback,
public <T> ListenableFuture<T> execute(URI url, HttpMethod method,
@Nullable AsyncRequestCallback requestCallback,
@Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {
return doExecute(url, method, requestCallback, responseExtractor);
@@ -500,7 +526,8 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
* be {@code null})
* @return an arbitrary object, as returned by the {@link ResponseExtractor}
*/
protected <T> ListenableFuture<T> doExecute(URI url, HttpMethod method, @Nullable AsyncRequestCallback requestCallback,
protected <T> ListenableFuture<T> doExecute(URI url, HttpMethod method,
@Nullable AsyncRequestCallback requestCallback,
@Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {
Assert.notNull(url, "'url' must not be null");
@@ -651,7 +678,9 @@ public class AsyncRestTemplate extends org.springframework.http.client.support.I
}
@Override
public void doWithRequest(final org.springframework.http.client.AsyncClientHttpRequest request) throws IOException {
public void doWithRequest(final org.springframework.http.client.AsyncClientHttpRequest request)
throws IOException {
this.adaptee.doWithRequest(new ClientHttpRequest() {
@Override
public ClientHttpResponse execute() throws IOException {

View File

@@ -87,7 +87,8 @@ public interface RestOperations {
* @return the entity
* @since 3.0.2
*/
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables) throws RestClientException;
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables)
throws RestClientException;
/**
* Retrieve a representation by doing a GET on the URI template.
@@ -99,7 +100,8 @@ public interface RestOperations {
* @return the converted object
* @since 3.0.2
*/
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException;
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException;
/**
* Retrieve a representation by doing a GET on the URL .
@@ -170,7 +172,8 @@ public interface RestOperations {
* @see HttpEntity
*/
@Nullable
URI postForLocation(String url, @Nullable Object request, Map<String, ?> uriVariables) throws RestClientException;
URI postForLocation(String url, @Nullable Object request, Map<String, ?> uriVariables)
throws RestClientException;
/**
* Create a new resource by POSTing the given object to the URL, and returns the value of the
@@ -199,8 +202,8 @@ public interface RestOperations {
* @see HttpEntity
*/
@Nullable
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
throws RestClientException;
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
Object... uriVariables) throws RestClientException;
/**
* Create a new resource by POSTing the given object to the URI template,
@@ -216,8 +219,8 @@ public interface RestOperations {
* @see HttpEntity
*/
@Nullable
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException;
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
Map<String, ?> uriVariables) throws RestClientException;
/**
* Create a new resource by POSTing the given object to the URL,
@@ -246,8 +249,8 @@ public interface RestOperations {
* @since 3.0.2
* @see HttpEntity
*/
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
throws RestClientException;
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType,
Object... uriVariables) throws RestClientException;
/**
* Create a new resource by POSTing the given object to the URI template,
@@ -262,8 +265,8 @@ public interface RestOperations {
* @since 3.0.2
* @see HttpEntity
*/
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException;
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType,
Map<String, ?> uriVariables) throws RestClientException;
/**
* Create a new resource by POSTing the given object to the URL,
@@ -276,7 +279,8 @@ public interface RestOperations {
* @since 3.0.2
* @see HttpEntity
*/
<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException;
<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType)
throws RestClientException;
// PUT
@@ -361,8 +365,8 @@ public interface RestOperations {
* @see org.springframework.http.client.OkHttp3ClientHttpRequestFactory
*/
@Nullable
<T> T patchForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException;
<T> T patchForObject(String url, @Nullable Object request, Class<T> responseType,
Map<String, ?> uriVariables) throws RestClientException;
/**
* Update a resource by PATCHing the given object to the URL,
@@ -382,7 +386,8 @@ public interface RestOperations {
* @see org.springframework.http.client.OkHttp3ClientHttpRequestFactory
*/
@Nullable
<T> T patchForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException;
<T> T patchForObject(URI url, @Nullable Object request, Class<T> responseType)
throws RestClientException;
@@ -493,8 +498,11 @@ public interface RestOperations {
* request entity to the request, and returns the response as {@link ResponseEntity}.
* The given {@link ParameterizedTypeReference} is used to pass generic type information:
* <pre class="code">
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean =
* new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
*
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response =
* template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* </pre>
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
@@ -513,8 +521,11 @@ public interface RestOperations {
* request entity to the request, and returns the response as {@link ResponseEntity}.
* The given {@link ParameterizedTypeReference} is used to pass generic type information:
* <pre class="code">
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean =
* new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
*
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response =
* template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* </pre>
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
@@ -533,8 +544,11 @@ public interface RestOperations {
* request entity to the request, and returns the response as {@link ResponseEntity}.
* The given {@link ParameterizedTypeReference} is used to pass generic type information:
* <pre class="code">
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean =
* new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
*
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response =
* template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* </pre>
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
@@ -553,7 +567,10 @@ public interface RestOperations {
* with the static builder methods on {@code RequestEntity}, for instance:
* <pre class="code">
* MyRequest body = ...
* RequestEntity request = RequestEntity.post(new URI(&quot;http://example.com/foo&quot;)).accept(MediaType.APPLICATION_JSON).body(body);
* RequestEntity request = RequestEntity
* .post(new URI(&quot;http://example.com/foo&quot;))
* .accept(MediaType.APPLICATION_JSON)
* .body(body);
* ResponseEntity&lt;MyResponse&gt; response = template.exchange(request, MyResponse.class);
* </pre>
* @param requestEntity the entity to write to the request
@@ -561,7 +578,8 @@ public interface RestOperations {
* @return the response as entity
* @since 4.1
*/
<T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType) throws RestClientException;
<T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType)
throws RestClientException;
/**
* Execute the request specified in the given {@link RequestEntity} and return
@@ -569,8 +587,12 @@ public interface RestOperations {
* {@link ParameterizedTypeReference} is used to pass generic type information:
* <pre class="code">
* MyRequest body = ...
* RequestEntity request = RequestEntity.post(new URI(&quot;http://example.com/foo&quot;)).accept(MediaType.APPLICATION_JSON).body(body);
* ParameterizedTypeReference&lt;List&lt;MyResponse&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyResponse&gt;&gt;() {};
* RequestEntity request = RequestEntity
* .post(new URI(&quot;http://example.com/foo&quot;))
* .accept(MediaType.APPLICATION_JSON)
* .body(body);
* ParameterizedTypeReference&lt;List&lt;MyResponse&gt;&gt; myBean =
* new ParameterizedTypeReference&lt;List&lt;MyResponse&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyResponse&gt;&gt; response = template.exchange(request, myBean);
* </pre>
* @param requestEntity the entity to write to the request
@@ -597,7 +619,8 @@ public interface RestOperations {
*/
@Nullable
<T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,
@Nullable ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException;
@Nullable ResponseExtractor<T> responseExtractor, Object... uriVariables)
throws RestClientException;
/**
* Execute the HTTP method to the given URI template, preparing the request with the
@@ -612,7 +635,8 @@ public interface RestOperations {
*/
@Nullable
<T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,
@Nullable ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables) throws RestClientException;
@Nullable ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables)
throws RestClientException;
/**
* Execute the HTTP method to the given URL, preparing the request with the

View File

@@ -385,7 +385,9 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
@Override
@Nullable
public URI postForLocation(String url, @Nullable Object request, Object... uriVariables) throws RestClientException {
public URI postForLocation(String url, @Nullable Object request, Object... uriVariables)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request);
HttpHeaders headers = execute(url, HttpMethod.POST, requestCallback, headersExtractor(), uriVariables);
return (headers != null ? headers.getLocation() : null);
@@ -393,7 +395,9 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
@Override
@Nullable
public URI postForLocation(String url, @Nullable Object request, Map<String, ?> uriVariables) throws RestClientException {
public URI postForLocation(String url, @Nullable Object request, Map<String, ?> uriVariables)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request);
HttpHeaders headers = execute(url, HttpMethod.POST, requestCallback, headersExtractor(), uriVariables);
return (headers != null ? headers.getLocation() : null);
@@ -409,8 +413,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
@Override
@Nullable
public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
throws RestClientException {
public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor =
@@ -420,8 +424,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
@Override
@Nullable
public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException {
public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor =
@@ -431,7 +435,9 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
@Override
@Nullable
public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException {
public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<>(responseType, getMessageConverters());
@@ -439,8 +445,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
}
@Override
public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
throws RestClientException {
public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request,
Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
@@ -448,8 +454,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
}
@Override
public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException {
public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request,
Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
@@ -457,7 +463,9 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
}
@Override
public <T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException {
public <T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return nonNull(execute(url, HttpMethod.POST, requestCallback, responseExtractor));
@@ -467,13 +475,17 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
// PUT
@Override
public void put(String url, @Nullable Object request, Object... uriVariables) throws RestClientException {
public void put(String url, @Nullable Object request, Object... uriVariables)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request);
execute(url, HttpMethod.PUT, requestCallback, null, uriVariables);
}
@Override
public void put(String url, @Nullable Object request, Map<String, ?> uriVariables) throws RestClientException {
public void put(String url, @Nullable Object request, Map<String, ?> uriVariables)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request);
execute(url, HttpMethod.PUT, requestCallback, null, uriVariables);
}
@@ -567,7 +579,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
@Override
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
@Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException {
@Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
@@ -576,7 +589,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
@Override
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
@Nullable HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
@Nullable HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
@@ -660,7 +674,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
@Override
@Nullable
public <T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,
@Nullable ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables) throws RestClientException {
@Nullable ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables)
throws RestClientException {
URI expanded = getUriTemplateHandler().expand(url, uriVariables);
return doExecute(expanded, method, requestCallback, responseExtractor);
@@ -898,8 +913,9 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
MediaType requestContentType = requestHeaders.getContentType();
for (HttpMessageConverter<?> messageConverter : getMessageConverters()) {
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<Object> genericMessageConverter = (GenericHttpMessageConverter<Object>) messageConverter;
if (genericMessageConverter.canWrite(requestBodyType, requestBodyClass, requestContentType)) {
GenericHttpMessageConverter<Object> genericConverter =
(GenericHttpMessageConverter<Object>) messageConverter;
if (genericConverter.canWrite(requestBodyType, requestBodyClass, requestContentType)) {
if (!requestHeaders.isEmpty()) {
httpRequest.getHeaders().putAll(requestHeaders);
}
@@ -913,8 +929,7 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
}
}
genericMessageConverter.write(
requestBody, requestBodyType, requestContentType, httpRequest);
genericConverter.write(requestBody, requestBodyType, requestContentType, httpRequest);
return;
}
}

View File

@@ -42,7 +42,9 @@ class DeferredResultInterceptorChain {
this.interceptors = interceptors;
}
public void applyBeforeConcurrentHandling(NativeWebRequest request, DeferredResult<?> deferredResult) throws Exception {
public void applyBeforeConcurrentHandling(NativeWebRequest request, DeferredResult<?> deferredResult)
throws Exception {
for (DeferredResultProcessingInterceptor interceptor : this.interceptors) {
interceptor.beforeConcurrentHandling(request, deferredResult);
}
@@ -55,7 +57,9 @@ class DeferredResultInterceptorChain {
}
}
public Object applyPostProcess(NativeWebRequest request, DeferredResult<?> deferredResult, Object concurrentResult) {
public Object applyPostProcess(NativeWebRequest request, DeferredResult<?> deferredResult,
Object concurrentResult) {
try {
for (int i = this.preProcessingIndex; i >= 0; i--) {
this.interceptors.get(i).postProcess(request, deferredResult, concurrentResult);
@@ -78,12 +82,14 @@ class DeferredResultInterceptorChain {
}
}
public void triggerAfterError(NativeWebRequest request, DeferredResult<?> deferredResult, Throwable t) throws Exception {
public void triggerAfterError(NativeWebRequest request, DeferredResult<?> deferredResult, Throwable ex)
throws Exception {
for (DeferredResultProcessingInterceptor interceptor : this.interceptors) {
if (deferredResult.isSetOrExpired()) {
return;
}
if (!interceptor.handleError(request, deferredResult, t)){
if (!interceptor.handleError(request, deferredResult, ex)){
break;
}
}

View File

@@ -270,7 +270,9 @@ public final class WebAsyncManager {
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
*/
public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext) throws Exception {
public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext)
throws Exception {
Assert.notNull(webAsyncTask, "WebAsyncTask must not be null");
Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");

View File

@@ -61,7 +61,9 @@ public class RequestHandledEvent extends ApplicationEvent {
* request, if any (usually the UserPrincipal)
* @param processingTimeMillis the processing time of the request in milliseconds
*/
public RequestHandledEvent(Object source, @Nullable String sessionId, @Nullable String userName, long processingTimeMillis) {
public RequestHandledEvent(Object source, @Nullable String sessionId, @Nullable String userName,
long processingTimeMillis) {
super(source);
this.sessionId = sessionId;
this.userName = userName;
@@ -77,8 +79,8 @@ public class RequestHandledEvent extends ApplicationEvent {
* @param processingTimeMillis the processing time of the request in milliseconds
* @param failureCause the cause of failure, if any
*/
public RequestHandledEvent(
Object source, @Nullable String sessionId, @Nullable String userName, long processingTimeMillis, @Nullable Throwable failureCause) {
public RequestHandledEvent(Object source, @Nullable String sessionId, @Nullable String userName,
long processingTimeMillis, @Nullable Throwable failureCause) {
this(source, sessionId, userName, processingTimeMillis);
this.failureCause = failureCause;

View File

@@ -21,7 +21,6 @@ import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletConfig;
@@ -180,7 +179,9 @@ public abstract class WebApplicationContextUtils {
* @param beanFactory the BeanFactory to configure
* @param sc the ServletContext that we're running within
*/
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, @Nullable ServletContext sc) {
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory,
@Nullable ServletContext sc) {
beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope());
if (sc != null) {
@@ -278,7 +279,7 @@ public abstract class WebApplicationContextUtils {
* <p>This method is idempotent with respect to the fact it may be called any number
* of times but will perform replacement of stub property sources with their
* corresponding actual property sources once and only once.
* @param propertySources the {@link MutablePropertySources} to initialize (must not
* @param sources the {@link MutablePropertySources} to initialize (must not
* be {@code null})
* @param servletContext the current {@link ServletContext} (ignored if {@code null}
* or if the {@link StandardServletEnvironment#SERVLET_CONTEXT_PROPERTY_SOURCE_NAME
@@ -289,19 +290,17 @@ public abstract class WebApplicationContextUtils {
* @see org.springframework.core.env.PropertySource.StubPropertySource
* @see org.springframework.core.env.ConfigurableEnvironment#getPropertySources()
*/
public static void initServletPropertySources(
MutablePropertySources propertySources, @Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {
public static void initServletPropertySources(MutablePropertySources sources,
@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {
Assert.notNull(propertySources, "'propertySources' must not be null");
if (servletContext != null && propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME) &&
propertySources.get(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME) instanceof StubPropertySource) {
propertySources.replace(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME,
new ServletContextPropertySource(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, servletContext));
Assert.notNull(sources, "'propertySources' must not be null");
String name = StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME;
if (servletContext != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) {
sources.replace(name, new ServletContextPropertySource(name, servletContext));
}
if (servletConfig != null && propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME) &&
propertySources.get(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME) instanceof StubPropertySource) {
propertySources.replace(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME,
new ServletConfigPropertySource(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME, servletConfig));
name = StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME;
if (servletConfig != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) {
sources.replace(name, new ServletConfigPropertySource(name, servletConfig));
}
}

View File

@@ -58,8 +58,8 @@ public class DefaultCorsProcessor implements CorsProcessor {
@Override
@SuppressWarnings("resource")
public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request, HttpServletResponse response)
throws IOException {
public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (!CorsUtils.isCorsRequest(request)) {
return true;

View File

@@ -98,8 +98,8 @@ public abstract class DecoratingNavigationHandler extends NavigationHandler {
* or {@code null} if none
* @see #callNextHandlerInChain
*/
public abstract void handleNavigation(
FacesContext facesContext, @Nullable String fromAction, @Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler);
public abstract void handleNavigation(FacesContext facesContext, @Nullable String fromAction,
@Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler);
/**
@@ -130,8 +130,8 @@ public abstract class DecoratingNavigationHandler extends NavigationHandler {
* @param originalNavigationHandler the original NavigationHandler,
* or {@code null} if none
*/
protected final void callNextHandlerInChain(
FacesContext facesContext, @Nullable String fromAction, @Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler) {
protected final void callNextHandlerInChain(FacesContext facesContext, @Nullable String fromAction,
@Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler) {
NavigationHandler decoratedNavigationHandler = getDecoratedNavigationHandler();

View File

@@ -100,7 +100,9 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
* is treated as a request parameter even if it isn't annotated, the
* request parameter name is derived from the method parameter name.
*/
public RequestParamMethodArgumentResolver(@Nullable ConfigurableBeanFactory beanFactory, boolean useDefaultResolution) {
public RequestParamMethodArgumentResolver(@Nullable ConfigurableBeanFactory beanFactory,
boolean useDefaultResolution) {
super(beanFactory);
this.useDefaultResolution = useDefaultResolution;
}

View File

@@ -72,7 +72,9 @@ public class HandlerMethodArgumentResolverComposite implements HandlerMethodArgu
/**
* Add the given {@link HandlerMethodArgumentResolver}s.
*/
public HandlerMethodArgumentResolverComposite addResolvers(@Nullable List<? extends HandlerMethodArgumentResolver> resolvers) {
public HandlerMethodArgumentResolverComposite addResolvers(
@Nullable List<? extends HandlerMethodArgumentResolver> resolvers) {
if (resolvers != null) {
for (HandlerMethodArgumentResolver resolver : resolvers) {
this.argumentResolvers.add(resolver);

View File

@@ -76,7 +76,9 @@ public class StandardMultipartHttpServletRequest extends AbstractMultipartHttpSe
* first access of multipart files or parameters
* @throws MultipartException if an immediate parsing attempt failed
*/
public StandardMultipartHttpServletRequest(HttpServletRequest request, boolean lazyParsing) throws MultipartException {
public StandardMultipartHttpServletRequest(HttpServletRequest request,
boolean lazyParsing) throws MultipartException {
super(request);
if (!lazyParsing) {
parseRequest(request);

View File

@@ -73,13 +73,16 @@ public abstract class ServletContextPropertyUtils {
* @see SystemPropertyUtils#resolvePlaceholders(String, boolean)
* @throws IllegalArgumentException if there is an unresolvable placeholder and the flag is false
*/
public static String resolvePlaceholders(String text, ServletContext servletContext, boolean ignoreUnresolvablePlaceholders) {
public static String resolvePlaceholders(String text, ServletContext servletContext,
boolean ignoreUnresolvablePlaceholders) {
PropertyPlaceholderHelper helper = (ignoreUnresolvablePlaceholders ? nonStrictHelper : strictHelper);
return helper.replacePlaceholders(text, new ServletContextPlaceholderResolver(text, servletContext));
}
private static class ServletContextPlaceholderResolver implements PropertyPlaceholderHelper.PlaceholderResolver {
private static class ServletContextPlaceholderResolver
implements PropertyPlaceholderHelper.PlaceholderResolver {
private final String text;

View File

@@ -125,11 +125,14 @@ public abstract class TagUtils {
* type-assignable to the {@link Tag} class
* @see #hasAncestorOfType(javax.servlet.jsp.tagext.Tag, Class)
*/
public static void assertHasAncestorOfType(Tag tag, Class<?> ancestorTagClass, String tagName, String ancestorTagName) {
public static void assertHasAncestorOfType(Tag tag, Class<?> ancestorTagClass, String tagName,
String ancestorTagName) {
Assert.hasText(tagName, "'tagName' must not be empty");
Assert.hasText(ancestorTagName, "'ancestorTagName' must not be empty");
if (!TagUtils.hasAncestorOfType(tag, ancestorTagClass)) {
throw new IllegalStateException("The '" + tagName + "' tag can only be used inside a valid '" + ancestorTagName + "' tag.");
throw new IllegalStateException("The '" + tagName +
"' tag can only be used inside a valid '" + ancestorTagName + "' tag.");
}
}

View File

@@ -229,8 +229,11 @@ public abstract class UriUtils {
* @return the encoded query parameter
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodeQueryParam(String queryParam, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(queryParam, encoding, HierarchicalUriComponents.Type.QUERY_PARAM);
public static String encodeQueryParam(String queryParam, String encoding)
throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(
queryParam, encoding, HierarchicalUriComponents.Type.QUERY_PARAM);
}
/**
@@ -241,7 +244,8 @@ public abstract class UriUtils {
* @since 5.0
*/
public static String encodeQueryParam(String queryParam, Charset charset) {
return HierarchicalUriComponents.encodeUriComponent(queryParam, charset, HierarchicalUriComponents.Type.QUERY_PARAM);
return HierarchicalUriComponents.encodeUriComponent(
queryParam, charset, HierarchicalUriComponents.Type.QUERY_PARAM);
}
/**
@@ -251,8 +255,11 @@ public abstract class UriUtils {
* @return the encoded fragment
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodeFragment(String fragment, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(fragment, encoding, HierarchicalUriComponents.Type.FRAGMENT);
public static String encodeFragment(String fragment, String encoding)
throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(
fragment, encoding, HierarchicalUriComponents.Type.FRAGMENT);
}
/**

View File

@@ -554,7 +554,9 @@ public class UrlPathHelper {
* @param vars URI variables extracted from the URL path
* @return the same Map or a new Map instance
*/
public MultiValueMap<String, String> decodeMatrixVariables(HttpServletRequest request, MultiValueMap<String, String> vars) {
public MultiValueMap<String, String> decodeMatrixVariables(HttpServletRequest request,
MultiValueMap<String, String> vars) {
if (this.urlDecode) {
return vars;
}

View File

@@ -435,7 +435,9 @@ public abstract class WebUtils {
* @param ex the exception encountered
* @param servletName the name of the offending servlet
*/
public static void exposeErrorRequestAttributes(HttpServletRequest request, Throwable ex, @Nullable String servletName) {
public static void exposeErrorRequestAttributes(HttpServletRequest request, Throwable ex,
@Nullable String servletName) {
exposeRequestAttributeIfNotPresent(request, ERROR_STATUS_CODE_ATTRIBUTE, HttpServletResponse.SC_OK);
exposeRequestAttributeIfNotPresent(request, ERROR_EXCEPTION_TYPE_ATTRIBUTE, ex.getClass());
exposeRequestAttributeIfNotPresent(request, ERROR_MESSAGE_ATTRIBUTE, ex.getMessage());

View File

@@ -82,7 +82,8 @@ class CaptureVariablePathElement extends PathElement {
}
if (this.constraintPattern != null) {
// TODO possible optimization - only regex match if rest of pattern matches? Benefit likely to vary pattern to pattern
// TODO possible optimization - only regex match if rest of pattern matches?
// Benefit likely to vary pattern to pattern
Matcher matcher = constraintPattern.matcher(candidateCapture);
if (matcher.groupCount() != 0) {
throw new IllegalArgumentException(
@@ -117,7 +118,8 @@ class CaptureVariablePathElement extends PathElement {
}
if (match && matchingContext.extractingVariables) {
matchingContext.set(this.variableName, candidateCapture, ((PathSegment)matchingContext.pathElements.get(pathIndex-1)).parameters());
matchingContext.set(this.variableName, candidateCapture,
((PathSegment)matchingContext.pathElements.get(pathIndex-1)).parameters());
}
return match;
}

View File

@@ -381,7 +381,9 @@ public class PathPattern implements Comparable<PathPattern> {
// /hotels/* + /booking => /hotels/booking
// /hotels/* + booking => /hotels/booking
if (this.endsWithSeparatorWildcard) {
return parser.parse(concat(this.patternString.substring(0, this.patternString.length() - 2), pattern2string.patternString));
return parser.parse(concat(
this.patternString.substring(0, this.patternString.length() - 2),
pattern2string.patternString));
}
// /hotels + /booking => /hotels/booking

View File

@@ -98,8 +98,8 @@ public class PatternParseException extends IllegalArgumentException {
MISSING_OPEN_CAPTURE("Missing preceeding open capture character before variable name'{'"),
ILLEGAL_NESTED_CAPTURE("Not allowed to nest variable captures"),
CANNOT_HAVE_ADJACENT_CAPTURES("Adjacent captures are not allowed"),
ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR("Character ''{0}'' is not allowed at start of captured variable name"),
ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR("Character ''{0}'' is not allowed in a captured variable name"),
ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR("Char ''{0}'' not allowed at start of captured variable name"),
ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR("Char ''{0}'' is not allowed in a captured variable name"),
NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST("No more pattern data allowed after '{*...}' pattern element"),
BADLY_FORMED_CAPTURE_THE_REST("Expected form when capturing the rest of the path is simply '{*...}'"),
MISSING_REGEX_CONSTRAINT("Missing regex constraint on capture"),

View File

@@ -25,7 +25,8 @@ import java.net.URI
/**
* Extension for [RestOperations.getForObject] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.getForObject] avoiding specifying the type
* parameter thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -36,7 +37,8 @@ inline fun <reified T: Any> RestOperations.getForObject(url: String, vararg uriV
getForObject(url, T::class.java, *uriVariables)
/**
* Extension for [RestOperations.getForObject] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.getForObject] avoiding specifying the type
* parameter thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -47,7 +49,8 @@ inline fun <reified T: Any> RestOperations.getForObject(url: String, uriVariable
getForObject(url, T::class.java, uriVariables)
/**
* Extension for [RestOperations.getForObject] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.getForObject] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -58,7 +61,8 @@ inline fun <reified T: Any> RestOperations.getForObject(url: URI): T? =
getForObject(url, T::class.java)
/**
* Extension for [RestOperations.getForEntity] avoiding requiring the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.getForEntity] avoiding requiring the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -69,7 +73,8 @@ inline fun <reified T: Any> RestOperations.getForEntity(url: String, vararg uriV
getForEntity(url, T::class.java, *uriVariables)
/**
* Extension for [RestOperations.postForObject] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.postForObject] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -80,7 +85,8 @@ inline fun <reified T: Any> RestOperations.postForObject(url: String, request: A
postForObject(url, request, T::class.java, *uriVariables)
/**
* Extension for [RestOperations.postForObject] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.postForObject] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -91,7 +97,8 @@ inline fun <reified T: Any> RestOperations.postForObject(url: String, request: A
postForObject(url, request, T::class.java, uriVariables)
/**
* Extension for [RestOperations.postForObject] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.postForObject] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -102,7 +109,8 @@ inline fun <reified T: Any> RestOperations.postForObject(url: URI, request: Any)
postForObject(url, request, T::class.java)
/**
* Extension for [RestOperations.postForEntity] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.postForEntity] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -113,7 +121,8 @@ inline fun <reified T: Any> RestOperations.postForEntity(url: String, request: A
postForEntity(url, request, T::class.java, *uriVariables)
/**
* Extension for [RestOperations.postForEntity] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.postForEntity] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -124,7 +133,8 @@ inline fun <reified T: Any> RestOperations.postForEntity(url: String, request: A
postForEntity(url, request, T::class.java, uriVariables)
/**
* Extension for [RestOperations.postForEntity] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.postForEntity] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -135,7 +145,8 @@ inline fun <reified T: Any> RestOperations.postForEntity(url: URI, request: Any)
postForEntity(url, request, T::class.java)
/**
* Extension for [RestOperations.exchange] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.exchange] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -146,7 +157,8 @@ inline fun <reified T: Any> RestOperations.exchange(url: String, method: HttpMet
exchange(url, method, requestEntity, object : ParameterizedTypeReference<T>() {}, *uriVariables)
/**
* Extension for [RestOperations.exchange] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.exchange] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -157,7 +169,8 @@ inline fun <reified T: Any> RestOperations.exchange(url: String, method: HttpMet
exchange(url, method, requestEntity, object : ParameterizedTypeReference<T>() {}, uriVariables)
/**
* Extension for [RestOperations.exchange] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.exchange] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze
@@ -168,7 +181,8 @@ inline fun <reified T: Any> RestOperations.exchange(url: URI, method: HttpMethod
exchange(url, method, requestEntity, object : ParameterizedTypeReference<T>() {})
/**
* Extension for [RestOperations.exchange] avoiding specifying the type parameter thanks to Kotlin reified type parameters.
* Extension for [RestOperations.exchange] avoiding specifying the type parameter
* thanks to Kotlin reified type parameters.
*
* @author Jon Schneider
* @author Sebastien Deleuze

View File

@@ -81,21 +81,24 @@ public class ContentDispositionTests {
@Test
public void parseDates() {
ContentDisposition disposition = ContentDisposition
.parse("attachment; creation-date=\"Mon, 12 Feb 2007 10:15:30 -0500\"; modification-date=\"Tue, 13 Feb 2007 10:15:30 -0500\"; read-date=\"Wed, 14 Feb 2007 10:15:30 -0500\"");
.parse("attachment; creation-date=\"Mon, 12 Feb 2007 10:15:30 -0500\"; " +
"modification-date=\"Tue, 13 Feb 2007 10:15:30 -0500\"; " +
"read-date=\"Wed, 14 Feb 2007 10:15:30 -0500\"");
DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
assertEquals(ContentDisposition.builder("attachment")
.creationDate(ZonedDateTime.parse("Mon, 12 Feb 2007 10:15:30 -0500", DateTimeFormatter.RFC_1123_DATE_TIME))
.modificationDate(ZonedDateTime.parse("Tue, 13 Feb 2007 10:15:30 -0500", DateTimeFormatter.RFC_1123_DATE_TIME))
.readDate(ZonedDateTime.parse("Wed, 14 Feb 2007 10:15:30 -0500", DateTimeFormatter.RFC_1123_DATE_TIME))
.build(), disposition);
.creationDate(ZonedDateTime.parse("Mon, 12 Feb 2007 10:15:30 -0500", formatter))
.modificationDate(ZonedDateTime.parse("Tue, 13 Feb 2007 10:15:30 -0500", formatter))
.readDate(ZonedDateTime.parse("Wed, 14 Feb 2007 10:15:30 -0500", formatter)).build(), disposition);
}
@Test
public void parseInvalidDates() {
ContentDisposition disposition = ContentDisposition
.parse("attachment; creation-date=\"-1\"; modification-date=\"-1\"; read-date=\"Wed, 14 Feb 2007 10:15:30 -0500\"");
.parse("attachment; creation-date=\"-1\"; modification-date=\"-1\"; " +
"read-date=\"Wed, 14 Feb 2007 10:15:30 -0500\"");
DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
assertEquals(ContentDisposition.builder("attachment")
.readDate(ZonedDateTime.parse("Wed, 14 Feb 2007 10:15:30 -0500", DateTimeFormatter.RFC_1123_DATE_TIME))
.build(), disposition);
.readDate(ZonedDateTime.parse("Wed, 14 Feb 2007 10:15:30 -0500", formatter)).build(), disposition);
}
@Test

View File

@@ -240,7 +240,8 @@ public class ResponseEntityTests {
assertTrue(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL));
assertEquals(entity, responseEntity.getBody());
String cacheControlHeader = responseEntity.getHeaders().getCacheControl();
assertThat(cacheControlHeader, Matchers.equalTo("max-age=3600, must-revalidate, private, proxy-revalidate, s-maxage=1800"));
assertThat(cacheControlHeader,
Matchers.equalTo("max-age=3600, must-revalidate, private, proxy-revalidate, s-maxage=1800"));
}
@Test

View File

@@ -102,7 +102,10 @@ public class Jackson2JsonEncoderTests extends AbstractDataBufferAllocatingTestCa
Flux<DataBuffer> output = this.encoder.encode(source, this.bufferFactory, type, null, emptyMap());
StepVerifier.create(output)
.consumeNextWith(stringConsumer("[{\"foo\":\"foo\",\"bar\":\"bar\"},{\"foo\":\"foofoo\",\"bar\":\"barbar\"},{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}]"))
.consumeNextWith(stringConsumer("[" +
"{\"foo\":\"foo\",\"bar\":\"bar\"}," +
"{\"foo\":\"foofoo\",\"bar\":\"barbar\"}," +
"{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}]"))
.verifyComplete();
}

View File

@@ -87,7 +87,8 @@ public class FormHttpMessageConverterTests {
public void readForm() throws Exception {
String body = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.ISO_8859_1));
inputMessage.getHeaders().setContentType(new MediaType("application", "x-www-form-urlencoded", StandardCharsets.ISO_8859_1));
inputMessage.getHeaders().setContentType(
new MediaType("application", "x-www-form-urlencoded", StandardCharsets.ISO_8859_1));
MultiValueMap<String, String> result = this.converter.read(null, inputMessage);
assertEquals("Invalid result", 3, result.size());

View File

@@ -18,6 +18,7 @@ package org.springframework.http.converter.json;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@@ -156,7 +157,8 @@ public class GsonHttpMessageConverterTests {
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
List<MyBean> results = (List<MyBean>) converter.read(beansList.getGenericType(), MyBeanListHolder.class, inputMessage);
Type genericType = beansList.getGenericType();
List<MyBean> results = (List<MyBean>) converter.read(genericType, MyBeanListHolder.class, inputMessage);
assertEquals(1, results.size());
MyBean result = results.get(0);
assertEquals("Foo", result.getString());

View File

@@ -73,8 +73,15 @@ import org.junit.Test;
import org.springframework.beans.FatalBeanException;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Test class for {@link Jackson2ObjectMapperBuilder}.
@@ -225,16 +232,22 @@ public class Jackson2ObjectMapperBuilderTests {
@Test
@SuppressWarnings("unchecked")
public void modulesToInstallByClass() {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modulesToInstall(CustomIntegerModule.class).build();
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modulesToInstall(CustomIntegerModule.class)
.build();
Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next();
assertSame(CustomIntegerSerializer.class, serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass());
assertSame(CustomIntegerSerializer.class,
serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass());
}
@Test
public void modulesToInstallByInstance() {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modulesToInstall(new CustomIntegerModule()).build();
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modulesToInstall(new CustomIntegerModule())
.build();
Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next();
assertSame(CustomIntegerSerializer.class, serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass());
assertSame(CustomIntegerSerializer.class,
serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass());
}
@Test
@@ -257,9 +270,12 @@ public class Jackson2ObjectMapperBuilderTests {
}
@Test // SPR-12634
public void customizeWellKnownModulesWithModule() throws JsonProcessingException, UnsupportedEncodingException {
public void customizeWellKnownModulesWithModule()
throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modulesToInstall(new CustomIntegerModule()).build();
.modulesToInstall(new CustomIntegerModule())
.build();
DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8"));
assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8"), containsString("customid"));
@@ -267,15 +283,21 @@ public class Jackson2ObjectMapperBuilderTests {
@Test // SPR-12634
@SuppressWarnings("unchecked")
public void customizeWellKnownModulesWithModuleClass() throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modulesToInstall(CustomIntegerModule.class).build();
public void customizeWellKnownModulesWithModuleClass()
throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modulesToInstall(CustomIntegerModule.class)
.build();
DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8"));
assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8"), containsString("customid"));
}
@Test // SPR-12634
public void customizeWellKnownModulesWithSerializer() throws JsonProcessingException, UnsupportedEncodingException {
public void customizeWellKnownModulesWithSerializer()
throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.serializerByType(Integer.class, new CustomIntegerSerializer()).build();
DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
@@ -305,7 +327,8 @@ public class Jackson2ObjectMapperBuilderTests {
JsonSerializer<Number> serializer = new NumberSerializer(Integer.class);
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(new ArrayList<>()) // Disable well-known modules detection
.serializerByType(Boolean.class, serializer).build();
.serializerByType(Boolean.class, serializer)
.build();
assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers());
Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next();
assertSame(serializer, serializers.findSerializer(null, SimpleType.construct(Boolean.class), null));
@@ -316,7 +339,8 @@ public class Jackson2ObjectMapperBuilderTests {
JsonDeserializer<Date> deserializer = new DateDeserializers.DateDeserializer();
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(new ArrayList<>()) // Disable well-known modules detection
.deserializerByType(Date.class, deserializer).build();
.deserializerByType(Date.class, deserializer)
.build();
assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers());
Deserializers deserializers = getDeserializerFactoryConfig(objectMapper).deserializers().iterator().next();
assertSame(deserializer, deserializers.findBeanDeserializer(SimpleType.construct(Date.class), null, null));
@@ -327,8 +351,9 @@ public class Jackson2ObjectMapperBuilderTests {
Class<?> target = String.class;
Class<?> mixInSource = Object.class;
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules()
.mixIn(target, mixInSource).build();
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modules().mixIn(target, mixInSource)
.build();
assertEquals(1, objectMapper.mixInCount());
assertSame(mixInSource, objectMapper.findMixInClassFor(target));
@@ -341,8 +366,9 @@ public class Jackson2ObjectMapperBuilderTests {
Map<Class<?>, Class<?>> mixIns = new HashMap<>();
mixIns.put(target, mixInSource);
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules()
.mixIns(mixIns).build();
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modules().mixIns(mixIns)
.build();
assertEquals(1, objectMapper.mixInCount());
assertSame(mixInSource, objectMapper.findMixInClassFor(target));
@@ -357,8 +383,10 @@ public class Jackson2ObjectMapperBuilderTests {
assertThat(output, containsString("value1"));
assertThat(output, containsString("value2"));
objectMapper = Jackson2ObjectMapperBuilder.json().filters((new SimpleFilterProvider().setFailOnUnknownId(false)
.setDefaultFilter(SimpleBeanPropertyFilter.serializeAllExcept("property2")))).build();
SimpleFilterProvider provider = new SimpleFilterProvider()
.setFailOnUnknownId(false)
.setDefaultFilter(SimpleBeanPropertyFilter.serializeAllExcept("property2"));
objectMapper = Jackson2ObjectMapperBuilder.json().filters(provider).build();
output = objectMapper.writeValueAsString(bean);
assertThat(output, containsString("value1"));
assertThat(output, not(containsString("value2")));
@@ -378,7 +406,7 @@ public class Jackson2ObjectMapperBuilderTests {
Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json()
.modules(new ArrayList<>()) // Disable well-known modules detection
.serializers(serializer1)
.serializersByType(Collections.<Class<?>, JsonSerializer<?>>singletonMap(Boolean.class, serializer2))
.serializersByType(Collections.singletonMap(Boolean.class, serializer2))
.deserializersByType(deserializerMap)
.annotationIntrospector(annotationIntrospector)
.featuresToEnable(SerializationFeature.FAIL_ON_EMPTY_BEANS,
@@ -391,35 +419,35 @@ public class Jackson2ObjectMapperBuilderTests {
JsonGenerator.Feature.QUOTE_FIELD_NAMES)
.serializationInclusion(JsonInclude.Include.NON_NULL);
ObjectMapper objectMapper = new ObjectMapper();
builder.configure(objectMapper);
ObjectMapper mapper = new ObjectMapper();
builder.configure(mapper);
assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers());
assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers());
assertTrue(getSerializerFactoryConfig(mapper).hasSerializers());
assertTrue(getDeserializerFactoryConfig(mapper).hasDeserializers());
Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next();
Serializers serializers = getSerializerFactoryConfig(mapper).serializers().iterator().next();
assertSame(serializer1, serializers.findSerializer(null, SimpleType.construct(Class.class), null));
assertSame(serializer2, serializers.findSerializer(null, SimpleType.construct(Boolean.class), null));
assertNull(serializers.findSerializer(null, SimpleType.construct(Number.class), null));
Deserializers deserializers = getDeserializerFactoryConfig(objectMapper).deserializers().iterator().next();
Deserializers deserializers = getDeserializerFactoryConfig(mapper).deserializers().iterator().next();
assertSame(deserializer, deserializers.findBeanDeserializer(SimpleType.construct(Date.class), null, null));
assertSame(annotationIntrospector, objectMapper.getSerializationConfig().getAnnotationIntrospector());
assertSame(annotationIntrospector, objectMapper.getDeserializationConfig().getAnnotationIntrospector());
assertSame(annotationIntrospector, mapper.getSerializationConfig().getAnnotationIntrospector());
assertSame(annotationIntrospector, mapper.getDeserializationConfig().getAnnotationIntrospector());
assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
assertTrue(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
assertTrue(objectMapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER));
assertTrue(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS));
assertTrue(mapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
assertTrue(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
assertTrue(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER));
assertTrue(mapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS));
assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
assertFalse(objectMapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE));
assertFalse(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES));
assertSame(JsonInclude.Include.NON_NULL, objectMapper.getSerializationConfig().getSerializationInclusion());
assertFalse(mapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
assertFalse(mapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
assertFalse(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
assertFalse(mapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
assertFalse(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE));
assertFalse(mapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES));
assertSame(JsonInclude.Include.NON_NULL, mapper.getSerializationConfig().getSerializationInclusion());
}
@Test
@@ -495,7 +523,9 @@ public class Jackson2ObjectMapperBuilderTests {
public static class CustomIntegerSerializer extends JsonSerializer<Integer> {
@Override
public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
gen.writeStartObject();
gen.writeNumberField("customid", value);
gen.writeEndObject();

View File

@@ -84,8 +84,13 @@ public class MappingJackson2HttpMessageConverterTests {
@Test
public void readTyped() throws IOException {
String body =
"{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}";
String body = "{" +
"\"bytes\":\"AQI=\"," +
"\"array\":[\"Foo\",\"Bar\"]," +
"\"number\":42," +
"\"string\":\"Foo\"," +
"\"bool\":true," +
"\"fraction\":42.0}";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
MyBean result = (MyBean) converter.read(MyBean.class, inputMessage);
@@ -100,8 +105,13 @@ public class MappingJackson2HttpMessageConverterTests {
@Test
@SuppressWarnings("unchecked")
public void readUntyped() throws IOException {
String body =
"{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}";
String body = "{" +
"\"bytes\":\"AQI=\"," +
"\"array\":[\"Foo\",\"Bar\"]," +
"\"number\":42," +
"\"string\":\"Foo\"," +
"\"bool\":true," +
"\"fraction\":42.0}";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
HashMap<String, Object> result = (HashMap<String, Object>) converter.read(HashMap.class, inputMessage);
@@ -179,8 +189,13 @@ public class MappingJackson2HttpMessageConverterTests {
}
}
};
String body =
"[{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]";
String body = "[{" +
"\"bytes\":\"AQI=\"," +
"\"array\":[\"Foo\",\"Bar\"]," +
"\"number\":42," +
"\"string\":\"Foo\"," +
"\"bool\":true," +
"\"fraction\":42.0}]";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
@@ -200,8 +215,13 @@ public class MappingJackson2HttpMessageConverterTests {
public void readParameterizedType() throws IOException {
ParameterizedTypeReference<List<MyBean>> beansList = new ParameterizedTypeReference<List<MyBean>>() {};
String body =
"[{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]";
String body = "[{" +
"\"bytes\":\"AQI=\"," +
"\"array\":[\"Foo\",\"Bar\"]," +
"\"number\":42," +
"\"string\":\"Foo\"," +
"\"bool\":true," +
"\"fraction\":42.0}]";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
@@ -228,7 +248,8 @@ public class MappingJackson2HttpMessageConverterTests {
this.converter.writeInternal(bean, null, outputMessage);
String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
assertEquals("{" + NEWLINE_SYSTEM_PROPERTY + " \"name\" : \"Jason\"" + NEWLINE_SYSTEM_PROPERTY + "}", result);
assertEquals("{" + NEWLINE_SYSTEM_PROPERTY +
" \"name\" : \"Jason\"" + NEWLINE_SYSTEM_PROPERTY + "}", result);
}
@Test

View File

@@ -136,7 +136,9 @@ public class SpringHandlerInstantiatorTests {
private Capitalizer capitalizer;
@Override
public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
public void serialize(User user, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("username", this.capitalizer.capitalize(user.getUsername()));
jsonGenerator.writeEndObject();
@@ -150,7 +152,7 @@ public class SpringHandlerInstantiatorTests {
private Capitalizer capitalizer;
@Override
public Object deserializeKey(String key, DeserializationContext context) throws IOException, JsonProcessingException {
public Object deserializeKey(String key, DeserializationContext context) throws IOException {
return this.capitalizer.capitalize(key);
}
}
@@ -164,13 +166,17 @@ public class SpringHandlerInstantiatorTests {
public static boolean isAutowiredFiledInitialized = false;
@Override
public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType, Collection<NamedType> subtypes) {
public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType,
Collection<NamedType> subtypes) {
isAutowiredFiledInitialized = (this.capitalizer != null);
return super.buildTypeSerializer(config, baseType, subtypes);
}
@Override
public TypeDeserializer buildTypeDeserializer(DeserializationConfig config, JavaType baseType, Collection<NamedType> subtypes) {
public TypeDeserializer buildTypeDeserializer(DeserializationConfig config,
JavaType baseType, Collection<NamedType> subtypes) {
return super.buildTypeDeserializer(config, baseType, subtypes);
}
}

View File

@@ -82,15 +82,20 @@ public class Jaxb2RootElementHttpMessageConverterTests {
@Test
public void canRead() throws Exception {
assertTrue("Converter does not support reading @XmlRootElement", converter.canRead(RootElement.class, null));
assertTrue("Converter does not support reading @XmlType", converter.canRead(Type.class, null));
assertTrue("Converter does not support reading @XmlRootElement",
converter.canRead(RootElement.class, null));
assertTrue("Converter does not support reading @XmlType",
converter.canRead(Type.class, null));
}
@Test
public void canWrite() throws Exception {
assertTrue("Converter does not support writing @XmlRootElement", converter.canWrite(RootElement.class, null));
assertTrue("Converter does not support writing @XmlRootElement subclass", converter.canWrite(RootElementSubclass.class, null));
assertTrue("Converter does not support writing @XmlRootElement subclass", converter.canWrite(rootElementCglib.getClass(), null));
assertTrue("Converter does not support writing @XmlRootElement",
converter.canWrite(RootElement.class, null));
assertTrue("Converter does not support writing @XmlRootElement subclass",
converter.canWrite(RootElementSubclass.class, null));
assertTrue("Converter does not support writing @XmlRootElement subclass",
converter.canWrite(rootElementCglib.getClass(), null));
assertFalse("Converter supports writing @XmlType", converter.canWrite(Type.class, null));
}

View File

@@ -65,7 +65,14 @@ public class MappingJackson2XmlHttpMessageConverterTests {
@Test
public void read() throws IOException {
String body = "<MyBean><string>Foo</string><number>42</number><fraction>42.0</fraction><array><array>Foo</array><array>Bar</array></array><bool>true</bool><bytes>AQI=</bytes></MyBean>";
String body = "<MyBean>" +
"<string>Foo</string>" +
"<number>42</number>" +
"<fraction>42.0</fraction>" +
"<array><array>Foo</array>" +
"<array>Bar</array></array>" +
"<bool>true</bool>" +
"<bytes>AQI=</bytes></MyBean>";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
MyBean result = (MyBean) converter.read(MyBean.class, inputMessage);

View File

@@ -57,7 +57,9 @@ public class MockExpressionEvaluator extends javax.servlet.jsp.el.ExpressionEval
return new javax.servlet.jsp.el.Expression() {
@Override
public Object evaluate(javax.servlet.jsp.el.VariableResolver variableResolver) throws javax.servlet.jsp.el.ELException {
public Object evaluate(javax.servlet.jsp.el.VariableResolver variableResolver)
throws javax.servlet.jsp.el.ELException {
return doEvaluate(expression, expectedType, functionMapper);
}
};
@@ -65,7 +67,8 @@ public class MockExpressionEvaluator extends javax.servlet.jsp.el.ExpressionEval
@Override
@SuppressWarnings("rawtypes")
public Object evaluate(String expression, Class expectedType, javax.servlet.jsp.el.VariableResolver variableResolver,
public Object evaluate(String expression, Class expectedType,
javax.servlet.jsp.el.VariableResolver variableResolver,
javax.servlet.jsp.el.FunctionMapper functionMapper) throws javax.servlet.jsp.el.ELException {
Assert.isNull(variableResolver, "Custom VariableResolver not supported");
@@ -73,15 +76,17 @@ public class MockExpressionEvaluator extends javax.servlet.jsp.el.ExpressionEval
}
@SuppressWarnings("rawtypes")
protected Object doEvaluate(String expression, Class expectedType, javax.servlet.jsp.el.FunctionMapper functionMapper)
throws javax.servlet.jsp.el.ELException {
protected Object doEvaluate(String expression, Class expectedType,
javax.servlet.jsp.el.FunctionMapper functionMapper) throws javax.servlet.jsp.el.ELException {
Assert.isNull(functionMapper, "Custom FunctionMapper not supported");
try {
return ExpressionEvaluatorManager.evaluate("JSP EL expression", expression, expectedType, this.pageContext);
return ExpressionEvaluatorManager.evaluate(
"JSP EL expression", expression, expectedType, this.pageContext);
}
catch (JspException ex) {
throw new javax.servlet.jsp.el.ELException("Parsing of JSP EL expression \"" + expression + "\" failed", ex);
throw new javax.servlet.jsp.el.ELException(
"Parsing of JSP EL expression \"" + expression + "\" failed", ex);
}
}

View File

@@ -526,7 +526,8 @@ public final class Msg extends
// optional .SecondMsg blah = 2;
private org.springframework.protobuf.SecondMsg blah_ = org.springframework.protobuf.SecondMsg.getDefaultInstance();
private com.google.protobuf.SingleFieldBuilder<
org.springframework.protobuf.SecondMsg, org.springframework.protobuf.SecondMsg.Builder, org.springframework.protobuf.SecondMsgOrBuilder> blahBuilder_;
org.springframework.protobuf.SecondMsg, org.springframework.protobuf.SecondMsg.Builder,
org.springframework.protobuf.SecondMsgOrBuilder> blahBuilder_;
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
@@ -627,7 +628,8 @@ public final class Msg extends
* <code>optional .SecondMsg blah = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
org.springframework.protobuf.SecondMsg, org.springframework.protobuf.SecondMsg.Builder, org.springframework.protobuf.SecondMsgOrBuilder>
org.springframework.protobuf.SecondMsg, org.springframework.protobuf.SecondMsg.Builder,
org.springframework.protobuf.SecondMsgOrBuilder>
getBlahFieldBuilder() {
if (blahBuilder_ == null) {
blahBuilder_ = new com.google.protobuf.SingleFieldBuilder<>(

View File

@@ -25,7 +25,8 @@ import org.springframework.util.Assert;
/**
* @author Juergen Hoeller
*/
@WebService(serviceName="OrderService", portName="OrderService", endpointInterface = "org.springframework.remoting.jaxws.OrderService")
@WebService(serviceName="OrderService", portName="OrderService",
endpointInterface = "org.springframework.remoting.jaxws.OrderService")
public class OrderServiceImpl implements OrderService {
@Resource

View File

@@ -50,12 +50,13 @@ public class EscapedErrorsTests {
assertTrue("Correct global errors flag", errors.hasGlobalErrors());
assertTrue("Correct number of global errors", errors.getGlobalErrorCount() == 1);
ObjectError globalError = errors.getGlobalError();
assertTrue("Global error message escaped", "message: &quot; &#39;".equals(globalError.getDefaultMessage()));
String defaultMessage = globalError.getDefaultMessage();
assertTrue("Global error message escaped", "message: &quot; &#39;".equals(defaultMessage));
assertTrue("Global error code not escaped", "GENERAL_ERROR \" '".equals(globalError.getCode()));
ObjectError globalErrorInList = errors.getGlobalErrors().get(0);
assertTrue("Same global error in list", globalError.getDefaultMessage().equals(globalErrorInList.getDefaultMessage()));
assertTrue("Same global error in list", defaultMessage.equals(globalErrorInList.getDefaultMessage()));
ObjectError globalErrorInAllList = errors.getAllErrors().get(3);
assertTrue("Same global error in list", globalError.getDefaultMessage().equals(globalErrorInAllList.getDefaultMessage()));
assertTrue("Same global error in list", defaultMessage.equals(globalErrorInAllList.getDefaultMessage()));
assertTrue("Correct field errors flag", errors.hasFieldErrors());
assertTrue("Correct number of field errors", errors.getFieldErrorCount() == 3);

View File

@@ -58,6 +58,7 @@ import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
import static org.springframework.http.HttpMethod.POST;
/**
* @author Arjen Poutsma
@@ -248,8 +249,8 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyHeader", "MyValue");
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<String> requestEntity = new HttpEntity<>(helloWorld, requestHeaders);
HttpEntity<Void> result = template.exchange(baseUrl + "/{method}", HttpMethod.POST, requestEntity, Void.class, "post");
HttpEntity<String> entity = new HttpEntity<>(helloWorld, requestHeaders);
HttpEntity<Void> result = template.exchange(baseUrl + "/{method}", POST, entity, Void.class, "post");
assertEquals("Invalid location", new URI(baseUrl + "/post/1"), result.getHeaders().getLocation());
assertFalse(result.hasBody());
}

View File

@@ -47,6 +47,7 @@ import org.springframework.web.util.DefaultUriBuilderFactory;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.http.MediaType.*;
/**
@@ -326,7 +327,7 @@ public class RestTemplateTests {
@Test
public void postForLocation() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(request);
String helloWorld = "Hello World";
given(converter.canWrite(String.class, null)).willReturn(true);
converter.write(helloWorld, null, request);
@@ -348,7 +349,7 @@ public class RestTemplateTests {
@Test
public void postForLocationEntityContentType() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(request);
String helloWorld = "Hello World";
MediaType contentType = MediaType.TEXT_PLAIN;
given(converter.canWrite(String.class, contentType)).willReturn(true);
@@ -377,7 +378,7 @@ public class RestTemplateTests {
@Test
public void postForLocationEntityCustomHeader() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(request);
String helloWorld = "Hello World";
given(converter.canWrite(String.class, null)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
@@ -406,7 +407,7 @@ public class RestTemplateTests {
@Test
public void postForLocationNoLocation() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(request);
String helloWorld = "Hello World";
given(converter.canWrite(String.class, null)).willReturn(true);
converter.write(helloWorld, null, request);
@@ -426,7 +427,7 @@ public class RestTemplateTests {
@Test
public void postForLocationNull() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
@@ -448,7 +449,7 @@ public class RestTemplateTests {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
String request = "Hello World";
@@ -481,7 +482,7 @@ public class RestTemplateTests {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
String request = "Hello World";
@@ -514,7 +515,7 @@ public class RestTemplateTests {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
@@ -543,7 +544,7 @@ public class RestTemplateTests {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
@@ -685,7 +686,7 @@ public class RestTemplateTests {
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
EnumSet<HttpMethod> expected = EnumSet.of(HttpMethod.GET, HttpMethod.POST);
EnumSet<HttpMethod> expected = EnumSet.of(HttpMethod.GET, POST);
responseHeaders.setAllow(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
@@ -747,7 +748,7 @@ public class RestTemplateTests {
public void exchange() throws Exception {
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
given(converter.canWrite(String.class, null)).willReturn(true);
@@ -769,8 +770,8 @@ public class RestTemplateTests {
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.set("MyHeader", "MyValue");
HttpEntity<String> requestEntity = new HttpEntity<>(body, entityHeaders);
ResponseEntity<Integer> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, Integer.class);
HttpEntity<String> entity = new HttpEntity<>(body, entityHeaders);
ResponseEntity<Integer> result = template.exchange("http://example.com", POST, entity, Integer.class);
assertEquals("Invalid POST result", expected, result.getBody());
assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
@@ -789,7 +790,7 @@ public class RestTemplateTests {
ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {};
given(converter.canRead(intList.getType(), null, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
given(requestFactory.createRequest(new URI("http://example.com"), POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
given(converter.canWrite(String.class, String.class, null)).willReturn(true);
@@ -811,7 +812,7 @@ public class RestTemplateTests {
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.set("MyHeader", "MyValue");
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, entityHeaders);
ResponseEntity<List<Integer>> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, intList);
ResponseEntity<List<Integer>> result = template.exchange("http://example.com", POST, requestEntity, intList);
assertEquals("Invalid POST result", expected, result.getBody());
assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));

View File

@@ -126,7 +126,8 @@ public class ServletWebRequestHttpMethodsTests {
assertTrue(request.checkNotModified(epochTime));
assertEquals(304, servletResponse.getStatus());
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(epochTime).atZone(GMT)), servletResponse.getHeader("Last-Modified"));
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(epochTime).atZone(GMT)),
servletResponse.getHeader("Last-Modified"));
}
@Test
@@ -137,7 +138,8 @@ public class ServletWebRequestHttpMethodsTests {
assertFalse(request.checkNotModified(currentDate.getTime()));
assertEquals(200, servletResponse.getStatus());
assertEquals(RFC_1123_DATE_TIME.format(currentDate.toInstant().atZone(GMT)), servletResponse.getHeader("Last-Modified"));
assertEquals(RFC_1123_DATE_TIME.format(currentDate.toInstant().atZone(GMT)),
servletResponse.getHeader("Last-Modified"));
}
@Test
@@ -220,7 +222,8 @@ public class ServletWebRequestHttpMethodsTests {
assertEquals(304, servletResponse.getStatus());
assertEquals(eTag, servletResponse.getHeader("ETag"));
assertEquals(RFC_1123_DATE_TIME.format(currentDate.toInstant().atZone(GMT)), servletResponse.getHeader("Last-Modified"));
assertEquals(RFC_1123_DATE_TIME.format(currentDate.toInstant().atZone(GMT)),
servletResponse.getHeader("Last-Modified"));
}
@Test // SPR-14224
@@ -235,7 +238,8 @@ public class ServletWebRequestHttpMethodsTests {
assertEquals(304, servletResponse.getStatus());
assertEquals(eTag, servletResponse.getHeader("ETag"));
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(currentEpoch).atZone(GMT)), servletResponse.getHeader("Last-Modified"));
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(currentEpoch).atZone(GMT)),
servletResponse.getHeader("Last-Modified"));
}
@Test
@@ -250,7 +254,8 @@ public class ServletWebRequestHttpMethodsTests {
assertEquals(200, servletResponse.getStatus());
assertEquals(currentETag, servletResponse.getHeader("ETag"));
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(epochTime).atZone(GMT)), servletResponse.getHeader("Last-Modified"));
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(epochTime).atZone(GMT)),
servletResponse.getHeader("Last-Modified"));
}
@Test
@@ -297,7 +302,8 @@ public class ServletWebRequestHttpMethodsTests {
assertTrue(request.checkNotModified(epochTime));
assertEquals(304, servletResponse.getStatus());
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(epochTime).atZone(GMT)), servletResponse.getHeader("Last-Modified"));
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(epochTime).atZone(GMT)),
servletResponse.getHeader("Last-Modified"));
}
@Test
@@ -309,7 +315,8 @@ public class ServletWebRequestHttpMethodsTests {
assertFalse(request.checkNotModified(epochTime));
assertEquals(200, servletResponse.getStatus());
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(epochTime).atZone(GMT)), servletResponse.getHeader("Last-Modified"));
assertEquals(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(epochTime).atZone(GMT)),
servletResponse.getHeader("Last-Modified"));
}
@Test

View File

@@ -42,11 +42,16 @@ public class StandardServletEnvironmentTests {
ConfigurableEnvironment env = new StandardServletEnvironment();
MutablePropertySources sources = env.getPropertySources();
assertThat(sources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), equalTo(0));
assertThat(sources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)), equalTo(1));
assertThat(sources.precedenceOf(PropertySource.named(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)), equalTo(2));
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(3));
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(4));
assertThat(sources.precedenceOf(PropertySource.named(
StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), equalTo(0));
assertThat(sources.precedenceOf(PropertySource.named(
StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)), equalTo(1));
assertThat(sources.precedenceOf(PropertySource.named(
StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)), equalTo(2));
assertThat(sources.precedenceOf(PropertySource.named(
StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(3));
assertThat(sources.precedenceOf(PropertySource.named(
StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(4));
assertThat(sources.size(), is(5));
}

View File

@@ -232,8 +232,10 @@ public class CorsConfigurationTests {
config.addAllowedHeader("header1");
config.addAllowedHeader("header2");
assertEquals(Arrays.asList("header1"), config.checkHeaders(Arrays.asList("header1")));
assertEquals(Arrays.asList("header1", "header2"), config.checkHeaders(Arrays.asList("header1", "header2")));
assertEquals(Arrays.asList("header1", "header2"), config.checkHeaders(Arrays.asList("header1", "header2", "header3")));
assertEquals(Arrays.asList("header1", "header2"),
config.checkHeaders(Arrays.asList("header1", "header2")));
assertEquals(Arrays.asList("header1", "header2"),
config.checkHeaders(Arrays.asList("header1", "header2", "header3")));
}
@Test

View File

@@ -32,15 +32,20 @@ public class UrlBasedCorsConfigurationSourceTests {
@Test
public void empty() {
assertNull(this.configSource.getCorsConfiguration(new MockHttpServletRequest(HttpMethod.GET.name(), "/bar/test.html")));
MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "/bar/test.html");
assertNull(this.configSource.getCorsConfiguration(request));
}
@Test
public void registerAndMatch() {
CorsConfiguration config = new CorsConfiguration();
this.configSource.registerCorsConfiguration("/bar/**", config);
assertNull(this.configSource.getCorsConfiguration(new MockHttpServletRequest(HttpMethod.GET.name(), "/foo/test.html")));
assertEquals(config, this.configSource.getCorsConfiguration(new MockHttpServletRequest(HttpMethod.GET.name(), "/bar/test.html")));
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/test.html");
assertNull(this.configSource.getCorsConfiguration(request));
request.setRequestURI("/bar/test.html");
assertEquals(config, this.configSource.getCorsConfiguration(request));
}
@Test(expected = UnsupportedOperationException.class)

View File

@@ -46,7 +46,7 @@ public class CharacterEncodingFilterTests {
HttpServletRequest request = mock(HttpServletRequest.class);
request.setCharacterEncoding(ENCODING);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
@@ -55,8 +55,8 @@ public class CharacterEncodingFilterTests {
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
verify(request).removeAttribute(filteredName(FILTER_NAME));
verify(response).setCharacterEncoding(ENCODING);
verify(filterChain).doFilter(request, response);
}
@@ -66,7 +66,7 @@ public class CharacterEncodingFilterTests {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getCharacterEncoding()).willReturn(null);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -77,8 +77,8 @@ public class CharacterEncodingFilterTests {
filter.doFilter(request, response, filterChain);
verify(request).setCharacterEncoding(ENCODING);
verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
verify(request).removeAttribute(filteredName(FILTER_NAME));
verify(filterChain).doFilter(request, response);
}
@@ -87,7 +87,7 @@ public class CharacterEncodingFilterTests {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getCharacterEncoding()).willReturn(ENCODING);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -97,8 +97,8 @@ public class CharacterEncodingFilterTests {
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
verify(request).removeAttribute(filteredName(FILTER_NAME));
verify(filterChain).doFilter(request, response);
}
@@ -107,7 +107,7 @@ public class CharacterEncodingFilterTests {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getCharacterEncoding()).willReturn(null);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -120,8 +120,8 @@ public class CharacterEncodingFilterTests {
filter.doFilter(request, response, filterChain);
verify(request).setCharacterEncoding(ENCODING);
verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
verify(request).removeAttribute(filteredName(FILTER_NAME));
verify(filterChain).doFilter(request, response);
}
@@ -130,7 +130,7 @@ public class CharacterEncodingFilterTests {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getCharacterEncoding()).willReturn(null);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
given(request.getAttribute(filteredName(CharacterEncodingFilter.class.getName()))).willReturn(null);
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -140,8 +140,8 @@ public class CharacterEncodingFilterTests {
filter.doFilter(request, response, filterChain);
verify(request).setCharacterEncoding(ENCODING);
verify(request).setAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(request).setAttribute(filteredName(CharacterEncodingFilter.class.getName()), Boolean.TRUE);
verify(request).removeAttribute(filteredName(CharacterEncodingFilter.class.getName()));
verify(filterChain).doFilter(request, response);
}
@@ -151,7 +151,7 @@ public class CharacterEncodingFilterTests {
HttpServletRequest request = mock(HttpServletRequest.class);
request.setCharacterEncoding(ENCODING);
given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);
given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
@@ -160,11 +160,15 @@ public class CharacterEncodingFilterTests {
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
verify(request).removeAttribute(filteredName(FILTER_NAME));
verify(request, times(2)).setCharacterEncoding(ENCODING);
verify(response, never()).setCharacterEncoding(ENCODING);
verify(filterChain).doFilter(request, response);
}
private String filteredName(String prefix) {
return prefix + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX;
}
}

View File

@@ -146,7 +146,9 @@ public class DelegatingFilterProxyTests {
}
@Test
public void testDelegatingFilterProxyWithTargetBeanNameAndNotYetRefreshedApplicationContext() throws ServletException, IOException {
public void testDelegatingFilterProxyWithTargetBeanNameAndNotYetRefreshedApplicationContext()
throws ServletException, IOException {
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
@@ -172,7 +174,9 @@ public class DelegatingFilterProxyTests {
}
@Test(expected = IllegalStateException.class)
public void testDelegatingFilterProxyWithTargetBeanNameAndNoApplicationContext() throws ServletException, IOException {
public void testDelegatingFilterProxyWithTargetBeanNameAndNoApplicationContext()
throws ServletException, IOException {
MockServletContext sc = new MockServletContext();
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("targetFilter", null);
@@ -325,7 +329,9 @@ public class DelegatingFilterProxyTests {
}
@Test
public void testDelegatingFilterProxyNotInjectedWacServletAttrPreferred() throws ServletException, IOException {
public void testDelegatingFilterProxyNotInjectedWacServletAttrPreferred()
throws ServletException, IOException {
ServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
@@ -401,7 +407,9 @@ public class DelegatingFilterProxyTests {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
request.setAttribute("called", Boolean.TRUE);
}

View File

@@ -91,8 +91,9 @@ public class DelegatingNavigationHandlerTests {
private String lastOutcome;
@Override
public void handleNavigation(
FacesContext facesContext, @Nullable String fromAction, @Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler) {
public void handleNavigation(FacesContext facesContext, @Nullable String fromAction,
@Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler) {
lastFromAction = fromAction;
lastOutcome = outcome;
if (originalNavigationHandler != null) {

View File

@@ -49,7 +49,9 @@ public class UriComponentsBuilderTests {
@Test
public void plain() throws URISyntaxException {
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
UriComponents result = builder.scheme("http").host("example.com").path("foo").queryParam("bar").fragment("baz").build();
UriComponents result = builder.scheme("http").host("example.com")
.path("foo").queryParam("bar").fragment("baz")
.build();
assertEquals("http", result.getScheme());
assertEquals("example.com", result.getHost());
assertEquals("foo", result.getPath());
@@ -62,7 +64,8 @@ public class UriComponentsBuilderTests {
@Test
public void multipleFromSameBuilder() throws URISyntaxException {
UriComponentsBuilder builder = UriComponentsBuilder.newInstance().scheme("http").host("example.com").pathSegment("foo");
UriComponentsBuilder builder = UriComponentsBuilder.newInstance()
.scheme("http").host("example.com").pathSegment("foo");
UriComponents result1 = builder.build();
builder = builder.pathSegment("foo2").queryParam("bar").fragment("baz");
UriComponents result2 = builder.build();
@@ -129,7 +132,8 @@ public class UriComponentsBuilderTests {
public void fromUriEncodedQuery() throws URISyntaxException {
URI uri = new URI("http://www.example.org/?param=aGVsbG9Xb3JsZA%3D%3D");
String fromUri = UriComponentsBuilder.fromUri(uri).build().getQueryParams().get("param").get(0);
String fromUriString = UriComponentsBuilder.fromUriString(uri.toString()).build().getQueryParams().get("param").get(0);
String fromUriString = UriComponentsBuilder.fromUriString(uri.toString())
.build().getQueryParams().get("param").get(0);
assertEquals(fromUri, fromUriString);
}
@@ -146,9 +150,9 @@ public class UriComponentsBuilderTests {
assertNull(result.getQuery());
assertNull(result.getFragment());
result = UriComponentsBuilder.fromUriString(
"http://arjen:foobar@java.sun.com:80/javase/6/docs/api/java/util/BitSet.html?foo=bar#and(java.util.BitSet)")
.build();
String url = "http://arjen:foobar@java.sun.com:80" +
"/javase/6/docs/api/java/util/BitSet.html?foo=bar#and(java.util.BitSet)";
result = UriComponentsBuilder.fromUriString(url).build();
assertEquals("http", result.getScheme());
assertEquals("arjen:foobar", result.getUserInfo());
assertEquals("java.sun.com", result.getHost());
@@ -635,7 +639,8 @@ public class UriComponentsBuilderTests {
@Test
public void buildAndExpandOpaque() {
UriComponents result = UriComponentsBuilder.fromUriString("mailto:{user}@{domain}").buildAndExpand("foo", "example.com");
UriComponents result = UriComponentsBuilder.fromUriString("mailto:{user}@{domain}")
.buildAndExpand("foo", "example.com");
assertEquals("mailto:foo@example.com", result.toUriString());
Map<String, String> values = new HashMap<>();
@@ -670,23 +675,38 @@ public class UriComponentsBuilderTests {
@Test
public void relativeUrls() throws Exception {
assertThat(UriComponentsBuilder.fromUriString("http://example.com/foo/../bar").build().toString(), equalTo("http://example.com/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString("http://example.com/foo/../bar").build().toUriString(), equalTo("http://example.com/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString("http://example.com/foo/../bar").build().toUri().getPath(), equalTo("/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString("../../").build().toString(), equalTo("../../"));
assertThat(UriComponentsBuilder.fromUriString("../../").build().toUriString(), equalTo("../../"));
assertThat(UriComponentsBuilder.fromUriString("../../").build().toUri().getPath(), equalTo("../../"));
assertThat(UriComponentsBuilder.fromUriString("http://example.com").path("foo/../bar").build().toString(), equalTo("http://example.com/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString("http://example.com").path("foo/../bar").build().toUriString(), equalTo("http://example.com/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString("http://example.com").path("foo/../bar").build().toUri().getPath(), equalTo("/foo/../bar"));
String baseUrl = "http://example.com";
assertThat(UriComponentsBuilder.fromUriString(baseUrl + "/foo/../bar").build().toString(),
equalTo(baseUrl + "/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString(baseUrl + "/foo/../bar").build().toUriString(),
equalTo(baseUrl + "/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString(baseUrl + "/foo/../bar").build().toUri().getPath(),
equalTo("/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString("../../").build().toString(),
equalTo("../../"));
assertThat(UriComponentsBuilder.fromUriString("../../").build().toUriString(),
equalTo("../../"));
assertThat(UriComponentsBuilder.fromUriString("../../").build().toUri().getPath(),
equalTo("../../"));
assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("foo/../bar").build().toString(),
equalTo(baseUrl + "/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("foo/../bar").build().toUriString(),
equalTo(baseUrl + "/foo/../bar"));
assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("foo/../bar").build().toUri().getPath(),
equalTo("/foo/../bar"));
}
@Test
public void emptySegments() throws Exception {
assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").path("/x/y/z").build().toString(), equalTo("http://example.com/abc/x/y/z"));
assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").pathSegment("x", "y", "z").build().toString(), equalTo("http://example.com/abc/x/y/z"));
assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").path("/x/").path("/y/z").build().toString(), equalTo("http://example.com/abc/x/y/z"));
assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").pathSegment("x").path("y").build().toString(), equalTo("http://example.com/abc/x/y"));
String baseUrl = "http://example.com/abc/";
assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("/x/y/z").build().toString(),
equalTo("http://example.com/abc/x/y/z"));
assertThat(UriComponentsBuilder.fromUriString(baseUrl).pathSegment("x", "y", "z").build().toString(),
equalTo("http://example.com/abc/x/y/z"));
assertThat(UriComponentsBuilder.fromUriString(baseUrl).path("/x/").path("/y/z").build().toString(),
equalTo("http://example.com/abc/x/y/z"));
assertThat(UriComponentsBuilder.fromUriString(baseUrl).pathSegment("x").path("y").build().toString(),
equalTo("http://example.com/abc/x/y"));
}
@Test

View File

@@ -159,24 +159,26 @@ public class UriComponentsTests {
@Test
public void equalsHierarchicalUriComponents() throws Exception {
UriComponents uriComponents1 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bar={baz}").build();
UriComponents uriComponents2 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bar={baz}").build();
UriComponents uriComponents3 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bin={baz}").build();
assertThat(uriComponents1, instanceOf(HierarchicalUriComponents.class));
assertThat(uriComponents1, equalTo(uriComponents1));
assertThat(uriComponents1, equalTo(uriComponents2));
assertThat(uriComponents1, not(equalTo(uriComponents3)));
String url = "http://example.com";
UriComponents uric1 = UriComponentsBuilder.fromUriString(url).path("/{foo}").query("bar={baz}").build();
UriComponents uric2 = UriComponentsBuilder.fromUriString(url).path("/{foo}").query("bar={baz}").build();
UriComponents uric3 = UriComponentsBuilder.fromUriString(url).path("/{foo}").query("bin={baz}").build();
assertThat(uric1, instanceOf(HierarchicalUriComponents.class));
assertThat(uric1, equalTo(uric1));
assertThat(uric1, equalTo(uric2));
assertThat(uric1, not(equalTo(uric3)));
}
@Test
public void equalsOpaqueUriComponents() throws Exception {
UriComponents uriComponents1 = UriComponentsBuilder.fromUriString("http:example.com/foo/bar").build();
UriComponents uriComponents2 = UriComponentsBuilder.fromUriString("http:example.com/foo/bar").build();
UriComponents uriComponents3 = UriComponentsBuilder.fromUriString("http:example.com/foo/bin").build();
assertThat(uriComponents1, instanceOf(OpaqueUriComponents.class));
assertThat(uriComponents1, equalTo(uriComponents1));
assertThat(uriComponents1, equalTo(uriComponents2));
assertThat(uriComponents1, not(equalTo(uriComponents3)));
String baseUrl = "http:example.com";
UriComponents uric1 = UriComponentsBuilder.fromUriString(baseUrl + "/foo/bar").build();
UriComponents uric2 = UriComponentsBuilder.fromUriString(baseUrl + "/foo/bar").build();
UriComponents uric3 = UriComponentsBuilder.fromUriString(baseUrl + "/foo/bin").build();
assertThat(uric1, instanceOf(OpaqueUriComponents.class));
assertThat(uric1, equalTo(uric1));
assertThat(uric1, equalTo(uric2));
assertThat(uric1, not(equalTo(uric3)));
}
}

View File

@@ -30,7 +30,10 @@ import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* @author Juergen Hoeller
@@ -126,10 +129,15 @@ public class WebUtilsTests {
// Handling of IPv6 hosts as described in SPR-13525
assertTrue(checkSameOrigin("[::1]", -1, "http://[::1]"));
assertTrue(checkSameOrigin("[::1]", 8080, "http://[::1]:8080"));
assertTrue(checkSameOrigin("[2001:0db8:0000:85a3:0000:0000:ac1f:8001]", -1, "http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]"));
assertTrue(checkSameOrigin("[2001:0db8:0000:85a3:0000:0000:ac1f:8001]", 8080, "http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]:8080"));
assertTrue(checkSameOrigin(
"[2001:0db8:0000:85a3:0000:0000:ac1f:8001]", -1,
"http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]"));
assertTrue(checkSameOrigin(
"[2001:0db8:0000:85a3:0000:0000:ac1f:8001]", 8080,
"http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]:8080"));
assertFalse(checkSameOrigin("[::1]", -1, "http://[::1]:8080"));
assertFalse(checkSameOrigin("[::1]", 8080, "http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]:8080"));
assertFalse(checkSameOrigin("[::1]", 8080,
"http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]:8080"));
}

View File

@@ -33,7 +33,6 @@ import static org.junit.Assert.fail;
/**
* Exercise the {@link PathPatternParser}.
*
* @author Andy Clement
*/
public class PathPatternParserTests {
@@ -62,7 +61,8 @@ public class PathPatternParserTests {
public void multiwildcardPattern() {
pathPattern = checkStructure("/**");
assertPathElements(pathPattern, WildcardTheRestPathElement.class);
pathPattern = checkStructure("/**acb"); // this is not double wildcard use, it is / then **acb (an odd, unnecessary use of double *)
// this is not double wildcard, it's / then **acb (an odd, unnecessary use of double *)
pathPattern = checkStructure("/**acb");
assertPathElements(pathPattern, SeparatorPathElement.class, RegexPathElement.class);
}
@@ -122,33 +122,40 @@ public class PathPatternParserTests {
checkError("/{var:a{{1,2}}}", 6, PatternMessage.REGEX_PATTERN_SYNTAX_EXCEPTION);
pathPattern = checkStructure("/{var:\\\\}");
assertEquals(CaptureVariablePathElement.class.getName(), pathPattern.getHeadSection().next.getClass().getName());
PathElement next = pathPattern.getHeadSection().next;
assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName());
assertMatches(pathPattern,"/\\");
pathPattern = checkStructure("/{var:\\/}");
assertEquals(CaptureVariablePathElement.class.getName(), pathPattern.getHeadSection().next.getClass().getName());
next = pathPattern.getHeadSection().next;
assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName());
assertNoMatch(pathPattern,"/aaa");
pathPattern = checkStructure("/{var:a{1,2}}");
assertEquals(CaptureVariablePathElement.class.getName(), pathPattern.getHeadSection().next.getClass().getName());
next = pathPattern.getHeadSection().next;
assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName());
pathPattern = checkStructure("/{var:[^\\/]*}");
assertEquals(CaptureVariablePathElement.class.getName(), pathPattern.getHeadSection().next.getClass().getName());
next = pathPattern.getHeadSection().next;
assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName());
PathPattern.PathMatchInfo result = matchAndExtract(pathPattern,"/foo");
assertEquals("foo", result.getUriVariables().get("var"));
pathPattern = checkStructure("/{var:\\[*}");
assertEquals(CaptureVariablePathElement.class.getName(), pathPattern.getHeadSection().next.getClass().getName());
next = pathPattern.getHeadSection().next;
assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName());
result = matchAndExtract(pathPattern,"/[[[");
assertEquals("[[[", result.getUriVariables().get("var"));
pathPattern = checkStructure("/{var:[\\{]*}");
assertEquals(CaptureVariablePathElement.class.getName(), pathPattern.getHeadSection().next.getClass().getName());
next = pathPattern.getHeadSection().next;
assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName());
result = matchAndExtract(pathPattern,"/{{{");
assertEquals("{{{", result.getUriVariables().get("var"));
pathPattern = checkStructure("/{var:[\\}]*}");
assertEquals(CaptureVariablePathElement.class.getName(), pathPattern.getHeadSection().next.getClass().getName());
next = pathPattern.getHeadSection().next;
assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName());
result = matchAndExtract(pathPattern,"/}}}");
assertEquals("}}}", result.getUriVariables().get("var"));
@@ -159,7 +166,8 @@ public class PathPatternParserTests {
checkStructure("*/");
checkStructure("/*/");
pathPattern = checkStructure("/*a*/");
assertEquals(RegexPathElement.class.getName(), pathPattern.getHeadSection().next.getClass().getName());
next = pathPattern.getHeadSection().next;
assertEquals(RegexPathElement.class.getName(), next.getClass().getName());
pathPattern = checkStructure("*/");
assertEquals(WildcardPathElement.class.getName(), pathPattern.getHeadSection().getClass().getName());
checkError("{foo}_{foo}", 0, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "foo");
@@ -308,12 +316,12 @@ public class PathPatternParserTests {
public void multipleSeparatorPatterns() {
pathPattern = checkStructure("///aaa");
assertEquals(6, pathPattern.getNormalizedLength());
assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class,
LiteralPathElement.class);
assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class,
SeparatorPathElement.class, LiteralPathElement.class);
pathPattern = checkStructure("///aaa////aaa/b");
assertEquals(15, pathPattern.getNormalizedLength());
assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class,
LiteralPathElement.class, SeparatorPathElement.class,
assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class,
SeparatorPathElement.class, LiteralPathElement.class, SeparatorPathElement.class,
SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class,
LiteralPathElement.class, SeparatorPathElement.class, LiteralPathElement.class);
pathPattern = checkStructure("/////**");
@@ -421,7 +429,9 @@ public class PathPatternParserTests {
return pp;
}
private void checkError(String pattern, int expectedPos, PatternMessage expectedMessage, String... expectedInserts) {
private void checkError(String pattern, int expectedPos, PatternMessage expectedMessage,
String... expectedInserts) {
try {
pathPattern = parse(pattern);
fail("Expected to fail");

View File

@@ -329,13 +329,16 @@ public class PathPatternTests {
// With a /** on the end have to check if there is any more data post
// 'the match' it starts with a separator
assertNull(parse("/resource/**").matchStartOfPath(toPathContainer("/resourceX")));
assertEquals("",parse("/resource/**").matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value());
assertEquals("",parse("/resource/**")
.matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value());
// Similar to above for the capture-the-rest variant
assertNull(parse("/resource/{*foo}").matchStartOfPath(toPathContainer("/resourceX")));
assertEquals("",parse("/resource/{*foo}").matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value());
assertEquals("", parse("/resource/{*foo}")
.matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value());
PathPattern.PathRemainingMatchInfo pri = parse("/aaa/{bbb}/c?d/e*f/*/g").matchStartOfPath(toPathContainer("/aaa/b/ccd/ef/x/g/i"));
PathPattern.PathRemainingMatchInfo pri = parse("/aaa/{bbb}/c?d/e*f/*/g")
.matchStartOfPath(toPathContainer("/aaa/b/ccd/ef/x/g/i"));
assertNotNull(pri);
assertEquals("/i",pri.getPathRemaining().value());
assertEquals("b",pri.getUriVariables().get("bbb"));
@@ -397,7 +400,8 @@ public class PathPatternTests {
@Test
public void multipleSeparatorsInPattern() {
PathPattern pp = parse("a//b//c");
assertEquals("Literal(a) Separator(/) Separator(/) Literal(b) Separator(/) Separator(/) Literal(c)",pp.toChainString());
assertEquals("Literal(a) Separator(/) Separator(/) Literal(b) Separator(/) Separator(/) Literal(c)",
pp.toChainString());
assertMatches(pp,"a//b//c");
assertEquals("Literal(a) Separator(/) WildcardTheRest(/**)",parse("a//**").toChainString());
checkMatches("///abc", "///abc");
@@ -812,7 +816,8 @@ public class PathPatternTests {
assertEquals("com.example", result.getUriVariables().get("symbolicName"));
assertEquals("1.0.0", result.getUriVariables().get("version"));
p = pp.parse("{symbolicName:[\\w\\.]+}-sources-{version:[\\d\\.]+}-{year:\\d{4}}{month:\\d{2}}{day:\\d{2}}.jar");
p = pp.parse("{symbolicName:[\\w\\.]+}-sources-" +
"{version:[\\d\\.]+}-{year:\\d{4}}{month:\\d{2}}{day:\\d{2}}.jar");
result = matchAndExtract(p,"com.example-sources-1.0.0-20100220.jar");
assertEquals("com.example", result.getUriVariables().get("symbolicName"));
assertEquals("1.0.0", result.getUriVariables().get("version"));

View File

@@ -84,7 +84,9 @@ public abstract class BodyExtractors {
* @param <T> the element type
* @return a {@code BodyExtractor} that reads a mono
*/
public static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(ParameterizedTypeReference<T> typeReference) {
public static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(
ParameterizedTypeReference<T> typeReference) {
Assert.notNull(typeReference, "'typeReference' must not be null");
return toMono(ResolvableType.forType(typeReference.getType()));
}
@@ -134,7 +136,9 @@ public abstract class BodyExtractors {
* @param <T> the element type
* @return a {@code BodyExtractor} that reads a flux
*/
public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(ParameterizedTypeReference<T> typeReference) {
public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(
ParameterizedTypeReference<T> typeReference) {
Assert.notNull(typeReference, "'typeReference' must not be null");
return toFlux(ResolvableType.forType(typeReference.getType()));
}
@@ -174,12 +178,13 @@ public abstract class BodyExtractors {
// ReactiveHttpInputMessage like other methods, since reading form data only typically happens on
// the server-side
public static BodyExtractor<Mono<MultiValueMap<String, String>>, ServerHttpRequest> toFormData() {
return (serverRequest, context) -> {
HttpMessageReader<MultiValueMap<String, String>> messageReader =
messageReader(FORM_MAP_TYPE, MediaType.APPLICATION_FORM_URLENCODED, context);
return (request, context) -> {
ResolvableType type = FORM_MAP_TYPE;
HttpMessageReader<MultiValueMap<String, String>> reader =
messageReader(type, MediaType.APPLICATION_FORM_URLENCODED, context);
return context.serverResponse()
.map(serverResponse -> messageReader.readMono(FORM_MAP_TYPE, FORM_MAP_TYPE, serverRequest, serverResponse, context.hints()))
.orElseGet(() -> messageReader.readMono(FORM_MAP_TYPE, serverRequest, context.hints()));
.map(response -> reader.readMono(type, type, request, response, context.hints()))
.orElseGet(() -> reader.readMono(type, request, context.hints()));
};
}
@@ -193,12 +198,12 @@ public abstract class BodyExtractors {
// the server-side
public static BodyExtractor<Mono<MultiValueMap<String, Part>>, ServerHttpRequest> toMultipartData() {
return (serverRequest, context) -> {
HttpMessageReader<MultiValueMap<String, Part>> messageReader =
messageReader(MULTIPART_MAP_TYPE, MediaType.MULTIPART_FORM_DATA, context);
ResolvableType type = MULTIPART_MAP_TYPE;
HttpMessageReader<MultiValueMap<String, Part>> reader =
messageReader(type, MediaType.MULTIPART_FORM_DATA, context);
return context.serverResponse()
.map(serverResponse -> messageReader.readMono(MULTIPART_MAP_TYPE,
MULTIPART_MAP_TYPE, serverRequest, serverResponse, context.hints()))
.orElseGet(() -> messageReader.readMono(MULTIPART_MAP_TYPE, serverRequest, context.hints()));
.map(response -> reader.readMono(type, type, serverRequest, response, context.hints()))
.orElseGet(() -> reader.readMono(type, serverRequest, context.hints()));
};
}
@@ -212,11 +217,11 @@ public abstract class BodyExtractors {
// the server-side
public static BodyExtractor<Flux<Part>, ServerHttpRequest> toParts() {
return (serverRequest, context) -> {
HttpMessageReader<Part> messageReader =
messageReader(PART_TYPE, MediaType.MULTIPART_FORM_DATA, context);
ResolvableType type = PART_TYPE;
HttpMessageReader<Part> reader = messageReader(type, MediaType.MULTIPART_FORM_DATA, context);
return context.serverResponse()
.map(serverResponse -> messageReader.read(PART_TYPE, PART_TYPE, serverRequest, serverResponse, context.hints()))
.orElseGet(() -> messageReader.read(PART_TYPE, serverRequest, context.hints()));
.map(response -> reader.read(type, type, serverRequest, response, context.hints()))
.orElseGet(() -> reader.read(type, serverRequest, context.hints()));
};
}

View File

@@ -298,7 +298,9 @@ class DefaultWebClient implements WebClient {
}
@Override
public <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher, ParameterizedTypeReference<T> typeReference) {
public <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher,
ParameterizedTypeReference<T> typeReference) {
this.inserter = BodyInserters.fromPublisher(publisher, typeReference);
return this;
}

View File

@@ -42,10 +42,11 @@ import org.springframework.util.Assert;
public abstract class ExchangeFilterFunctions {
/**
* Name of the {@link ClientRequest} attribute that contains the {@link Credentials}, as used by
* {@link #basicAuthentication()}
* Name of the {@link ClientRequest} attribute that contains the
* {@link Credentials}, as used by {@link #basicAuthentication()}.
*/
public static final String BASIC_AUTHENTICATION_CREDENTIALS_ATTRIBUTE = ExchangeFilterFunctions.class.getName() + ".basicAuthenticationCredentials";
public static final String BASIC_AUTHENTICATION_CREDENTIALS_ATTRIBUTE =
ExchangeFilterFunctions.class.getName() + ".basicAuthenticationCredentials";
/**

View File

@@ -86,7 +86,9 @@ public interface EntityResponse<T> extends ServerResponse {
* @param <P> the type of the {@code Publisher}
* @return the created builder
*/
static <T, P extends Publisher<T>> Builder<P> fromPublisher(P publisher, ParameterizedTypeReference<T> typeReference) {
static <T, P extends Publisher<T>> Builder<P> fromPublisher(P publisher,
ParameterizedTypeReference<T> typeReference) {
return new DefaultEntityResponseBuilder<>(publisher,
BodyInserters.fromPublisher(publisher, typeReference));
}

View File

@@ -71,8 +71,9 @@ public final class RequestMappingInfo implements RequestCondition<RequestMapping
private final RequestConditionHolder customConditionHolder;
public RequestMappingInfo(@Nullable String name, @Nullable PatternsRequestCondition patterns, @Nullable RequestMethodsRequestCondition methods,
@Nullable ParamsRequestCondition params, @Nullable HeadersRequestCondition headers, @Nullable ConsumesRequestCondition consumes,
public RequestMappingInfo(@Nullable String name, @Nullable PatternsRequestCondition patterns,
@Nullable RequestMethodsRequestCondition methods, @Nullable ParamsRequestCondition params,
@Nullable HeadersRequestCondition headers, @Nullable ConsumesRequestCondition consumes,
@Nullable ProducesRequestCondition produces, @Nullable RequestCondition<?> custom) {
this.name = (StringUtils.hasText(name) ? name : null);
@@ -88,8 +89,9 @@ public final class RequestMappingInfo implements RequestCondition<RequestMapping
/**
* Creates a new instance with the given request conditions.
*/
public RequestMappingInfo(@Nullable PatternsRequestCondition patterns, @Nullable RequestMethodsRequestCondition methods,
@Nullable ParamsRequestCondition params, @Nullable HeadersRequestCondition headers, @Nullable ConsumesRequestCondition consumes,
public RequestMappingInfo(@Nullable PatternsRequestCondition patterns,
@Nullable RequestMethodsRequestCondition methods, @Nullable ParamsRequestCondition params,
@Nullable HeadersRequestCondition headers, @Nullable ConsumesRequestCondition consumes,
@Nullable ProducesRequestCondition produces, @Nullable RequestCondition<?> custom) {
this(null, patterns, methods, params, headers, consumes, produces, custom);

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