Browse Source

Broadly remove deprecated core classes and methods

Issue: SPR-14430
pull/1099/head
Juergen Hoeller 10 years ago
parent
commit
b5db5d3aac
  1. 7
      spring-aspects/src/test/java/org/springframework/cache/config/SomeKeyGenerator.java
  2. 36
      spring-beans/src/main/java/org/springframework/beans/factory/UnsatisfiedDependencyException.java
  3. 18
      spring-beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java
  4. 11
      spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java
  5. 9
      spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java
  6. 8
      spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
  7. 67
      spring-context/src/main/java/org/springframework/cache/interceptor/DefaultKeyGenerator.java
  8. 17
      spring-context/src/main/java/org/springframework/cache/support/AbstractCacheManager.java
  9. 31
      spring-context/src/main/java/org/springframework/format/number/CurrencyFormatter.java
  10. 46
      spring-context/src/main/java/org/springframework/format/number/NumberFormatter.java
  11. 31
      spring-context/src/main/java/org/springframework/format/number/PercentFormatter.java
  12. 13
      spring-context/src/main/java/org/springframework/jmx/support/JmxUtils.java
  13. 65
      spring-context/src/main/java/org/springframework/jmx/support/MBeanRegistrationSupport.java
  14. 22
      spring-context/src/main/java/org/springframework/jmx/support/RegistrationPolicy.java
  15. 4
      spring-context/src/main/java/org/springframework/scripting/config/LangNamespaceUtils.java
  16. 4
      spring-context/src/main/java/org/springframework/scripting/config/ScriptingDefaultsParser.java
  17. 7
      spring-context/src/test/java/org/springframework/cache/config/SomeKeyGenerator.java
  18. 119
      spring-context/src/test/java/org/springframework/cache/interceptor/DefaultKeyGeneratorTests.java
  19. 4
      spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java
  20. 53
      spring-context/src/test/java/org/springframework/jmx/support/RegistrationPolicyTests.java
  21. 118
      spring-core/src/main/java/org/springframework/core/JdkVersion.java
  22. 47
      spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java
  23. 30
      spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java
  24. 6
      spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java
  25. 6
      spring-core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java
  26. 13
      spring-core/src/main/java/org/springframework/core/env/PropertyResolver.java
  27. 57
      spring-core/src/main/java/org/springframework/core/env/PropertySourcesPropertyResolver.java
  28. 26
      spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java
  29. 11
      spring-core/src/main/java/org/springframework/util/MimeType.java
  30. 6
      spring-core/src/test/java/org/springframework/core/env/DummyEnvironment.java
  31. 40
      spring-core/src/test/java/org/springframework/core/env/PropertySourceTests.java
  32. 73
      spring-core/src/test/java/org/springframework/core/env/PropertySourcesPropertyResolverTests.java
  33. 69
      spring-jms/src/main/java/org/springframework/jms/support/converter/MappingJackson2MessageConverter.java
  34. 16
      spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java
  35. 26
      spring-messaging/src/main/java/org/springframework/messaging/converter/AbstractMessageConverter.java
  36. 16
      spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolver.java
  37. 12
      spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java
  38. 79
      spring-messaging/src/main/java/org/springframework/messaging/simp/user/DefaultUserSessionRegistry.java
  39. 59
      spring-messaging/src/main/java/org/springframework/messaging/simp/user/UserSessionRegistry.java
  40. 136
      spring-messaging/src/main/java/org/springframework/messaging/simp/user/UserSessionRegistryAdapter.java
  41. 136
      spring-messaging/src/test/java/org/springframework/messaging/converter/AbstractMessageConverterTests.java
  42. 7
      spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java
  43. 30
      spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java
  44. 152
      spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java
  45. 66
      spring-test/src/main/java/org/springframework/test/util/MatcherAssertionErrors.java
  46. 29
      spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnection.java
  47. 19
      spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionBuilderSupport.java
  48. 6
      spring-test/src/test/java/org/springframework/test/context/web/AnnotationConfigWebContextLoaderTests.java
  49. 6
      spring-test/src/test/java/org/springframework/test/context/web/GenericXmlWebContextLoaderTests.java
  50. 64
      spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsIntegrationTests.java
  51. 13
      spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionTests.java
  52. 40
      spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java
  53. 65
      spring-web/src/main/java/org/springframework/remoting/jaxws/AbstractJaxWsServiceExporter.java
  54. 72
      spring-web/src/main/java/org/springframework/remoting/jaxws/JaxWsPortClientInterceptor.java
  55. 5
      spring-web/src/main/java/org/springframework/remoting/jaxws/JaxWsPortProxyFactoryBean.java
  56. 1
      spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java
  57. 6
      spring-web/src/main/java/org/springframework/remoting/jaxws/SimpleJaxWsServiceExporter.java
  58. 19
      spring-web/src/main/java/org/springframework/web/util/WebUtils.java
  59. 21
      spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java
  60. 5
      spring-webmvc/src/main/java/org/springframework/web/servlet/config/ViewResolversBeanDefinitionParser.java
  61. 20
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java
  62. 27
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java
  63. 118
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/AbstractUrlMethodNameResolver.java
  64. 126
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/InternalPathMethodNameResolver.java
  65. 47
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/MethodNameResolver.java
  66. 657
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/MultiActionController.java
  67. 80
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/NoSuchRequestHandlingMethodException.java
  68. 224
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java
  69. 101
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/PropertiesMethodNameResolver.java
  70. 13
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/package-info.java
  71. 158
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/AbstractControllerUrlHandlerMapping.java
  72. 45
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/AnnotationControllerTypePredicate.java
  73. 96
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/ControllerBeanNameHandlerMapping.java
  74. 183
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/ControllerClassNameHandlerMapping.java
  75. 40
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/ControllerTypePredicate.java
  76. 33
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.java
  77. 19
      spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java
  78. 49
      spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContextUtils.java
  79. 32
      spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java
  80. 5
      spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java
  81. 32
      spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java
  82. 5
      spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java
  83. 27
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/AdminController.java
  84. 52
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/BookController.java
  85. 27
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/BuyForm.java
  86. 16
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/CglibProxyControllerTests.java
  87. 40
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ControllerClassNameController.java
  88. 128
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ControllerClassNameHandlerMappingTests.java
  89. 37
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/IndexController.java
  90. 17
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/JdkProxyControllerTests.java
  91. 53
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/MethodNameDispatchingController.java
  92. 37
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/WelcomeController.java
  93. 26
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/AdminController.java
  94. 32
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/BuyForm.java
  95. 34
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/Controller.java
  96. 92
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerBeanNameHandlerMappingTests.java
  97. 130
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerClassNameHandlerMappingTests.java
  98. 35
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/WelcomeController.java
  99. 8
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandlerTests.java
  100. 45
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java
  101. Some files were not shown because too many files have changed in this diff Show More

7
spring-aspects/src/test/java/org/springframework/cache/config/SomeKeyGenerator.java vendored

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,8 +16,7 @@ @@ -16,8 +16,7 @@
package org.springframework.cache.config;
import org.springframework.cache.interceptor.DefaultKeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
@SuppressWarnings("deprecation")
public class SomeKeyGenerator extends DefaultKeyGenerator {
public class SomeKeyGenerator extends SimpleKeyGenerator {
}

36
spring-beans/src/main/java/org/springframework/beans/factory/UnsatisfiedDependencyException.java

@ -93,42 +93,6 @@ public class UnsatisfiedDependencyException extends BeanCreationException { @@ -93,42 +93,6 @@ public class UnsatisfiedDependencyException extends BeanCreationException {
initCause(ex);
}
/**
* Create a new UnsatisfiedDependencyException.
* @param resourceDescription description of the resource that the bean definition came from
* @param beanName the name of the bean requested
* @param ctorArgIndex the index of the constructor argument that couldn't be satisfied
* @param ctorArgType the type of the constructor argument that couldn't be satisfied
* @param msg the detail message
* @deprecated in favor of {@link #UnsatisfiedDependencyException(String, String, InjectionPoint, String)}
*/
@Deprecated
public UnsatisfiedDependencyException(
String resourceDescription, String beanName, int ctorArgIndex, Class<?> ctorArgType, String msg) {
super(resourceDescription, beanName,
"Unsatisfied dependency expressed through constructor argument with index " +
ctorArgIndex + " of type [" + ClassUtils.getQualifiedName(ctorArgType) + "]" +
(msg != null ? ": " + msg : ""));
}
/**
* Create a new UnsatisfiedDependencyException.
* @param resourceDescription description of the resource that the bean definition came from
* @param beanName the name of the bean requested
* @param ctorArgIndex the index of the constructor argument that couldn't be satisfied
* @param ctorArgType the type of the constructor argument that couldn't be satisfied
* @param ex the bean creation exception that indicated the unsatisfied dependency
* @deprecated in favor of {@link #UnsatisfiedDependencyException(String, String, InjectionPoint, BeansException)}
*/
@Deprecated
public UnsatisfiedDependencyException(
String resourceDescription, String beanName, int ctorArgIndex, Class<?> ctorArgType, BeansException ex) {
this(resourceDescription, beanName, ctorArgIndex, ctorArgType, (ex != null ? ex.getMessage() : ""));
initCause(ex);
}
/**
* Return the injection point (field or method/constructor parameter), if known.

18
spring-beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java

@ -222,24 +222,6 @@ public class PropertyPlaceholderConfigurer extends PlaceholderConfigurerSupport @@ -222,24 +222,6 @@ public class PropertyPlaceholderConfigurer extends PlaceholderConfigurerSupport
doProcessProperties(beanFactoryToProcess, valueResolver);
}
/**
* Parse the given String value for placeholder resolution.
* @param strVal the String value to parse
* @param props the Properties to resolve placeholders against
* @param visitedPlaceholders the placeholders that have already been visited
* during the current resolution attempt (ignored in this version of the code)
* @deprecated as of Spring 3.0, in favor of using {@link #resolvePlaceholder}
* with {@link org.springframework.util.PropertyPlaceholderHelper}.
* Only retained for compatibility with Spring 2.5 extensions.
*/
@Deprecated
protected String parseStringValue(String strVal, Properties props, Set<?> visitedPlaceholders) {
PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(
placeholderPrefix, placeholderSuffix, valueSeparator, ignoreUnresolvablePlaceholders);
PlaceholderResolver resolver = new PropertyPlaceholderConfigurerResolver(props);
return helper.replacePlaceholders(strVal, resolver);
}
private class PlaceholderResolvingStringValueResolver implements StringValueResolver {

11
spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java

@ -166,17 +166,6 @@ public class BeanDefinitionBuilder { @@ -166,17 +166,6 @@ public class BeanDefinitionBuilder {
return this;
}
/**
* Add an indexed constructor arg value. The current index is tracked internally
* and all additions are at the present point.
* @deprecated since Spring 2.5, in favor of {@link #addConstructorArgValue}.
* This variant just remains around for Spring Security 2.x compatibility.
*/
@Deprecated
public BeanDefinitionBuilder addConstructorArg(Object value) {
return addConstructorArgValue(value);
}
/**
* Add an indexed constructor arg value. The current index is tracked internally
* and all additions are at the present point.

9
spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java

@ -270,15 +270,6 @@ public class BeanDefinitionParserDelegate { @@ -270,15 +270,6 @@ public class BeanDefinitionParserDelegate {
return this.readerContext;
}
/**
* Get the {@link Environment} associated with this helper instance.
* @deprecated in favor of {@link XmlReaderContext#getEnvironment()}
*/
@Deprecated
public final Environment getEnvironment() {
return this.readerContext.getEnvironment();
}
/**
* Invoke the {@link org.springframework.beans.factory.parsing.SourceExtractor} to pull the
* source metadata from the supplied {@link Element}.

8
spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java vendored

@ -172,14 +172,6 @@ public abstract class CacheAspectSupport extends AbstractCacheInvoker @@ -172,14 +172,6 @@ public abstract class CacheAspectSupport extends AbstractCacheInvoker
this.beanFactory = beanFactory;
}
/**
* @deprecated as of 4.3, in favor of {@link #setBeanFactory}
*/
@Deprecated
public void setApplicationContext(ApplicationContext applicationContext) {
this.beanFactory = applicationContext;
}
@Override
public void afterPropertiesSet() {

67
spring-context/src/main/java/org/springframework/cache/interceptor/DefaultKeyGenerator.java vendored

@ -1,67 +0,0 @@ @@ -1,67 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.interceptor;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Default key generator. Returns {@value #NO_PARAM_KEY} if no
* parameters are provided, the parameter itself if only one is given or
* a hash code computed from all given parameters' hash code values.
* Uses the constant value {@value #NULL_PARAM_KEY} for any
* {@code null} parameters given.
*
* <p>NOTE: As this implementation returns only a hash of the parameters
* it is possible for key collisions to occur. Since Spring 4.0 the
* {@link SimpleKeyGenerator} is used when no explicit key generator
* has been defined. This class remains for applications that do not
* wish to migrate to the {@link SimpleKeyGenerator}.
*
* @author Costin Leau
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
* @deprecated as of Spring 4.0, in favor of {@link SimpleKeyGenerator}
* or custom {@link KeyGenerator} implementations based on hash codes
*/
@Deprecated
public class DefaultKeyGenerator implements KeyGenerator {
public static final int NO_PARAM_KEY = 0;
public static final int NULL_PARAM_KEY = 53;
@Override
public Object generate(Object target, Method method, Object... params) {
if (params.length == 0) {
return NO_PARAM_KEY;
}
if (params.length == 1) {
Object param = params[0];
if (param == null) {
return NULL_PARAM_KEY;
}
if (!param.getClass().isArray()) {
return param;
}
}
return Arrays.deepHashCode(params);
}
}

17
spring-context/src/main/java/org/springframework/cache/support/AbstractCacheManager.java vendored

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -128,21 +128,6 @@ public abstract class AbstractCacheManager implements CacheManager, Initializing @@ -128,21 +128,6 @@ public abstract class AbstractCacheManager implements CacheManager, Initializing
return this.cacheMap.get(name);
}
/**
* Dynamically register an additional Cache with this manager.
* @param cache the Cache to register
* @deprecated as of Spring 4.3, in favor of {@link #getMissingCache(String)}
*/
@Deprecated
protected final void addCache(Cache cache) {
String name = cache.getName();
synchronized (this.cacheMap) {
if (this.cacheMap.put(name, decorateCache(cache)) == null) {
updateCacheNames(name);
}
}
}
/**
* Update the exposed {@link #cacheNames} set with the given name.
* <p>This will always be called within a full {@link #cacheMap} lock

31
spring-context/src/main/java/org/springframework/format/number/CurrencyFormatter.java

@ -1,31 +0,0 @@ @@ -1,31 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.format.number;
/**
* A BigDecimal formatter for currency values.
*
* @author Keith Donald
* @author Juergen Hoeller
* @since 4.2
* @deprecated as of Spring 4.2, in favor of the more clearly named
* {@link CurrencyStyleFormatter}
*/
@Deprecated
public class CurrencyFormatter extends CurrencyStyleFormatter {
}

46
spring-context/src/main/java/org/springframework/format/number/NumberFormatter.java

@ -1,46 +0,0 @@ @@ -1,46 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.format.number;
/**
* A general-purpose Number formatter.
*
* @author Keith Donald
* @author Juergen Hoeller
* @since 3.0
* @deprecated as of Spring 4.2, in favor of the more clearly named
* {@link NumberStyleFormatter}
*/
@Deprecated
public class NumberFormatter extends NumberStyleFormatter {
/**
* Create a new NumberFormatter without a pattern.
*/
public NumberFormatter() {
}
/**
* Create a new NumberFormatter with the specified pattern.
* @param pattern the format pattern
* @see #setPattern
*/
public NumberFormatter(String pattern) {
super(pattern);
}
}

31
spring-context/src/main/java/org/springframework/format/number/PercentFormatter.java

@ -1,31 +0,0 @@ @@ -1,31 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.format.number;
/**
* A Number formatter for percent values.
*
* @author Keith Donald
* @author Juergen Hoeller
* @since 3.0
* @deprecated as of Spring 4.2, in favor of the more clearly named
* {@link PercentStyleFormatter}
*/
@Deprecated
public class PercentFormatter extends PercentStyleFormatter {
}

13
spring-context/src/main/java/org/springframework/jmx/support/JmxUtils.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -301,15 +301,4 @@ public abstract class JmxUtils { @@ -301,15 +301,4 @@ public abstract class JmxUtils {
return getMXBeanInterface(clazz.getSuperclass());
}
/**
* Check whether MXBean support is available, i.e. whether we're running
* on Java 6 or above.
* @return {@code true} if available; {@code false} otherwise
* @deprecated as of Spring 4.0, since Java 6 is required anyway now
*/
@Deprecated
public static boolean isMXBeanSupportAvailable() {
return true;
}
}

65
spring-context/src/main/java/org/springframework/jmx/support/MBeanRegistrationSupport.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -68,37 +68,6 @@ import org.springframework.util.Assert; @@ -68,37 +68,6 @@ import org.springframework.util.Assert;
*/
public class MBeanRegistrationSupport {
/**
* Constant indicating that registration should fail when
* attempting to register an MBean under a name that already exists.
* <p>This is the default registration behavior.
* @deprecated since Spring 3.2, in favor of {@link RegistrationPolicy#FAIL_ON_EXISTING}
*/
@Deprecated
public static final int REGISTRATION_FAIL_ON_EXISTING = 0;
/**
* Constant indicating that registration should ignore the affected MBean
* when attempting to register an MBean under a name that already exists.
* @deprecated since Spring 3.2, in favor of {@link RegistrationPolicy#IGNORE_EXISTING}
*/
@Deprecated
public static final int REGISTRATION_IGNORE_EXISTING = 1;
/**
* Constant indicating that registration should replace the affected MBean
* when attempting to register an MBean under a name that already exists.
* @deprecated since Spring 3.2, in favor of {@link RegistrationPolicy#REPLACE_EXISTING}
*/
@Deprecated
public static final int REGISTRATION_REPLACE_EXISTING = 2;
/**
* Constants for this class.
*/
private static final Constants constants = new Constants(MBeanRegistrationSupport.class);
/**
* {@code Log} instance for this class.
*/
@ -137,35 +106,6 @@ public class MBeanRegistrationSupport { @@ -137,35 +106,6 @@ public class MBeanRegistrationSupport {
return this.server;
}
/**
* Set the registration behavior by the name of the corresponding constant,
* e.g. "REGISTRATION_IGNORE_EXISTING".
* @see #setRegistrationBehavior
* @see #REGISTRATION_FAIL_ON_EXISTING
* @see #REGISTRATION_IGNORE_EXISTING
* @see #REGISTRATION_REPLACE_EXISTING
* @deprecated since Spring 3.2, in favor of {@link #setRegistrationPolicy(RegistrationPolicy)}
*/
@Deprecated
public void setRegistrationBehaviorName(String registrationBehavior) {
setRegistrationBehavior(constants.asNumber(registrationBehavior).intValue());
}
/**
* Specify what action should be taken when attempting to register an MBean
* under an {@link javax.management.ObjectName} that already exists.
* <p>Default is REGISTRATION_FAIL_ON_EXISTING.
* @see #setRegistrationBehaviorName(String)
* @see #REGISTRATION_FAIL_ON_EXISTING
* @see #REGISTRATION_IGNORE_EXISTING
* @see #REGISTRATION_REPLACE_EXISTING
* @deprecated since Spring 3.2, in favor of {@link #setRegistrationPolicy(RegistrationPolicy)}
*/
@Deprecated
public void setRegistrationBehavior(int registrationBehavior) {
setRegistrationPolicy(RegistrationPolicy.valueOf(registrationBehavior));
}
/**
* The policy to use when attempting to register an MBean
* under an {@link javax.management.ObjectName} that already exists.
@ -180,8 +120,7 @@ public class MBeanRegistrationSupport { @@ -180,8 +120,7 @@ public class MBeanRegistrationSupport {
/**
* Actually register the MBean with the server. The behavior when encountering
* an existing MBean can be configured using the {@link #setRegistrationBehavior(int)}
* and {@link #setRegistrationBehaviorName(String)} methods.
* an existing MBean can be configured using {@link #setRegistrationPolicy}.
* @param mbean the MBean instance
* @param objectName the suggested ObjectName for the MBean
* @throws JMException if the registration failed

22
spring-context/src/main/java/org/springframework/jmx/support/RegistrationPolicy.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -44,24 +44,4 @@ public enum RegistrationPolicy { @@ -44,24 +44,4 @@ public enum RegistrationPolicy {
*/
REPLACE_EXISTING;
/**
* Translate from an {@link MBeanRegistrationSupport} registration behavior constant
* to a {@link RegistrationPolicy} enum value.
* @param registrationBehavior one of the now-deprecated REGISTRATION_* constants
* available in {@link MBeanRegistrationSupport}.
*/
@SuppressWarnings("deprecation")
static RegistrationPolicy valueOf(int registrationBehavior) {
switch (registrationBehavior) {
case MBeanRegistrationSupport.REGISTRATION_IGNORE_EXISTING:
return RegistrationPolicy.IGNORE_EXISTING;
case MBeanRegistrationSupport.REGISTRATION_REPLACE_EXISTING:
return RegistrationPolicy.REPLACE_EXISTING;
case MBeanRegistrationSupport.REGISTRATION_FAIL_ON_EXISTING:
return RegistrationPolicy.FAIL_ON_EXISTING;
}
throw new IllegalArgumentException(
"Unknown MBean registration behavior: " + registrationBehavior);
}
}

4
spring-context/src/main/java/org/springframework/scripting/config/LangNamespaceUtils.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -44,7 +44,7 @@ public abstract class LangNamespaceUtils { @@ -44,7 +44,7 @@ public abstract class LangNamespaceUtils {
* @return the {@link ScriptFactoryPostProcessor} bean definition (new or already registered)
*/
public static BeanDefinition registerScriptFactoryPostProcessorIfNecessary(BeanDefinitionRegistry registry) {
BeanDefinition beanDefinition = null;
BeanDefinition beanDefinition;
if (registry.containsBeanDefinition(SCRIPT_FACTORY_POST_PROCESSOR_BEAN_NAME)) {
beanDefinition = registry.getBeanDefinition(SCRIPT_FACTORY_POST_PROCESSOR_BEAN_NAME);
}

4
spring-context/src/main/java/org/springframework/scripting/config/ScriptingDefaultsParser.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,7 +28,7 @@ import org.springframework.util.StringUtils; @@ -28,7 +28,7 @@ import org.springframework.util.StringUtils;
* @author Mark Fisher
* @since 2.5
*/
public class ScriptingDefaultsParser implements BeanDefinitionParser {
class ScriptingDefaultsParser implements BeanDefinitionParser {
private static final String REFRESH_CHECK_DELAY_ATTRIBUTE = "refresh-check-delay";

7
spring-context/src/test/java/org/springframework/cache/config/SomeKeyGenerator.java vendored

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,8 +16,7 @@ @@ -16,8 +16,7 @@
package org.springframework.cache.config;
import org.springframework.cache.interceptor.DefaultKeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
@SuppressWarnings("deprecation")
public class SomeKeyGenerator extends DefaultKeyGenerator {
public class SomeKeyGenerator extends SimpleKeyGenerator {
}

119
spring-context/src/test/java/org/springframework/cache/interceptor/DefaultKeyGeneratorTests.java vendored

@ -1,119 +0,0 @@ @@ -1,119 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.interceptor;
import org.junit.Test;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
* Tests for {@link DefaultKeyGenerator}.
*
* @author Juergen Hoeller
* @author Stephane Nicoll
*/
public class DefaultKeyGeneratorTests {
private final DefaultKeyGenerator generator = new DefaultKeyGenerator();
@Test
public void noValues() {
Object k1 = generateKey(new Object[] {});
Object k2 = generateKey(new Object[] {});
Object k3 = generateKey(new Object[] { "different" });
assertThat(k1.hashCode(), equalTo(k2.hashCode()));
assertThat(k1.hashCode(), not(equalTo(k3.hashCode())));
assertThat(k1, equalTo(k2));
assertThat(k1, not(equalTo(k3)));
}
@Test
public void singleValue(){
Object k1 = generateKey(new Object[] { "a" });
Object k2 = generateKey(new Object[] { "a" });
Object k3 = generateKey(new Object[] { "different" });
assertThat(k1.hashCode(), equalTo(k2.hashCode()));
assertThat(k1.hashCode(), not(equalTo(k3.hashCode())));
assertThat(k1, equalTo(k2));
assertThat(k1, not(equalTo(k3)));
assertThat(k1, equalTo((Object) "a"));
}
@Test
public void multipleValues() {
Object k1 = generateKey(new Object[] { "a", 1, "b" });
Object k2 = generateKey(new Object[] { "a", 1, "b" });
Object k3 = generateKey(new Object[] { "b", 1, "a" });
assertThat(k1.hashCode(), equalTo(k2.hashCode()));
assertThat(k1.hashCode(), not(equalTo(k3.hashCode())));
assertThat(k1, equalTo(k2));
assertThat(k1, not(equalTo(k3)));
}
@Test
public void singleNullValue() {
Object k1 = generateKey(new Object[] { null });
Object k2 = generateKey(new Object[] { null });
Object k3 = generateKey(new Object[] { "different" });
assertThat(k1.hashCode(), equalTo(k2.hashCode()));
assertThat(k1.hashCode(), not(equalTo(k3.hashCode())));
assertThat(k1, equalTo(k2));
assertThat(k1, not(equalTo(k3)));
assertThat(k1, instanceOf(Integer.class));
}
@Test
public void multipleNullValues() {
Object k1 = generateKey(new Object[] { "a", null, "b", null });
Object k2 = generateKey(new Object[] { "a", null, "b", null });
Object k3 = generateKey(new Object[] { "a", null, "b" });
assertThat(k1.hashCode(), equalTo(k2.hashCode()));
assertThat(k1.hashCode(), not(equalTo(k3.hashCode())));
assertThat(k1, equalTo(k2));
assertThat(k1, not(equalTo(k3)));
}
@Test
public void plainArray() {
Object k1 = generateKey(new Object[] { new String[]{"a", "b"} });
Object k2 = generateKey(new Object[] { new String[]{"a", "b"} });
Object k3 = generateKey(new Object[] { new String[]{"b", "a"} });
assertThat(k1.hashCode(), equalTo(k2.hashCode()));
assertThat(k1.hashCode(), not(equalTo(k3.hashCode())));
assertThat(k1, equalTo(k2));
assertThat(k1, not(equalTo(k3)));
}
@Test
public void arrayWithExtraParameter() {
Object k1 = generateKey(new Object[] { new String[]{"a", "b"}, "c" });
Object k2 = generateKey(new Object[] { new String[]{"a", "b"}, "c" });
Object k3 = generateKey(new Object[] { new String[]{"b", "a"}, "c" });
assertThat(k1.hashCode(), equalTo(k2.hashCode()));
assertThat(k1.hashCode(), not(equalTo(k3.hashCode())));
assertThat(k1, equalTo(k2));
assertThat(k1, not(equalTo(k3)));
}
private Object generateKey(Object[] arguments) {
return this.generator.generate(null, null, arguments);
}
}

4
spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -302,7 +302,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { @@ -302,7 +302,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests {
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setRegistrationBehavior(MBeanExporter.REGISTRATION_IGNORE_EXISTING);
exporter.setRegistrationPolicy(RegistrationPolicy.IGNORE_EXISTING);
start(exporter);

53
spring-context/src/test/java/org/springframework/jmx/support/RegistrationPolicyTests.java

@ -1,53 +0,0 @@ @@ -1,53 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.support;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* Unit tests for {@link RegistrationPolicy}.
*
* @author Chris Beams
*/
public class RegistrationPolicyTests {
@Test
@SuppressWarnings("deprecation")
public void convertRegistrationBehaviorToRegistrationPolicy() {
assertThat(
RegistrationPolicy.valueOf(MBeanRegistrationSupport.REGISTRATION_FAIL_ON_EXISTING),
equalTo(RegistrationPolicy.FAIL_ON_EXISTING));
assertThat(
RegistrationPolicy.valueOf(MBeanRegistrationSupport.REGISTRATION_IGNORE_EXISTING),
equalTo(RegistrationPolicy.IGNORE_EXISTING));
assertThat(
RegistrationPolicy.valueOf(MBeanRegistrationSupport.REGISTRATION_REPLACE_EXISTING),
equalTo(RegistrationPolicy.REPLACE_EXISTING));
try {
RegistrationPolicy.valueOf(Integer.MAX_VALUE);
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().startsWith("Unknown MBean registration behavior"));
}
}
}

118
spring-core/src/main/java/org/springframework/core/JdkVersion.java

@ -1,118 +0,0 @@ @@ -1,118 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
/**
* Internal helper class used to find the Java/JVM version that Spring is
* operating on, to allow for automatically adapting to the present platform's
* capabilities.
*
* <p>Note that Spring requires JVM 1.6 or higher, as of Spring 4.0.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Rick Evans
* @author Sam Brannen
* @deprecated as of Spring 4.2.1, in favor of direct checks for the desired
* JDK API variants via reflection
*/
@Deprecated
public abstract class JdkVersion {
/**
* Constant identifying the 1.3.x JVM (JDK 1.3).
*/
public static final int JAVA_13 = 0;
/**
* Constant identifying the 1.4.x JVM (J2SE 1.4).
*/
public static final int JAVA_14 = 1;
/**
* Constant identifying the 1.5 JVM (Java 5).
*/
public static final int JAVA_15 = 2;
/**
* Constant identifying the 1.6 JVM (Java 6).
*/
public static final int JAVA_16 = 3;
/**
* Constant identifying the 1.7 JVM (Java 7).
*/
public static final int JAVA_17 = 4;
/**
* Constant identifying the 1.8 JVM (Java 8).
*/
public static final int JAVA_18 = 5;
/**
* Constant identifying the 1.9 JVM (Java 9).
*/
public static final int JAVA_19 = 6;
private static final String javaVersion;
private static final int majorJavaVersion;
static {
javaVersion = System.getProperty("java.version");
// version String should look like "1.4.2_10"
if (javaVersion.contains("1.9.")) {
majorJavaVersion = JAVA_19;
}
else if (javaVersion.contains("1.8.")) {
majorJavaVersion = JAVA_18;
}
else if (javaVersion.contains("1.7.")) {
majorJavaVersion = JAVA_17;
}
else {
// else leave 1.6 as default (it's either 1.6 or unknown)
majorJavaVersion = JAVA_16;
}
}
/**
* Return the full Java version string, as returned by
* {@code System.getProperty("java.version")}.
* @return the full Java version string
* @see System#getProperty(String)
*/
public static String getJavaVersion() {
return javaVersion;
}
/**
* Get the major version code. This means we can do things like
* {@code if (getMajorJavaVersion() >= JAVA_17)}.
* @return a code comparable to the {@code JAVA_XX} codes in this class
* @see #JAVA_16
* @see #JAVA_17
* @see #JAVA_18
* @see #JAVA_19
*/
public static int getMajorJavaVersion() {
return majorJavaVersion;
}
}

47
spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java

@ -295,24 +295,6 @@ public class AnnotatedElementUtils { @@ -295,24 +295,6 @@ public class AnnotatedElementUtils {
return Boolean.TRUE.equals(searchWithGetSemantics(element, null, annotationName, alwaysTrueAnnotationProcessor));
}
/**
* @deprecated As of Spring Framework 4.2, use {@link #getMergedAnnotationAttributes(AnnotatedElement, String)} instead.
*/
@Deprecated
public static AnnotationAttributes getAnnotationAttributes(AnnotatedElement element, String annotationName) {
return getMergedAnnotationAttributes(element, annotationName);
}
/**
* @deprecated As of Spring Framework 4.2, use {@link #getMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)} instead.
*/
@Deprecated
public static AnnotationAttributes getAnnotationAttributes(AnnotatedElement element, String annotationName,
boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
return getMergedAnnotationAttributes(element, annotationName, classValuesAsString, nestedAnnotationsAsMap);
}
/**
* Get the first annotation of the specified {@code annotationType} within
* the annotation hierarchy <em>above</em> the supplied {@code element} and
@ -731,35 +713,6 @@ public class AnnotatedElementUtils { @@ -731,35 +713,6 @@ public class AnnotatedElementUtils {
return AnnotationUtils.synthesizeAnnotation(attributes, annotationType, element);
}
/**
* Find the first annotation of the specified {@code annotationName} within
* the annotation hierarchy <em>above</em> the supplied {@code element},
* merge that annotation's attributes with <em>matching</em> attributes from
* annotations in lower levels of the annotation hierarchy, and synthesize
* the result back into an annotation of the specified {@code annotationName}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both
* within a single annotation and within the annotation hierarchy.
* <p>This method delegates to {@link #findMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)}
* (supplying {@code false} for {@code classValuesAsString} and {@code nestedAnnotationsAsMap})
* and {@link AnnotationUtils#synthesizeAnnotation(Map, Class, AnnotatedElement)}.
* <p>This method follows <em>find semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the annotation type to find
* @return the merged, synthesized {@code Annotation}, or {@code null} if not found
* @since 4.2
* @see #findMergedAnnotation(AnnotatedElement, Class)
* @see #findMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
* @see AnnotationUtils#synthesizeAnnotation(Map, Class, AnnotatedElement)
* @deprecated As of Spring Framework 4.2.3, use {@link #findMergedAnnotation(AnnotatedElement, Class)} instead.
*/
@Deprecated
@SuppressWarnings("unchecked")
public static <A extends Annotation> A findMergedAnnotation(AnnotatedElement element, String annotationName) {
AnnotationAttributes attributes = findMergedAnnotationAttributes(element, annotationName, false, false);
return AnnotationUtils.synthesizeAnnotation(attributes, (Class<A>) attributes.annotationType(), element);
}
/**
* Find <strong>all</strong> annotations of the specified {@code annotationType}
* within the annotation hierarchy <em>above</em> the supplied {@code element};

30
spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java

@ -257,36 +257,6 @@ public abstract class AnnotationUtils { @@ -257,36 +257,6 @@ public abstract class AnnotationUtils {
return null;
}
/**
* Delegates to {@link #getRepeatableAnnotations(AnnotatedElement, Class, Class)}.
* @since 4.0
* @see #getRepeatableAnnotations(AnnotatedElement, Class, Class)
* @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class)
* @deprecated As of Spring Framework 4.2, use {@code getRepeatableAnnotations()}
* or {@code getDeclaredRepeatableAnnotations()} instead.
*/
@Deprecated
public static <A extends Annotation> Set<A> getRepeatableAnnotation(Method method,
Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) {
return getRepeatableAnnotations(method, annotationType, containerAnnotationType);
}
/**
* Delegates to {@link #getRepeatableAnnotations(AnnotatedElement, Class, Class)}.
* @since 4.0
* @see #getRepeatableAnnotations(AnnotatedElement, Class, Class)
* @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class)
* @deprecated As of Spring Framework 4.2, use {@code getRepeatableAnnotations()}
* or {@code getDeclaredRepeatableAnnotations()} instead.
*/
@Deprecated
public static <A extends Annotation> Set<A> getRepeatableAnnotation(AnnotatedElement annotatedElement,
Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) {
return getRepeatableAnnotations(annotatedElement, annotationType, containerAnnotationType);
}
/**
* Get the <em>repeatable</em> {@linkplain Annotation annotations} of
* {@code annotationType} from the supplied {@link AnnotatedElement}, where

6
spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java vendored

@ -546,12 +546,6 @@ public abstract class AbstractEnvironment implements ConfigurableEnvironment { @@ -546,12 +546,6 @@ public abstract class AbstractEnvironment implements ConfigurableEnvironment {
return this.propertyResolver.getProperty(key, targetType, defaultValue);
}
@Override
@Deprecated
public <T> Class<T> getPropertyAsClass(String key, Class<T> targetType) {
return this.propertyResolver.getPropertyAsClass(key, targetType);
}
@Override
public String getRequiredProperty(String key) throws IllegalStateException {
return this.propertyResolver.getRequiredProperty(key);

6
spring-core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java vendored

@ -153,12 +153,6 @@ public abstract class AbstractPropertyResolver implements ConfigurablePropertyRe @@ -153,12 +153,6 @@ public abstract class AbstractPropertyResolver implements ConfigurablePropertyRe
return (value != null ? value : defaultValue);
}
@Override
@Deprecated
public <T> Class<T> getPropertyAsClass(String key, Class<T> targetValueType) {
throw new UnsupportedOperationException();
}
@Override
public String getRequiredProperty(String key) throws IllegalStateException {
String value = getProperty(key);

13
spring-core/src/main/java/org/springframework/core/env/PropertyResolver.java vendored

@ -72,19 +72,6 @@ public interface PropertyResolver { @@ -72,19 +72,6 @@ public interface PropertyResolver {
*/
<T> T getProperty(String key, Class<T> targetType, T defaultValue);
/**
* Convert the property value associated with the given key to a {@code Class}
* of type {@code T} or {@code null} if the key cannot be resolved.
* @throws org.springframework.core.convert.ConversionException if class specified
* by property value cannot be found or loaded or if targetType is not assignable
* from class specified by property value
* @see #getProperty(String, Class)
* @deprecated as of 4.3, in favor of {@link #getProperty} with manual conversion
* to {@code Class} via the application's {@code ClassLoader}
*/
@Deprecated
<T> Class<T> getPropertyAsClass(String key, Class<T> targetType);
/**
* Return the property value associated with the given key (never {@code null}).
* @throws IllegalStateException if the key cannot be resolved

57
spring-core/src/main/java/org/springframework/core/env/PropertySourcesPropertyResolver.java vendored

@ -93,47 +93,6 @@ public class PropertySourcesPropertyResolver extends AbstractPropertyResolver { @@ -93,47 +93,6 @@ public class PropertySourcesPropertyResolver extends AbstractPropertyResolver {
return null;
}
@Override
@Deprecated
public <T> Class<T> getPropertyAsClass(String key, Class<T> targetValueType) {
if (this.propertySources != null) {
for (PropertySource<?> propertySource : this.propertySources) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Searching for key '%s' in [%s]", key, propertySource.getName()));
}
Object value = propertySource.getProperty(key);
if (value != null) {
logKeyFound(key, propertySource, value);
Class<?> clazz;
if (value instanceof String) {
try {
clazz = ClassUtils.forName((String) value, null);
}
catch (Exception ex) {
throw new ClassConversionException((String) value, targetValueType, ex);
}
}
else if (value instanceof Class) {
clazz = (Class<?>) value;
}
else {
clazz = value.getClass();
}
if (!targetValueType.isAssignableFrom(clazz)) {
throw new ClassConversionException(clazz, targetValueType);
}
@SuppressWarnings("unchecked")
Class<T> targetClass = (Class<T>) clazz;
return targetClass;
}
}
}
if (logger.isDebugEnabled()) {
logger.debug(String.format("Could not find key '%s' in any property source", key));
}
return null;
}
/**
* Log the given key as found in the given {@link PropertySource}, resulting in
* the given value.
@ -151,20 +110,4 @@ public class PropertySourcesPropertyResolver extends AbstractPropertyResolver { @@ -151,20 +110,4 @@ public class PropertySourcesPropertyResolver extends AbstractPropertyResolver {
}
}
@SuppressWarnings("serial")
@Deprecated
private static class ClassConversionException extends ConversionException {
public ClassConversionException(Class<?> actual, Class<?> expected) {
super(String.format("Actual type %s is not assignable to expected type %s",
actual.getName(), expected.getName()));
}
public ClassConversionException(String actual, Class<?> expected, Exception ex) {
super(String.format("Could not find/load class %s during attempt to convert to %s",
actual, expected.getName()), ex);
}
}
}

26
spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java

@ -551,16 +551,9 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol @@ -551,16 +551,9 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
* @see java.net.JarURLConnection
* @see org.springframework.util.PathMatcher
*/
@SuppressWarnings("deprecation")
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, URL rootDirURL, String subPattern)
throws IOException {
// Check deprecated variant for potential overriding first...
Set<Resource> result = doFindPathMatchingJarResources(rootDirResource, subPattern);
if (result != null) {
return result;
}
URLConnection con = rootDirURL.openConnection();
JarFile jarFile;
String jarFileUrl;
@ -614,7 +607,7 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol @@ -614,7 +607,7 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
// The Sun JRE does not return a slash here, but BEA JRockit does.
rootEntryPath = rootEntryPath + "/";
}
result = new LinkedHashSet<Resource>(8);
Set<Resource> result = new LinkedHashSet<Resource>(8);
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
@ -634,23 +627,6 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol @@ -634,23 +627,6 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
}
}
/**
* Find all resources in jar files that match the given location pattern
* via the Ant-style PathMatcher.
* @param rootDirResource the root directory as Resource
* @param subPattern the sub pattern to match (below the root directory)
* @return a mutable Set of matching Resource instances
* @throws IOException in case of I/O errors
* @deprecated as of Spring 4.3, in favor of
* {@link #doFindPathMatchingJarResources(Resource, URL, String)}
*/
@Deprecated
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
throws IOException {
return null;
}
/**
* Resolve the given jar file URL into a JarFile object.
*/

11
spring-core/src/main/java/org/springframework/util/MimeType.java

@ -281,17 +281,6 @@ public class MimeType implements Comparable<MimeType>, Serializable { @@ -281,17 +281,6 @@ public class MimeType implements Comparable<MimeType>, Serializable {
return (charSet != null ? Charset.forName(unquote(charSet)) : null);
}
/**
* Return the character set, as indicated by a {@code charset} parameter, if any.
* @return the character set, or {@code null} if not available
* @deprecated as of Spring 4.3, in favor of {@link #getCharset()} with its name
* aligned with the Java return type name
*/
@Deprecated
public Charset getCharSet() {
return getCharset();
}
/**
* Return a generic parameter value, given a parameter name.
* @param name the parameter name

6
spring-core/src/test/java/org/springframework/core/env/DummyEnvironment.java vendored

@ -43,12 +43,6 @@ public class DummyEnvironment implements Environment { @@ -43,12 +43,6 @@ public class DummyEnvironment implements Environment {
return null;
}
@Override
@Deprecated
public <T> Class<T> getPropertyAsClass(String key, Class<T> targetType) {
return null;
}
@Override
public String getRequiredProperty(String key) throws IllegalStateException {
return null;

40
spring-core/src/test/java/org/springframework/core/env/PropertySourceTests.java vendored

@ -22,21 +22,21 @@ import java.util.List; @@ -22,21 +22,21 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* Unit tests for {@link AbstractPropertySource} implementations.
* Unit tests for {@link PropertySource} implementations.
*
* @author Chris Beams
* @since 3.1
*/
public class PropertySourceTests {
@Test @SuppressWarnings("serial")
@Test
@SuppressWarnings("serial")
public void equals() {
Map<String, Object> map1 = new HashMap<String, Object>() {{ put("a", "b"); }};
Map<String, Object> map2 = new HashMap<String, Object>() {{ put("c", "d"); }};
@ -59,7 +59,8 @@ public class PropertySourceTests { @@ -59,7 +59,8 @@ public class PropertySourceTests {
assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("y", props2)), is(false));
}
@Test @SuppressWarnings("serial")
@Test
@SuppressWarnings("serial")
public void collectionsOperations() {
Map<String, Object> map1 = new HashMap<String, Object>() {{ put("a", "b"); }};
Map<String, Object> map2 = new HashMap<String, Object>() {{ put("c", "d"); }};
@ -87,33 +88,4 @@ public class PropertySourceTests { @@ -87,33 +88,4 @@ public class PropertySourceTests {
propertySources.clear();
}
@Test @SuppressWarnings("serial")
public void toString_verbosityVariesOnLogLevel() {
String name = "props";
Map<String, Object> map = new HashMap<String, Object>() {{ put("k1", "v1"); }};
MapPropertySource ps = new MapPropertySource(name, map);
Logger logger = Logger.getLogger(ps.getClass());
Level original = logger.getLevel();
try {
logger.setLevel(Level.DEBUG);
assertThat("PropertySource.toString() should render verbose output for log levels <= DEBUG",
ps.toString(),
equalTo(String.format("%s@%s [name='%s', properties=%s]",
ps.getClass().getSimpleName(),
System.identityHashCode(ps),
name,
map)));
logger.setLevel(Level.INFO);
assertThat("PropertySource.toString() should render concise output for log levels >= INFO",
ps.toString(),
equalTo(String.format("%s [name='%s']",
ps.getClass().getSimpleName(),
name)));
}
finally {
logger.setLevel(original);
}
}
}

73
spring-core/src/test/java/org/springframework/core/env/PropertySourcesPropertyResolverTests.java vendored

@ -23,7 +23,6 @@ import java.util.Properties; @@ -23,7 +23,6 @@ import java.util.Properties;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.convert.ConversionException;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.mock.env.MockPropertySource;
@ -257,78 +256,6 @@ public class PropertySourcesPropertyResolverTests { @@ -257,78 +256,6 @@ public class PropertySourcesPropertyResolverTests {
new PropertySourcesPropertyResolver(new MutablePropertySources()).resolveRequiredPlaceholders(null);
}
@Test
@SuppressWarnings("deprecation")
public void getPropertyAsClass() throws ClassNotFoundException, LinkageError {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("some.class", SpecificType.class.getName()));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
assertTrue(resolver.getPropertyAsClass("some.class", SomeType.class).equals(SpecificType.class));
}
@Test
@SuppressWarnings("deprecation")
public void getPropertyAsClass_withInterfaceAsTarget() throws ClassNotFoundException, LinkageError {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("some.class", SomeType.class.getName()));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
assertTrue(resolver.getPropertyAsClass("some.class", SomeType.class).equals(SomeType.class));
}
@Test(expected = ConversionException.class)
@SuppressWarnings("deprecation")
public void getPropertyAsClass_withMismatchedTypeForValue() {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("some.class", "java.lang.String"));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
resolver.getPropertyAsClass("some.class", SomeType.class);
}
@Test(expected = ConversionException.class)
@SuppressWarnings("deprecation")
public void getPropertyAsClass_withNonExistentClassForValue() {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("some.class", "some.bogus.Class"));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
resolver.getPropertyAsClass("some.class", SomeType.class);
}
@Test
@SuppressWarnings("deprecation")
public void getPropertyAsClass_withObjectForValue() {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("some.class", new SpecificType()));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
assertTrue(resolver.getPropertyAsClass("some.class", SomeType.class).equals(SpecificType.class));
}
@Test(expected = ConversionException.class)
@SuppressWarnings("deprecation")
public void getPropertyAsClass_withMismatchedObjectForValue() {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("some.class", new Integer(42)));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
resolver.getPropertyAsClass("some.class", SomeType.class);
}
@Test
@SuppressWarnings("deprecation")
public void getPropertyAsClass_withRealClassForValue() {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("some.class", SpecificType.class));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
assertTrue(resolver.getPropertyAsClass("some.class", SomeType.class).equals(SpecificType.class));
}
@Test(expected = ConversionException.class)
@SuppressWarnings("deprecation")
public void getPropertyAsClass_withMismatchedRealClassForValue() {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("some.class", Integer.class));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
resolver.getPropertyAsClass("some.class", SomeType.class);
}
@Test
public void setRequiredProperties_andValidateRequiredProperties() {
// no properties have been marked as required -> validation should pass

69
spring-jms/src/main/java/org/springframework/jms/support/converter/MappingJackson2MessageConverter.java

@ -177,13 +177,13 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B @@ -177,13 +177,13 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
try {
switch (this.targetType) {
case TEXT:
message = mapToTextMessage(object, session, this.objectMapper);
message = mapToTextMessage(object, session, this.objectMapper.writer());
break;
case BYTES:
message = mapToBytesMessage(object, session, this.objectMapper);
message = mapToBytesMessage(object, session, this.objectMapper.writer());
break;
default:
message = mapToMessage(object, session, this.objectMapper, this.targetType);
message = mapToMessage(object, session, this.objectMapper.writer(), this.targetType);
}
}
catch (IOException ex) {
@ -196,6 +196,7 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B @@ -196,6 +196,7 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
@Override
public Message toMessage(Object object, Session session, Object conversionHint)
throws JMSException, MessageConversionException {
return toMessage(object, session, getSerializationView(conversionHint));
}
@ -234,6 +235,7 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B @@ -234,6 +235,7 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
protected Message toMessage(Object object, Session session, ObjectWriter objectWriter)
throws JMSException, MessageConversionException {
Message message;
try {
switch (this.targetType) {
@ -255,24 +257,6 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B @@ -255,24 +257,6 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
}
/**
* Map the given object to a {@link TextMessage}.
* @param object the object to be mapped
* @param session current JMS session
* @param objectMapper the mapper to use
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Session#createBytesMessage
* @deprecated as of 4.3, use {@link #mapToTextMessage(Object, Session, ObjectWriter)}
*/
@Deprecated
protected TextMessage mapToTextMessage(Object object, Session session, ObjectMapper objectMapper)
throws JMSException, IOException {
return mapToTextMessage(object, session, objectMapper.writer());
}
/**
* Map the given object to a {@link TextMessage}.
* @param object the object to be mapped
@ -292,25 +276,6 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B @@ -292,25 +276,6 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
return session.createTextMessage(writer.toString());
}
/**
* Map the given object to a {@link BytesMessage}.
* @param object the object to be mapped
* @param session current JMS session
* @param objectMapper the mapper to use
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Session#createBytesMessage
* @deprecated as of 4.3, use {@link #mapToBytesMessage(Object, Session, ObjectWriter)}
*/
@Deprecated
protected BytesMessage mapToBytesMessage(Object object, Session session, ObjectMapper objectMapper)
throws JMSException, IOException {
return mapToBytesMessage(object, session, objectMapper.writer());
}
/**
* Map the given object to a {@link BytesMessage}.
* @param object the object to be mapped
@ -319,8 +284,8 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B @@ -319,8 +284,8 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Session#createBytesMessage
* @since 4.3
* @see Session#createBytesMessage
*/
protected BytesMessage mapToBytesMessage(Object object, Session session, ObjectWriter objectWriter)
throws JMSException, IOException {
@ -337,27 +302,6 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B @@ -337,27 +302,6 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
return message;
}
/**
* Template method that allows for custom message mapping.
* Invoked when {@link #setTargetType} is not {@link MessageType#TEXT} or
* {@link MessageType#BYTES}.
* <p>The default implementation throws an {@link IllegalArgumentException}.
* @param object the object to marshal
* @param session the JMS Session
* @param objectMapper the mapper to use
* @param targetType the target message type (other than TEXT or BYTES)
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @deprecated as of 4.3, use {@link #mapToMessage(Object, Session, ObjectWriter, MessageType)}
*/
@Deprecated
protected Message mapToMessage(Object object, Session session, ObjectMapper objectMapper, MessageType targetType)
throws JMSException, IOException {
return mapToMessage(object, session, objectMapper.writer(), targetType);
}
/**
* Template method that allows for custom message mapping.
* Invoked when {@link #setTargetType} is not {@link MessageType#TEXT} or
@ -400,7 +344,6 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B @@ -400,7 +344,6 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
}
}
/**
* Convenience method to dispatch to converters for individual message types.
*/

16
spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java

@ -124,16 +124,6 @@ public class MessagingMessageConverter implements MessageConverter, Initializing @@ -124,16 +124,6 @@ public class MessagingMessageConverter implements MessageConverter, Initializing
return this.payloadConverter.fromMessage(message);
}
/**
* Create a JMS message for the specified payload.
* @see MessageConverter#toMessage(Object, Session)
* @deprecated as of 4.3, use {@link #createMessageForPayload(Object, Session, Object)}
*/
@Deprecated
protected javax.jms.Message createMessageForPayload(Object payload, Session session) throws JMSException {
return this.payloadConverter.toMessage(payload, session);
}
/**
* Create a JMS message for the specified payload and conversionHint.
* The conversion hint is an extra object passed to the {@link MessageConverter},
@ -141,18 +131,14 @@ public class MessagingMessageConverter implements MessageConverter, Initializing @@ -141,18 +131,14 @@ public class MessagingMessageConverter implements MessageConverter, Initializing
* @see MessageConverter#toMessage(Object, Session)
* @since 4.3
*/
@SuppressWarnings("deprecation")
protected javax.jms.Message createMessageForPayload(Object payload, Session session, Object conversionHint)
throws JMSException {
return createMessageForPayload(payload, session);
return this.payloadConverter.toMessage(payload, session);
}
protected final MessageHeaders extractHeaders(javax.jms.Message message) {
return this.headerMapper.toHeaders(message);
}
}

26
spring-messaging/src/main/java/org/springframework/messaging/converter/AbstractMessageConverter.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -255,9 +255,8 @@ public abstract class AbstractMessageConverter implements SmartMessageConverter @@ -255,9 +255,8 @@ public abstract class AbstractMessageConverter implements SmartMessageConverter
* perform the conversion
* @since 4.2
*/
@SuppressWarnings("deprecation")
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) {
return convertFromInternal(message, targetClass);
return null;
}
/**
@ -270,28 +269,7 @@ public abstract class AbstractMessageConverter implements SmartMessageConverter @@ -270,28 +269,7 @@ public abstract class AbstractMessageConverter implements SmartMessageConverter
* cannot perform the conversion
* @since 4.2
*/
@SuppressWarnings("deprecation")
protected Object convertToInternal(Object payload, MessageHeaders headers, Object conversionHint) {
return convertToInternal(payload, headers);
}
/**
* Convert the message payload from serialized form to an Object.
* @deprecated as of Spring 4.2, in favor of {@link #convertFromInternal(Message, Class, Object)}
* (which is also protected instead of public)
*/
@Deprecated
public Object convertFromInternal(Message<?> message, Class<?> targetClass) {
return null;
}
/**
* Convert the payload object to serialized form.
* @deprecated as of Spring 4.2, in favor of {@link #convertFromInternal(Message, Class, Object)}
* (which is also protected instead of public)
*/
@Deprecated
public Object convertToInternal(Object payload, MessageHeaders headers) {
return null;
}

16
spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolver.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -76,18 +76,4 @@ public class AnnotationExceptionHandlerMethodResolver extends AbstractExceptionH @@ -76,18 +76,4 @@ public class AnnotationExceptionHandlerMethodResolver extends AbstractExceptionH
return result;
}
/**
* A filter for selecting annotated exception handling methods.
* @deprecated as of Spring 4.2.3, since it isn't used anymore
*/
@Deprecated
public final static MethodFilter EXCEPTION_HANDLER_METHOD_FILTER = new MethodFilter() {
@Override
public boolean matches(Method method) {
return AnnotationUtils.findAnnotation(method, MessageExceptionHandler.class) != null;
}
};
}

12
spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java

@ -399,18 +399,6 @@ public abstract class AbstractMessageBrokerConfiguration implements ApplicationC @@ -399,18 +399,6 @@ public abstract class AbstractMessageBrokerConfiguration implements ApplicationC
*/
protected abstract SimpUserRegistry createLocalUserRegistry();
/**
* As of 4.2, UserSessionRegistry is deprecated in favor of SimpUserRegistry
* exposing information about all connected users. The MultiServerUserRegistry
* implementation in combination with UserRegistryMessageHandler can be used
* to share user registries across multiple servers.
*/
@Deprecated
@SuppressWarnings("deprecation")
protected org.springframework.messaging.simp.user.UserSessionRegistry userSessionRegistry() {
return null;
}
/**
* Return a {@link org.springframework.validation.Validator}s instance for validating
* {@code @Payload} method arguments.

79
spring-messaging/src/main/java/org/springframework/messaging/simp/user/DefaultUserSessionRegistry.java

@ -1,79 +0,0 @@ @@ -1,79 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp.user;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import org.springframework.util.Assert;
/**
* A default thread-safe implementation of {@link UserSessionRegistry}.
*
* @author Rossen Stoyanchev
* @since 4.0
* @deprecated as of 4.2 this class is no longer used, see deprecation notes
* on {@link UserSessionRegistry} for more details.
*/
@Deprecated
@SuppressWarnings({"deprecation", "unused"})
public class DefaultUserSessionRegistry implements UserSessionRegistry {
// userId -> sessionId
private final ConcurrentMap<String, Set<String>> userSessionIds = new ConcurrentHashMap<String, Set<String>>();
private final Object lock = new Object();
@Override
public Set<String> getSessionIds(String user) {
Set<String> set = this.userSessionIds.get(user);
return (set != null ? set : Collections.<String>emptySet());
}
@Override
public void registerSessionId(String user, String sessionId) {
Assert.notNull(user, "User must not be null");
Assert.notNull(sessionId, "Session ID must not be null");
synchronized (this.lock) {
Set<String> set = this.userSessionIds.get(user);
if (set == null) {
set = new CopyOnWriteArraySet<String>();
this.userSessionIds.put(user, set);
}
set.add(sessionId);
}
}
@Override
public void unregisterSessionId(String userName, String sessionId) {
Assert.notNull(userName, "User Name must not be null");
Assert.notNull(sessionId, "Session ID must not be null");
synchronized (lock) {
Set<String> set = this.userSessionIds.get(userName);
if (set != null) {
if (set.remove(sessionId) && set.isEmpty()) {
this.userSessionIds.remove(userName);
}
}
}
}
}

59
spring-messaging/src/main/java/org/springframework/messaging/simp/user/UserSessionRegistry.java

@ -1,59 +0,0 @@ @@ -1,59 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp.user;
import java.util.Set;
/**
* A contract for adding and removing user sessions.
*
* <p>As of 4.2, this interface is replaced by {@link SimpUserRegistry},
* exposing methods to return all registered users as well as to provide
* more extensive information for each user.
*
* @author Rossen Stoyanchev
* @since 4.0
* @deprecated in favor of {@link SimpUserRegistry} in combination with
* {@link org.springframework.context.ApplicationListener} listening for
* {@link org.springframework.web.socket.messaging.AbstractSubProtocolEvent} events.
*/
@Deprecated
public interface UserSessionRegistry {
/**
* Return the active session ids for the user.
* The returned set is a snapshot that will never be modified.
* @param userName the user to look up
* @return a set with 0 or more session ids, never {@code null}.
*/
Set<String> getSessionIds(String userName);
/**
* Register an active session id for a user.
* @param userName the user name
* @param sessionId the session id
*/
void registerSessionId(String userName, String sessionId);
/**
* Unregister an active session id for a user.
* @param userName the user name
* @param sessionId the session id
*/
void unregisterSessionId(String userName, String sessionId);
}

136
spring-messaging/src/main/java/org/springframework/messaging/simp/user/UserSessionRegistryAdapter.java

@ -1,136 +0,0 @@ @@ -1,136 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp.user;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.util.CollectionUtils;
/**
* An adapter that allows a {@code UserSessionRegistry}, which is deprecated in
* favor of {@code SimpUserRegistry}, to be used as a {@code SimpUserRegistry}.
* Due to the more limited information available, methods such as
* {@link #getUsers()} and {@link #findSubscriptions} are not supported.
*
* <p>As of 4.2, this adapter is used only in applications that explicitly
* register a custom {@code UserSessionRegistry} bean by overriding
* {@link org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration#userSessionRegistry()}.
*
* @author Rossen Stoyanchev
* @since 4.2
*/
@SuppressWarnings("deprecation")
public class UserSessionRegistryAdapter implements SimpUserRegistry {
private final UserSessionRegistry userSessionRegistry;
public UserSessionRegistryAdapter(UserSessionRegistry registry) {
this.userSessionRegistry = registry;
}
@Override
public SimpUser getUser(String userName) {
Set<String> sessionIds = this.userSessionRegistry.getSessionIds(userName);
return (!CollectionUtils.isEmpty(sessionIds) ? new SimpUserAdapter(userName, sessionIds) : null);
}
@Override
public Set<SimpUser> getUsers() {
throw new UnsupportedOperationException("UserSessionRegistry does not expose a listing of users");
}
@Override
public Set<SimpSubscription> findSubscriptions(SimpSubscriptionMatcher matcher) {
throw new UnsupportedOperationException("UserSessionRegistry does not support operations across users");
}
/**
* Expose the only information available from a UserSessionRegistry
* (name and session id's) as a {@code SimpUser}.
*/
private static class SimpUserAdapter implements SimpUser {
private final String name;
private final Map<String, SimpSession> sessions;
public SimpUserAdapter(String name, Set<String> sessionIds) {
this.name = name;
this.sessions = new HashMap<String, SimpSession>(sessionIds.size());
for (String sessionId : sessionIds) {
this.sessions.put(sessionId, new SimpSessionAdapter(sessionId));
}
}
@Override
public String getName() {
return this.name;
}
@Override
public boolean hasSessions() {
return !this.sessions.isEmpty();
}
@Override
public SimpSession getSession(String sessionId) {
return this.sessions.get(sessionId);
}
@Override
public Set<SimpSession> getSessions() {
return new HashSet<SimpSession>(this.sessions.values());
}
}
/**
* Expose the only information available from a UserSessionRegistry
* (session ids but no subscriptions) as a {@code SimpSession}.
*/
private static class SimpSessionAdapter implements SimpSession {
private final String id;
public SimpSessionAdapter(String id) {
this.id = id;
}
@Override
public String getId() {
return this.id;
}
@Override
public SimpUser getUser() {
return null;
}
@Override
public Set<SimpSubscription> getSubscriptions() {
return Collections.<SimpSubscription>emptySet();
}
}
}

136
spring-messaging/src/test/java/org/springframework/messaging/converter/AbstractMessageConverterTests.java

@ -1,136 +0,0 @@ @@ -1,136 +0,0 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.converter;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import static org.junit.Assert.*;
/**
* Test fixture for {@link org.springframework.messaging.converter.AbstractMessageConverter}.
*
* @author Rossen Stoyanchev
*/
public class AbstractMessageConverterTests {
private TestMessageConverter converter;
@Before
public void setup() {
this.converter = new TestMessageConverter();
this.converter.setContentTypeResolver(new DefaultContentTypeResolver());
}
@Test
public void supportsTargetClass() {
Message<String> message = MessageBuilder.withPayload("ABC").build();
assertEquals("success-from", this.converter.fromMessage(message, String.class));
assertNull(this.converter.fromMessage(message, Integer.class));
}
@Test
public void supportsMimeType() {
Message<String> message = MessageBuilder.withPayload(
"ABC").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build();
assertEquals("success-from", this.converter.fromMessage(message, String.class));
}
@Test
public void supportsMimeTypeNotSupported() {
Message<String> message = MessageBuilder.withPayload(
"ABC").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON).build();
assertNull(this.converter.fromMessage(message, String.class));
}
@Test
public void supportsMimeTypeNotSpecified() {
Message<String> message = MessageBuilder.withPayload("ABC").build();
assertEquals("success-from", this.converter.fromMessage(message, String.class));
}
@Test
public void supportsMimeTypeNoneConfigured() {
Message<String> message = MessageBuilder.withPayload(
"ABC").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON).build();
this.converter = new TestMessageConverter(Collections.<MimeType>emptyList());
this.converter.setContentTypeResolver(new DefaultContentTypeResolver());
assertEquals("success-from", this.converter.fromMessage(message, String.class));
}
@Test
public void toMessageHeadersCopied() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("foo", "bar");
MessageHeaders headers = new MessageHeaders(map );
Message<?> message = this.converter.toMessage("ABC", headers);
assertEquals("bar", message.getHeaders().get("foo"));
}
@Test
public void toMessageContentTypeHeader() {
Message<?> message = this.converter.toMessage("ABC", null);
assertEquals(MimeTypeUtils.TEXT_PLAIN, message.getHeaders().get(MessageHeaders.CONTENT_TYPE));
}
private static class TestMessageConverter extends AbstractMessageConverter {
public TestMessageConverter() {
super(MimeTypeUtils.TEXT_PLAIN);
}
public TestMessageConverter(Collection<MimeType> supportedMimeTypes) {
super(supportedMimeTypes);
}
@Override
protected boolean supports(Class<?> clazz) {
return String.class.equals(clazz);
}
@Override
public Object convertFromInternal(Message<?> message, Class<?> targetClass) {
return "success-from";
}
@Override
public Object convertToInternal(Object payload, MessageHeaders headers) {
return "success-to";
}
}
}

7
spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -44,6 +44,7 @@ public class MessageConverterTests { @@ -44,6 +44,7 @@ public class MessageConverterTests {
private TestMessageConverter converter = new TestMessageConverter();
@Test
public void supportsTargetClass() {
Message<String> message = MessageBuilder.withPayload("ABC").build();
@ -155,12 +156,12 @@ public class MessageConverterTests { @@ -155,12 +156,12 @@ public class MessageConverterTests {
}
@Override
public Object convertFromInternal(Message<?> message, Class<?> targetClass) {
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) {
return "success-from";
}
@Override
public Object convertToInternal(Object payload, MessageHeaders headers) {
protected Object convertToInternal(Object payload, MessageHeaders headers, Object conversionHint) {
return "success-to";
}
}

30
spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java

@ -59,36 +59,6 @@ public class WebMergedContextConfiguration extends MergedContextConfiguration { @@ -59,36 +59,6 @@ public class WebMergedContextConfiguration extends MergedContextConfiguration {
private final String resourceBasePath;
/**
* Create a new {@code WebMergedContextConfiguration} instance for the
* supplied parameters.
* <p>Delegates to
* {@link #WebMergedContextConfiguration(Class, String[], Class[], Set, String[], String[], String[], String, ContextLoader, CacheAwareContextLoaderDelegate, MergedContextConfiguration)}.
* @param testClass the test class for which the configuration was merged
* @param locations the merged resource locations
* @param classes the merged annotated classes
* @param contextInitializerClasses the merged context initializer classes
* @param activeProfiles the merged active bean definition profiles
* @param resourceBasePath the resource path to the root directory of the web application
* @param contextLoader the resolved {@code ContextLoader}
* @param cacheAwareContextLoaderDelegate a cache-aware context loader
* delegate with which to retrieve the parent context
* @param parent the parent configuration or {@code null} if there is no parent
* @since 3.2.2
* @deprecated as of Spring 4.1, use
* {@link #WebMergedContextConfiguration(Class, String[], Class[], Set, String[], String[], String[], String, ContextLoader, CacheAwareContextLoaderDelegate, MergedContextConfiguration)}
* instead.
*/
@Deprecated
public WebMergedContextConfiguration(Class<?> testClass, String[] locations, Class<?>[] classes,
Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> contextInitializerClasses,
String[] activeProfiles, String resourceBasePath, ContextLoader contextLoader,
CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate, MergedContextConfiguration parent) {
this(testClass, locations, classes, contextInitializerClasses, activeProfiles, null, null, resourceBasePath,
contextLoader, cacheAwareContextLoaderDelegate, parent);
}
/**
* Create a new {@code WebMergedContextConfiguration} instance by copying
* all properties from the supplied {@code MergedContextConfiguration}.

152
spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,21 +16,11 @@ @@ -16,21 +16,11 @@
package org.springframework.test.jdbc;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.util.StringUtils;
/**
@ -124,6 +114,7 @@ public class JdbcTestUtils { @@ -124,6 +114,7 @@ public class JdbcTestUtils {
*/
public static int deleteFromTableWhere(JdbcTemplate jdbcTemplate, String tableName, String whereClause,
Object... args) {
String sql = "DELETE FROM " + tableName;
if (StringUtils.hasText(whereClause)) {
sql += " WHERE " + whereClause;
@ -149,143 +140,4 @@ public class JdbcTestUtils { @@ -149,143 +140,4 @@ public class JdbcTestUtils {
}
}
/**
* Execute the given SQL script.
* <p>The script will typically be loaded from the classpath. There should
* be one statement per line. Any semicolons and line comments will be removed.
* <p><b>Do not use this method to execute DDL if you expect rollback.</b>
* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations
* @param resourceLoader the resource loader with which to load the SQL script
* @param sqlResourcePath the Spring resource path for the SQL script
* @param continueOnError whether or not to continue without throwing an
* exception in the event of an error
* @throws DataAccessException if there is an error executing a statement
* and {@code continueOnError} is {@code false}
* @see ResourceDatabasePopulator
* @see #executeSqlScript(JdbcTemplate, Resource, boolean)
* @deprecated as of Spring 4.0.3, in favor of using
* {@link org.springframework.jdbc.datasource.init.ScriptUtils#executeSqlScript}
* or {@link org.springframework.jdbc.datasource.init.ResourceDatabasePopulator}.
*/
@Deprecated
public static void executeSqlScript(JdbcTemplate jdbcTemplate, ResourceLoader resourceLoader,
String sqlResourcePath, boolean continueOnError) throws DataAccessException {
Resource resource = resourceLoader.getResource(sqlResourcePath);
executeSqlScript(jdbcTemplate, resource, continueOnError);
}
/**
* Execute the given SQL script.
* <p>The script will typically be loaded from the classpath. Statements
* should be delimited with a semicolon. If statements are not delimited with
* a semicolon then there should be one statement per line. Statements are
* allowed to span lines only if they are delimited with a semicolon. Any
* line comments will be removed.
* <p><b>Do not use this method to execute DDL if you expect rollback.</b>
* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations
* @param resource the resource to load the SQL script from
* @param continueOnError whether or not to continue without throwing an
* exception in the event of an error
* @throws DataAccessException if there is an error executing a statement
* and {@code continueOnError} is {@code false}
* @see ResourceDatabasePopulator
* @see #executeSqlScript(JdbcTemplate, EncodedResource, boolean)
* @deprecated as of Spring 4.0.3, in favor of using
* {@link org.springframework.jdbc.datasource.init.ScriptUtils#executeSqlScript}
* or {@link org.springframework.jdbc.datasource.init.ResourceDatabasePopulator}.
*/
@Deprecated
public static void executeSqlScript(JdbcTemplate jdbcTemplate, Resource resource, boolean continueOnError)
throws DataAccessException {
executeSqlScript(jdbcTemplate, new EncodedResource(resource), continueOnError);
}
/**
* Execute the given SQL script.
* <p>The script will typically be loaded from the classpath. There should
* be one statement per line. Any semicolons and line comments will be removed.
* <p><b>Do not use this method to execute DDL if you expect rollback.</b>
* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations
* @param resource the resource (potentially associated with a specific encoding)
* to load the SQL script from
* @param continueOnError whether or not to continue without throwing an
* exception in the event of an error
* @throws DataAccessException if there is an error executing a statement
* and {@code continueOnError} is {@code false}
* @see ResourceDatabasePopulator
* @deprecated as of Spring 4.0.3, in favor of using
* {@link org.springframework.jdbc.datasource.init.ScriptUtils#executeSqlScript}
* or {@link org.springframework.jdbc.datasource.init.ResourceDatabasePopulator}.
*/
@Deprecated
public static void executeSqlScript(JdbcTemplate jdbcTemplate, EncodedResource resource, boolean continueOnError)
throws DataAccessException {
new ResourceDatabasePopulator(continueOnError, false, resource.getEncoding(), resource.getResource()).execute(jdbcTemplate.getDataSource());
}
/**
* Read a script from the provided {@code LineNumberReader}, using
* "{@code --}" as the comment prefix, and build a {@code String} containing
* the lines.
* @param lineNumberReader the {@code LineNumberReader} containing the script
* to be processed
* @return a {@code String} containing the script lines
* @see #readScript(LineNumberReader, String)
* @deprecated as of Spring 4.0.3, in favor of using
* {@link org.springframework.jdbc.datasource.init.ScriptUtils#readScript(LineNumberReader, String, String)}
*/
@Deprecated
public static String readScript(LineNumberReader lineNumberReader) throws IOException {
return readScript(lineNumberReader, ScriptUtils.DEFAULT_COMMENT_PREFIX);
}
/**
* Read a script from the provided {@code LineNumberReader}, using the supplied
* comment prefix, and build a {@code String} containing the lines.
* <p>Lines <em>beginning</em> with the comment prefix are excluded from the
* results; however, line comments anywhere else &mdash; for example, within
* a statement &mdash; will be included in the results.
* @param lineNumberReader the {@code LineNumberReader} containing the script
* to be processed
* @param commentPrefix the prefix that identifies comments in the SQL script &mdash; typically "--"
* @return a {@code String} containing the script lines
* @deprecated as of Spring 4.0.3, in favor of using
* {@link org.springframework.jdbc.datasource.init.ScriptUtils#readScript(LineNumberReader, String, String)}
*/
@Deprecated
public static String readScript(LineNumberReader lineNumberReader, String commentPrefix) throws IOException {
return ScriptUtils.readScript(lineNumberReader, commentPrefix, ScriptUtils.DEFAULT_STATEMENT_SEPARATOR);
}
/**
* Determine if the provided SQL script contains the specified delimiter.
* @param script the SQL script
* @param delim character delimiting each statement &mdash; typically a ';' character
* @return {@code true} if the script contains the delimiter; {@code false} otherwise
* @deprecated as of Spring 4.0.3, in favor of using
* {@link org.springframework.jdbc.datasource.init.ScriptUtils#containsSqlScriptDelimiters}
*/
@Deprecated
public static boolean containsSqlScriptDelimiters(String script, char delim) {
return ScriptUtils.containsSqlScriptDelimiters(script, String.valueOf(delim));
}
/**
* Split an SQL script into separate statements delimited by the provided
* delimiter character. Each individual statement will be added to the
* provided {@code List}.
* <p>Within a statement, "{@code --}" will be used as the comment prefix;
* any text beginning with the comment prefix and extending to the end of
* the line will be omitted from the statement. In addition, multiple adjacent
* whitespace characters will be collapsed into a single space.
* @param script the SQL script
* @param delim character delimiting each statement &mdash; typically a ';' character
* @param statements the list that will contain the individual statements
* @deprecated as of Spring 4.0.3, in favor of using
* {@link org.springframework.jdbc.datasource.init.ScriptUtils#splitSqlScript(String, char, List)}
*/
@Deprecated
public static void splitSqlScript(String script, char delim, List<String> statements) {
ScriptUtils.splitSqlScript(script, delim, statements);
}
}

66
spring-test/src/main/java/org/springframework/test/util/MatcherAssertionErrors.java

@ -1,66 +0,0 @@ @@ -1,66 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.util;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
/**
* A replacement of {@link org.hamcrest.MatcherAssert} that removes the need to
* depend on "hamcrest-all" when using Hamcrest 1.1 and also maintains backward
* compatibility with Hamcrest 1.1 (also embedded in JUnit 4.4 through 4.8).
*
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 3.2
* @deprecated as of Spring 4.2, in favor of the original
* {@link org.hamcrest.MatcherAssert} class with JUnit 4.9 / Hamcrest 1.3
*/
@Deprecated
public abstract class MatcherAssertionErrors {
/**
* Assert that the given matcher matches the actual value.
* @param <T> the static type accepted by the matcher
* @param actual the value to match against
* @param matcher the matcher
*/
public static <T> void assertThat(T actual, Matcher<T> matcher) {
assertThat("", actual, matcher);
}
/**
* Assert that the given matcher matches the actual value.
* @param <T> the static type accepted by the matcher
* @param reason additional information about the error
* @param actual the value to match against
* @param matcher the matcher
*/
public static <T> void assertThat(String reason, T actual, Matcher<T> matcher) {
if (!matcher.matches(actual)) {
Description description = new StringDescription();
description.appendText(reason);
description.appendText("\nExpected: ");
description.appendDescriptionOf(matcher);
description.appendText("\n but: ");
matcher.describeMismatch(actual, description);
throw new AssertionError(description.toString());
}
}
}

29
spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnection.java

@ -99,35 +99,6 @@ public final class MockMvcWebConnection implements WebConnection { @@ -99,35 +99,6 @@ public final class MockMvcWebConnection implements WebConnection {
this.contextPath = contextPath;
}
/**
* Create a new instance that assumes the context path of the application
* is {@code ""} (i.e., the root context).
* <p>For example, the URL {@code http://localhost/test/this} would use
* {@code ""} as the context path.
* @param mockMvc the {@code MockMvc} instance to use; never {@code null}
* @deprecated Use {@link #MockMvcWebConnection(MockMvc, WebClient)}
*/
@Deprecated
public MockMvcWebConnection(MockMvc mockMvc) {
this(mockMvc, "");
}
/**
* Create a new instance with the specified context path.
* <p>The path may be {@code null} in which case the first path segment
* of the URL is turned into the contextPath. Otherwise it must conform
* to {@link javax.servlet.http.HttpServletRequest#getContextPath()}
* which states that it can be an empty string and otherwise must start
* with a "/" character and not end with a "/" character.
* @param mockMvc the {@code MockMvc} instance to use; never {@code null}
* @param contextPath the contextPath to use
* @deprecated use {@link #MockMvcWebConnection(MockMvc, WebClient, String)}
*/
@Deprecated
public MockMvcWebConnection(MockMvc mockMvc, String contextPath) {
this(mockMvc, new WebClient(), contextPath);
}
/**
* Validate the supplied {@code contextPath}.
* <p>If the value is not {@code null}, it must conform to

19
spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionBuilderSupport.java

@ -136,25 +136,6 @@ public abstract class MockMvcWebConnectionBuilderSupport<T extends MockMvcWebCon @@ -136,25 +136,6 @@ public abstract class MockMvcWebConnectionBuilderSupport<T extends MockMvcWebCon
return (T) this;
}
/**
* Create a new {@link WebConnection} that will use a {@link MockMvc}
* instance if one of the specified {@link WebRequestMatcher} instances
* matches.
* @param defaultConnection the default WebConnection to use if none of
* the specified {@code WebRequestMatcher} instances matches; never {@code null}
* @return a new {@code WebConnection} that will use a {@code MockMvc}
* instance if one of the specified {@code WebRequestMatcher} matches
* @see #alwaysUseMockMvc()
* @see #useMockMvc(WebRequestMatcher...)
* @see #useMockMvcForHosts(String...)
* @deprecated Use {@link #createConnection(WebClient)} instead
*/
@Deprecated
protected final WebConnection createConnection(WebConnection defaultConnection) {
Assert.notNull(defaultConnection, "Default WebConnection must not be null");
return createConnection(new WebClient(), defaultConnection);
}
/**
* Create a new {@link WebConnection} that will use a {@link MockMvc}
* instance if one of the specified {@link WebRequestMatcher} instances

6
spring-test/src/test/java/org/springframework/test/context/web/AnnotationConfigWebContextLoaderTests.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,8 +45,8 @@ public class AnnotationConfigWebContextLoaderTests { @@ -45,8 +45,8 @@ public class AnnotationConfigWebContextLoaderTests {
AnnotationConfigWebContextLoader loader = new AnnotationConfigWebContextLoader();
WebMergedContextConfiguration mergedConfig = new WebMergedContextConfiguration(getClass(),
new String[] { "config.xml" }, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, "resource/path", loader, null,
null);
new String[] { "config.xml" }, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, EMPTY_STRING_ARRAY,
EMPTY_STRING_ARRAY, "resource/path", loader, null, null);
loader.loadContext(mergedConfig);
}

6
spring-test/src/test/java/org/springframework/test/context/web/GenericXmlWebContextLoaderTests.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -37,14 +37,14 @@ public class GenericXmlWebContextLoaderTests { @@ -37,14 +37,14 @@ public class GenericXmlWebContextLoaderTests {
@Test
@SuppressWarnings("deprecation")
public void configMustNotContainAnnotatedClasses() throws Exception {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage(containsString("does not support annotated classes"));
GenericXmlWebContextLoader loader = new GenericXmlWebContextLoader();
WebMergedContextConfiguration mergedConfig = new WebMergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
new Class<?>[] { getClass() }, null, EMPTY_STRING_ARRAY, "resource/path", loader, null, null);
new Class<?>[] { getClass() }, null, EMPTY_STRING_ARRAY, EMPTY_STRING_ARRAY, EMPTY_STRING_ARRAY,
"resource/path", loader, null, null);
loader.loadContext(mergedConfig);
}

64
spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsIntegrationTests.java

@ -1,64 +0,0 @@ @@ -1,64 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.jdbc;
import java.util.Arrays;
import org.junit.After;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import static org.junit.Assert.*;
/**
* Integration tests for {@link JdbcTestUtils}.
*
* @author Sam Brannen
* @since 4.0.3
* @see JdbcTestUtilsTests
*/
public class JdbcTestUtilsIntegrationTests {
private final EmbeddedDatabase db = new EmbeddedDatabaseBuilder().build();
private JdbcTemplate jdbcTemplate = new JdbcTemplate(db);
@After
public void shutdown() {
db.shutdown();
}
@Test
@SuppressWarnings("deprecation")
public void executeSqlScriptsAndcountRowsInTableWhere() throws Exception {
for (String script : Arrays.asList("schema.sql", "data.sql")) {
Resource resource = new ClassPathResource(script, getClass());
JdbcTestUtils.executeSqlScript(this.jdbcTemplate, new EncodedResource(resource), false);
}
assertEquals(1, JdbcTestUtils.countRowsInTableWhere(jdbcTemplate, "person", "name = 'bob'"));
}
}

13
spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionTests.java

@ -35,7 +35,6 @@ import static org.junit.Assert.*; @@ -35,7 +35,6 @@ import static org.junit.Assert.*;
* @author Rob Winch
* @since 4.2
*/
@SuppressWarnings("deprecation")
public class MockMvcWebConnectionTests {
private final WebClient webClient = new WebClient();
@ -50,7 +49,7 @@ public class MockMvcWebConnectionTests { @@ -50,7 +49,7 @@ public class MockMvcWebConnectionTests {
@Test
public void contextPathNull() throws IOException {
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, (String) null));
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient));
Page page = this.webClient.getPage("http://localhost/context/a");
@ -59,7 +58,7 @@ public class MockMvcWebConnectionTests { @@ -59,7 +58,7 @@ public class MockMvcWebConnectionTests {
@Test
public void contextPathExplicit() throws IOException {
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, "/context"));
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, "/context"));
Page page = this.webClient.getPage("http://localhost/context/a");
@ -68,7 +67,7 @@ public class MockMvcWebConnectionTests { @@ -68,7 +67,7 @@ public class MockMvcWebConnectionTests {
@Test
public void contextPathEmpty() throws IOException {
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, ""));
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, ""));
Page page = this.webClient.getPage("http://localhost/context/a");
@ -77,7 +76,7 @@ public class MockMvcWebConnectionTests { @@ -77,7 +76,7 @@ public class MockMvcWebConnectionTests {
@Test
public void forward() throws IOException {
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, ""));
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, ""));
Page page = this.webClient.getPage("http://localhost/forward");
@ -87,13 +86,13 @@ public class MockMvcWebConnectionTests { @@ -87,13 +86,13 @@ public class MockMvcWebConnectionTests {
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("resource")
public void contextPathDoesNotStartWithSlash() throws IOException {
new MockMvcWebConnection(this.mockMvc, "context");
new MockMvcWebConnection(this.mockMvc, this.webClient, "context");
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("resource")
public void contextPathEndsWithSlash() throws IOException {
new MockMvcWebConnection(this.mockMvc, "/context/");
new MockMvcWebConnection(this.mockMvc, this.webClient, "/context/");
}
}

40
spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java

@ -1,40 +0,0 @@ @@ -1,40 +0,0 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.converter.xml;
import javax.xml.transform.Source;
import org.springframework.http.converter.FormHttpMessageConverter;
/**
* Extension of {@link org.springframework.http.converter.FormHttpMessageConverter},
* adding support for XML-based parts through a {@link SourceHttpMessageConverter}.
*
* @author Juergen Hoeller
* @since 3.0.3
* @deprecated in favor of
* {@link org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter}
*/
@Deprecated
public class XmlAwareFormHttpMessageConverter extends FormHttpMessageConverter {
public XmlAwareFormHttpMessageConverter() {
super();
addPartConverter(new SourceHttpMessageConverter<Source>());
}
}

65
spring-web/src/main/java/org/springframework/remoting/jaxws/AbstractJaxWsServiceExporter.java

@ -26,7 +26,6 @@ import javax.xml.ws.Endpoint; @@ -26,7 +26,6 @@ import javax.xml.ws.Endpoint;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.WebServiceProvider;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.CannotLoadBeanClassException;
@ -34,13 +33,10 @@ import org.springframework.beans.factory.DisposableBean; @@ -34,13 +33,10 @@ import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* Abstract exporter for JAX-WS services, autodetecting annotated service beans
* (through the JAX-WS {@link javax.jws.WebService} annotation). Compatible with
* JAX-WS 2.1 and 2.2, as included in JDK 6 update 4+ and Java 7/8.
* (through the JAX-WS {@link javax.jws.WebService} annotation).
*
* <p>Subclasses need to implement the {@link #publishEndpoint} template methods
* for actual endpoint exposure.
@ -62,8 +58,6 @@ public abstract class AbstractJaxWsServiceExporter implements BeanFactoryAware, @@ -62,8 +58,6 @@ public abstract class AbstractJaxWsServiceExporter implements BeanFactoryAware,
private WebServiceFeature[] endpointFeatures;
private Object[] webServiceFeatures;
private ListableBeanFactory beanFactory;
private final Set<Endpoint> publishedEndpoints = new LinkedHashSet<Endpoint>();
@ -106,20 +100,6 @@ public abstract class AbstractJaxWsServiceExporter implements BeanFactoryAware, @@ -106,20 +100,6 @@ public abstract class AbstractJaxWsServiceExporter implements BeanFactoryAware,
this.endpointFeatures = endpointFeatures;
}
/**
* Allows for providing JAX-WS 2.2 WebServiceFeature specifications:
* in the form of actual {@link javax.xml.ws.WebServiceFeature} objects,
* WebServiceFeature Class references, or WebServiceFeature class names.
* <p>As of Spring 4.0, this is effectively just an alternative way of
* specifying {@link #setEndpointFeatures "endpointFeatures"}. Do not specify
* both properties at the same time; prefer "endpointFeatures" moving forward.
* @deprecated as of Spring 4.0, in favor of {@link #setEndpointFeatures}
*/
@Deprecated
public void setWebServiceFeatures(Object[] webServiceFeatures) {
this.webServiceFeatures = webServiceFeatures;
}
/**
* Obtains all web service beans and publishes them as JAX-WS endpoints.
*/
@ -190,46 +170,9 @@ public abstract class AbstractJaxWsServiceExporter implements BeanFactoryAware, @@ -190,46 +170,9 @@ public abstract class AbstractJaxWsServiceExporter implements BeanFactoryAware,
* @see Endpoint#create(String, Object)
*/
protected Endpoint createEndpoint(Object bean) {
if (this.endpointFeatures != null || this.webServiceFeatures != null) {
WebServiceFeature[] endpointFeaturesToUse = this.endpointFeatures;
if (endpointFeaturesToUse == null) {
endpointFeaturesToUse = new WebServiceFeature[this.webServiceFeatures.length];
for (int i = 0; i < this.webServiceFeatures.length; i++) {
endpointFeaturesToUse[i] = convertWebServiceFeature(this.webServiceFeatures[i]);
}
}
return Endpoint.create(this.bindingType, bean, endpointFeaturesToUse);
}
else {
return Endpoint.create(this.bindingType, bean);
}
}
private WebServiceFeature convertWebServiceFeature(Object feature) {
Assert.notNull(feature, "WebServiceFeature specification object must not be null");
if (feature instanceof WebServiceFeature) {
return (WebServiceFeature) feature;
}
else if (feature instanceof Class) {
return (WebServiceFeature) BeanUtils.instantiate((Class<?>) feature);
}
else if (feature instanceof String) {
try {
Class<?> featureClass = getBeanClassLoader().loadClass((String) feature);
return (WebServiceFeature) BeanUtils.instantiate(featureClass);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Could not load WebServiceFeature class [" + feature + "]");
}
}
else {
throw new IllegalArgumentException("Unknown WebServiceFeature specification type: " + feature.getClass());
}
}
private ClassLoader getBeanClassLoader() {
return (beanFactory instanceof ConfigurableBeanFactory ?
((ConfigurableBeanFactory) beanFactory).getBeanClassLoader() : ClassUtils.getDefaultClassLoader());
return (this.endpointFeatures != null ?
Endpoint.create(this.bindingType, bean, this.endpointFeatures) :
Endpoint.create(this.bindingType, bean));
}

72
spring-web/src/main/java/org/springframework/remoting/jaxws/JaxWsPortClientInterceptor.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -35,21 +35,18 @@ import org.aopalliance.intercept.MethodInterceptor; @@ -35,21 +35,18 @@ import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.remoting.RemoteConnectFailureException;
import org.springframework.remoting.RemoteLookupFailureException;
import org.springframework.remoting.RemoteProxyFailureException;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* {@link org.aopalliance.intercept.MethodInterceptor} for accessing a
* specific port of a JAX-WS service. Compatible with JAX-WS 2.1 and 2.2,
* as included in JDK 6 update 4+ and Java 7/8.
* specific port of a JAX-WS service.
*
* <p>Uses either {@link LocalJaxWsServiceFactory}'s facilities underneath,
* or takes an explicit reference to an existing JAX-WS Service instance
@ -86,8 +83,6 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory @@ -86,8 +83,6 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory
private WebServiceFeature[] portFeatures;
private Object[] webServiceFeatures;
private Class<?> serviceInterface;
private boolean lookupServiceOnStartup = true;
@ -271,22 +266,6 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory @@ -271,22 +266,6 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory
this.portFeatures = features;
}
/**
* Specify WebServiceFeature specifications for the JAX-WS port stub:
* in the form of actual {@link javax.xml.ws.WebServiceFeature} objects,
* WebServiceFeature Class references, or WebServiceFeature class names.
* <p>As of Spring 4.0, this is effectively just an alternative way of
* specifying {@link #setPortFeatures "portFeatures"}. Do not specify
* both properties at the same time; prefer "portFeatures" moving forward.
* @deprecated as of Spring 4.0, in favor of the differentiated
* {@link #setServiceFeatures "serviceFeatures"} and
* {@link #setPortFeatures "portFeatures"} properties
*/
@Deprecated
public void setWebServiceFeatures(Object[] webServiceFeatures) {
this.webServiceFeatures = webServiceFeatures;
}
/**
* Set the interface of the service that this factory should create a proxy for.
*/
@ -315,10 +294,8 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory @@ -315,10 +294,8 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory
}
/**
* Set the bean ClassLoader to use for this interceptor:
* for resolving WebServiceFeature class names as specified through
* {@link #setWebServiceFeatures}, and also for building a client
* proxy in the {@link JaxWsPortProxyFactoryBean} subclass.
* Set the bean ClassLoader to use for this interceptor: primarily for
* building a client proxy in the {@link JaxWsPortProxyFactoryBean} subclass.
*/
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
@ -429,16 +406,9 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory @@ -429,16 +406,9 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory
* {@code Service.getPort(...)}
*/
protected Object getPortStub(Service service, QName portQName) {
if (this.portFeatures != null || this.webServiceFeatures != null) {
WebServiceFeature[] portFeaturesToUse = this.portFeatures;
if (portFeaturesToUse == null) {
portFeaturesToUse = new WebServiceFeature[this.webServiceFeatures.length];
for (int i = 0; i < this.webServiceFeatures.length; i++) {
portFeaturesToUse[i] = convertWebServiceFeature(this.webServiceFeatures[i]);
}
}
return (portQName != null ? service.getPort(portQName, getServiceInterface(), portFeaturesToUse) :
service.getPort(getServiceInterface(), portFeaturesToUse));
if (this.portFeatures != null) {
return (portQName != null ? service.getPort(portQName, getServiceInterface(), this.portFeatures) :
service.getPort(getServiceInterface(), this.portFeatures));
}
else {
return (portQName != null ? service.getPort(portQName, getServiceInterface()) :
@ -446,34 +416,6 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory @@ -446,34 +416,6 @@ public class JaxWsPortClientInterceptor extends LocalJaxWsServiceFactory
}
}
/**
* Convert the given feature specification object to a WebServiceFeature instance
* @param feature the feature specification object, as passed into the
* {@link #setWebServiceFeatures "webServiceFeatures"} bean property
* @return the WebServiceFeature instance (never {@code null})
*/
private WebServiceFeature convertWebServiceFeature(Object feature) {
Assert.notNull(feature, "WebServiceFeature specification object must not be null");
if (feature instanceof WebServiceFeature) {
return (WebServiceFeature) feature;
}
else if (feature instanceof Class) {
return (WebServiceFeature) BeanUtils.instantiate((Class<?>) feature);
}
else if (feature instanceof String) {
try {
Class<?> featureClass = getBeanClassLoader().loadClass((String) feature);
return (WebServiceFeature) BeanUtils.instantiate(featureClass);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Could not load WebServiceFeature class [" + feature + "]");
}
}
else {
throw new IllegalArgumentException("Unknown WebServiceFeature specification type: " + feature.getClass());
}
}
/**
* Prepare the given JAX-WS port stub, applying properties to it.
* Called by {@link #prepare}.

5
spring-web/src/main/java/org/springframework/remoting/jaxws/JaxWsPortProxyFactoryBean.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -31,8 +31,7 @@ import org.springframework.beans.factory.FactoryBean; @@ -31,8 +31,7 @@ import org.springframework.beans.factory.FactoryBean;
* @see #setServiceInterface
* @see LocalJaxWsServiceFactoryBean
*/
public class JaxWsPortProxyFactoryBean extends JaxWsPortClientInterceptor
implements FactoryBean<Object> {
public class JaxWsPortProxyFactoryBean extends JaxWsPortClientInterceptor implements FactoryBean<Object> {
private Object serviceProxy;

1
spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java

@ -114,7 +114,6 @@ public class LocalJaxWsServiceFactory { @@ -114,7 +114,6 @@ public class LocalJaxWsServiceFactory {
/**
* Specify WebServiceFeature objects (e.g. as inner bean definitions)
* to apply to JAX-WS service creation.
* <p>Note: This mechanism requires JAX-WS 2.2 or higher.
* @since 4.0
* @see Service#create(QName, WebServiceFeature...)
*/

6
spring-web/src/main/java/org/springframework/remoting/jaxws/SimpleJaxWsServiceExporter.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2009 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -31,9 +31,9 @@ import javax.xml.ws.WebServiceProvider; @@ -31,9 +31,9 @@ import javax.xml.ws.WebServiceProvider;
* <p>Note that this exporter will only work if the JAX-WS runtime actually
* supports publishing with an address argument, i.e. if the JAX-WS runtime
* ships an internal HTTP server. This is the case with the JAX-WS runtime
* that's inclued in Sun's JDK 1.6 but not with the standalone JAX-WS 2.1 RI.
* that's included in Sun's JDK 6 but not with the standalone JAX-WS 2.1 RI.
*
* <p>For explicit configuration of JAX-WS endpoints with Sun's JDK 1.6
* <p>For explicit configuration of JAX-WS endpoints with Sun's JDK 6
* HTTP server, consider using {@link SimpleHttpServerJaxWsServiceExporter}!
*
* @author Juergen Hoeller

19
spring-web/src/main/java/org/springframework/web/util/WebUtils.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -181,23 +181,6 @@ public abstract class WebUtils { @@ -181,23 +181,6 @@ public abstract class WebUtils {
System.getProperties().remove(key);
}
/**
* Return whether default HTML escaping is enabled for the web application,
* i.e. the value of the "defaultHtmlEscape" context-param in {@code web.xml}
* (if any). Falls back to {@code false} in case of no explicit default given.
* @param servletContext the servlet context of the web application
* @return whether default HTML escaping is enabled (default is {@code false})
* @deprecated as of Spring 4.1, in favor of {@link #getDefaultHtmlEscape}
*/
@Deprecated
public static boolean isDefaultHtmlEscape(ServletContext servletContext) {
if (servletContext == null) {
return false;
}
String param = servletContext.getInitParameter(HTML_ESCAPE_CONTEXT_PARAM);
return Boolean.valueOf(param);
}
/**
* Return whether default HTML escaping is enabled for the web application,
* i.e. the value of the "defaultHtmlEscape" context-param in {@code web.xml}

21
spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,6 +22,7 @@ import javax.xml.namespace.QName; @@ -22,6 +22,7 @@ import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.WebServiceRef;
import javax.xml.ws.soap.AddressingFeature;
@ -43,25 +44,15 @@ public class JaxWsSupportTests { @@ -43,25 +44,15 @@ public class JaxWsSupportTests {
@Test
public void testJaxWsPortAccess() throws Exception {
doTestJaxWsPortAccess((Object[]) null);
doTestJaxWsPortAccess((WebServiceFeature[]) null);
}
@Test
public void testJaxWsPortAccessWithFeatureObject() throws Exception {
public void testJaxWsPortAccessWithFeature() throws Exception {
doTestJaxWsPortAccess(new AddressingFeature());
}
@Test
public void testJaxWsPortAccessWithFeatureClass() throws Exception {
doTestJaxWsPortAccess(AddressingFeature.class);
}
@Test
public void testJaxWsPortAccessWithFeatureString() throws Exception {
doTestJaxWsPortAccess("javax.xml.ws.soap.AddressingFeature");
}
private void doTestJaxWsPortAccess(Object... features) throws Exception {
private void doTestJaxWsPortAccess(WebServiceFeature... features) throws Exception {
GenericApplicationContext ac = new GenericApplicationContext();
GenericBeanDefinition serviceDef = new GenericBeanDefinition();
@ -83,7 +74,7 @@ public class JaxWsSupportTests { @@ -83,7 +74,7 @@ public class JaxWsSupportTests {
clientDef.getPropertyValues().add("serviceInterface", OrderService.class);
clientDef.getPropertyValues().add("lookupServiceOnStartup", Boolean.FALSE);
if (features != null) {
clientDef.getPropertyValues().add("webServiceFeatures", features);
clientDef.getPropertyValues().add("portFeatures", features);
}
ac.registerBeanDefinition("client", clientDef);

5
spring-webmvc/src/main/java/org/springframework/web/servlet/config/ViewResolversBeanDefinitionParser.java

@ -66,14 +66,13 @@ public class ViewResolversBeanDefinitionParser implements BeanDefinitionParser { @@ -66,14 +66,13 @@ public class ViewResolversBeanDefinitionParser implements BeanDefinitionParser {
public static final String VIEW_RESOLVER_BEAN_NAME = "mvcViewResolver";
@SuppressWarnings("deprecation")
public BeanDefinition parse(Element element, ParserContext context) {
Object source = context.extractSource(element);
context.pushContainingComponent(new CompositeComponentDefinition(element.getTagName(), source));
ManagedList<Object> resolvers = new ManagedList<Object>(4);
resolvers.setSource(context.extractSource(element));
String[] names = new String[] {"jsp", "tiles", "bean-name", "freemarker", "velocity", "groovy", "script-template", "bean", "ref"};
String[] names = new String[] {"jsp", "tiles", "bean-name", "freemarker", "groovy", "script-template", "bean", "ref"};
for (Element resolverElement : DomUtils.getChildElementsByTagName(element, names)) {
String name = resolverElement.getLocalName();
@ -81,7 +80,7 @@ public class ViewResolversBeanDefinitionParser implements BeanDefinitionParser { @@ -81,7 +80,7 @@ public class ViewResolversBeanDefinitionParser implements BeanDefinitionParser {
resolvers.add(context.getDelegate().parsePropertySubElement(resolverElement, null));
continue;
}
RootBeanDefinition resolverBeanDef = null;
RootBeanDefinition resolverBeanDef;
if ("jsp".equals(name)) {
resolverBeanDef = new RootBeanDefinition(InternalResourceViewResolver.class);
resolverBeanDef.getPropertyValues().add("prefix", "/WEB-INF/");

20
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java

@ -381,17 +381,6 @@ public class MvcUriComponentsBuilder { @@ -381,17 +381,6 @@ public class MvcUriComponentsBuilder {
(controllerType != null ? controllerType : method.getDeclaringClass()), method, args);
}
/**
* @see #fromMethod(Class, Method, Object...)
* @see #fromMethod(UriComponentsBuilder, Class, Method, Object...)
* @deprecated as of 4.2, this is deprecated in favor of the overloaded
* method that also accepts a controllerType argument
*/
@Deprecated
public static UriComponentsBuilder fromMethod(Method method, Object... args) {
return fromMethodInternal(null, method.getDeclaringClass(), method, args);
}
private static UriComponentsBuilder fromMethodInternal(UriComponentsBuilder baseUrl,
Class<?> controllerType, Method method, Object... args) {
@ -777,15 +766,6 @@ public class MvcUriComponentsBuilder { @@ -777,15 +766,6 @@ public class MvcUriComponentsBuilder {
}
}
/**
* @deprecated as of 4.2, this is deprecated in favor of alternative constructors
* that accept a controllerType argument
*/
@Deprecated
public MethodArgumentBuilder(Method method) {
this(method.getDeclaringClass(), method);
}
private static UriComponentsBuilder initBaseUrl() {
UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentServletMapping();
return UriComponentsBuilder.fromPath(builder.build().getPath());

27
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java

@ -98,9 +98,7 @@ public abstract class ResponseEntityExceptionHandler { @@ -98,9 +98,7 @@ public abstract class ResponseEntityExceptionHandler {
* @param ex the target exception
* @param request the current request
*/
@SuppressWarnings("deprecation")
@ExceptionHandler({
org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException.class,
HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class,
HttpMediaTypeNotAcceptableException.class,
@ -118,11 +116,7 @@ public abstract class ResponseEntityExceptionHandler { @@ -118,11 +116,7 @@ public abstract class ResponseEntityExceptionHandler {
})
public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
if (ex instanceof org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) {
HttpStatus status = HttpStatus.NOT_FOUND;
return handleNoSuchRequestHandlingMethod((org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) ex, headers, status, request);
}
else if (ex instanceof HttpRequestMethodNotSupportedException) {
if (ex instanceof HttpRequestMethodNotSupportedException) {
HttpStatus status = HttpStatus.METHOD_NOT_ALLOWED;
return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, headers, status, request);
}
@ -205,25 +199,6 @@ public abstract class ResponseEntityExceptionHandler { @@ -205,25 +199,6 @@ public abstract class ResponseEntityExceptionHandler {
return new ResponseEntity<Object>(body, headers, status);
}
/**
* Customize the response for NoSuchRequestHandlingMethodException.
* <p>This method logs a warning and delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
* @deprecated as of 4.3, along with {@link org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException}
*/
@Deprecated
protected ResponseEntity<Object> handleNoSuchRequestHandlingMethod(org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
pageNotFoundLogger.warn(ex.getMessage());
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for HttpRequestMethodNotSupportedException.
* <p>This method logs a warning, sets the "Allow" header, and delegates to

118
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/AbstractUrlMethodNameResolver.java

@ -1,118 +0,0 @@ @@ -1,118 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.multiaction;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.web.util.UrlPathHelper;
/**
* Abstract base class for URL-based {@link MethodNameResolver} implementations.
*
* <p>Provides infrastructure for mapping handlers to URLs and configurable
* URL lookup. For information on the latter, see the
* {@link #setAlwaysUseFullPath} "alwaysUseFullPath"}
* and {@link #setUrlDecode "urlDecode"} properties.
*
* @author Juergen Hoeller
* @since 14.01.2004
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public abstract class AbstractUrlMethodNameResolver implements MethodNameResolver {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private UrlPathHelper urlPathHelper = new UrlPathHelper();
/**
* Set if URL lookup should always use full path within current servlet
* context. Else, the path within the current servlet mapping is used
* if applicable (i.e. in the case of a ".../*" servlet mapping in web.xml).
* Default is "false".
* @see org.springframework.web.util.UrlPathHelper#setAlwaysUseFullPath
*/
public void setAlwaysUseFullPath(boolean alwaysUseFullPath) {
this.urlPathHelper.setAlwaysUseFullPath(alwaysUseFullPath);
}
/**
* Set if context path and request URI should be URL-decoded.
* Both are returned <i>undecoded</i> by the Servlet API,
* in contrast to the servlet path.
* <p>Uses either the request encoding or the default encoding according
* to the Servlet spec (ISO-8859-1).
* @see org.springframework.web.util.UrlPathHelper#setUrlDecode
*/
public void setUrlDecode(boolean urlDecode) {
this.urlPathHelper.setUrlDecode(urlDecode);
}
/**
* Set the UrlPathHelper to use for resolution of lookup paths.
* <p>Use this to override the default UrlPathHelper with a custom subclass,
* or to share common UrlPathHelper settings across multiple MethodNameResolvers
* and HandlerMappings.
* @see org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#setUrlPathHelper
*/
public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
Assert.notNull(urlPathHelper, "UrlPathHelper must not be null");
this.urlPathHelper = urlPathHelper;
}
/**
* Retrieves the URL path to use for lookup and delegates to
* {@code getHandlerMethodNameForUrlPath}.
* Converts {@code null} values to NoSuchRequestHandlingMethodExceptions.
* @see #getHandlerMethodNameForUrlPath
*/
@Override
public final String getHandlerMethodName(HttpServletRequest request)
throws NoSuchRequestHandlingMethodException {
String urlPath = this.urlPathHelper.getLookupPathForRequest(request);
String name = getHandlerMethodNameForUrlPath(urlPath);
if (name == null) {
throw new NoSuchRequestHandlingMethodException(urlPath, request.getMethod(), request.getParameterMap());
}
if (logger.isDebugEnabled()) {
logger.debug("Returning handler method name '" + name + "' for lookup path: " + urlPath);
}
return name;
}
/**
* Return a method name that can handle this request, based on the
* given lookup path. Called by {@code getHandlerMethodName}.
* @param urlPath the URL path to use for lookup,
* according to the settings in this class
* @return a method name that can handle this request.
* Should return null if no matching method found.
* @see #getHandlerMethodName
* @see #setAlwaysUseFullPath
* @see #setUrlDecode
*/
protected abstract String getHandlerMethodNameForUrlPath(String urlPath);
}

126
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/InternalPathMethodNameResolver.java

@ -1,126 +0,0 @@ @@ -1,126 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.multiaction;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.web.util.WebUtils;
/**
* Simple implementation of {@link MethodNameResolver} that maps URL to
* method name. Although this is the default implementation used by the
* {@link MultiActionController} class (because it requires no configuration),
* it's bit naive for most applications. In particular, we don't usually
* want to tie URL to implementation methods.
*
* <p>Maps the resource name after the last slash, ignoring an extension.
* E.g. "/foo/bar/baz.html" to "baz", assuming a "/foo/bar/baz.html"
* controller mapping to the corresponding MultiActionController handler.
* method. Doesn't support wildcards.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class InternalPathMethodNameResolver extends AbstractUrlMethodNameResolver {
private String prefix = "";
private String suffix = "";
/** Request URL path String --> method name String */
private final Map<String, String> methodNameCache = new ConcurrentHashMap<String, String>(16);
/**
* Specify a common prefix for handler method names.
* Will be prepended to the internal path found in the URL:
* e.g. internal path "baz", prefix "my" -> method name "mybaz".
*/
public void setPrefix(String prefix) {
this.prefix = (prefix != null ? prefix : "");
}
/**
* Return the common prefix for handler method names.
*/
protected String getPrefix() {
return this.prefix;
}
/**
* Specify a common suffix for handler method names.
* Will be appended to the internal path found in the URL:
* e.g. internal path "baz", suffix "Handler" -> method name "bazHandler".
*/
public void setSuffix(String suffix) {
this.suffix = (suffix != null ? suffix : "");
}
/**
* Return the common suffix for handler method names.
*/
protected String getSuffix() {
return this.suffix;
}
/**
* Extracts the method name indicated by the URL path.
* @see #extractHandlerMethodNameFromUrlPath
* @see #postProcessHandlerMethodName
*/
@Override
protected String getHandlerMethodNameForUrlPath(String urlPath) {
String methodName = this.methodNameCache.get(urlPath);
if (methodName == null) {
methodName = extractHandlerMethodNameFromUrlPath(urlPath);
methodName = postProcessHandlerMethodName(methodName);
this.methodNameCache.put(urlPath, methodName);
}
return methodName;
}
/**
* Extract the handler method name from the given request URI.
* Delegates to {@code WebUtils.extractFilenameFromUrlPath(String)}.
* @param uri the request URI (e.g. "/index.html")
* @return the extracted URI filename (e.g. "index")
* @see org.springframework.web.util.WebUtils#extractFilenameFromUrlPath
*/
protected String extractHandlerMethodNameFromUrlPath(String uri) {
return WebUtils.extractFilenameFromUrlPath(uri);
}
/**
* Build the full handler method name based on the given method name
* as indicated by the URL path.
* <p>The default implementation simply applies prefix and suffix.
* This can be overridden, for example, to manipulate upper case
* / lower case, etc.
* @param methodName the original method name, as indicated by the URL path
* @return the full method name to use
* @see #getPrefix()
* @see #getSuffix()
*/
protected String postProcessHandlerMethodName(String methodName) {
return getPrefix() + methodName + getSuffix();
}
}

47
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/MethodNameResolver.java

@ -1,47 +0,0 @@ @@ -1,47 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.multiaction;
import javax.servlet.http.HttpServletRequest;
/**
* Interface that parameterizes the MultiActionController class
* using the <b>Strategy</b> GoF Design pattern, allowing
* the mapping from incoming request to handler method name
* to be varied without affecting other application code.
*
* <p>Illustrates how delegation can be more flexible than subclassing.
*
* @author Rod Johnson
* @see MultiActionController#setMethodNameResolver
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public interface MethodNameResolver {
/**
* Return a method name that can handle this request. Such
* mappings are typically, but not necessarily, based on URL.
* @param request current HTTP request
* @return a method name that can handle this request.
* Never returns {@code null}; throws exception if not resolvable.
* @throws NoSuchRequestHandlingMethodException if no handler method
* can be found for the given request
*/
String getHandlerMethodName(HttpServletRequest request) throws NoSuchRequestHandlingMethodException;
}

657
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/MultiActionController.java

@ -1,657 +0,0 @@ @@ -1,657 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet. mvc.multiaction;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.LastModified;
/**
* {@link org.springframework.web.servlet.mvc.Controller Controller}
* implementation that allows multiple request types to be handled by the same
* class. Subclasses of this class can handle several different types of
* request with methods of the form
*
* <pre class="code">public (ModelAndView | Map | String | void) actionName(HttpServletRequest request, HttpServletResponse response, [,HttpSession] [,AnyObject]);</pre>
*
* A Map return value indicates a model that is supposed to be passed to a default view
* (determined through a {@link org.springframework.web.servlet.RequestToViewNameTranslator}).
* A String return value indicates the name of a view to be rendered without a specific model.
*
* <p>May take a third parameter (of type {@link HttpSession}) in which an
* existing session will be required, or a third parameter of an arbitrary
* class that gets treated as the command (that is, an instance of the class
* gets created, and request parameters get bound to it)
*
* <p>These methods can throw any kind of exception, but should only let
* propagate those that they consider fatal, or which their class or superclass
* is prepared to catch by implementing an exception handler.
*
* <p>When returning just a {@link Map} instance view name translation will be
* used to generate the view name. The configured
* {@link org.springframework.web.servlet.RequestToViewNameTranslator} will be
* used to determine the view name.
*
* <p>When returning {@code void} a return value of {@code null} is
* assumed meaning that the handler method is responsible for writing the
* response directly to the supplied {@link HttpServletResponse}.
*
* <p>This model allows for rapid coding, but loses the advantage of
* compile-time checking. It is similar to a Struts {@code DispatchAction},
* but more sophisticated. Also supports delegation to another object.
*
* <p>An implementation of the {@link MethodNameResolver} interface defined in
* this package should return a method name for a given request, based on any
* aspect of the request, such as its URL or an "action" parameter. The actual
* strategy can be configured via the "methodNameResolver" bean property, for
* each {@code MultiActionController}.
*
* <p>The default {@code MethodNameResolver} is
* {@link InternalPathMethodNameResolver}; further included strategies are
* {@link PropertiesMethodNameResolver} and {@link ParameterMethodNameResolver}.
*
* <p>Subclasses can implement custom exception handler methods with names such
* as:
*
* <pre class="code">public ModelAndView anyMeaningfulName(HttpServletRequest request, HttpServletResponse response, ExceptionClass exception);</pre>
*
* The third parameter can be any subclass or {@link Exception} or
* {@link RuntimeException}.
*
* <p>There can also be an optional {@code xxxLastModified} method for
* handlers, of signature:
*
* <pre class="code">public long anyMeaningfulNameLastModified(HttpServletRequest request)</pre>
*
* If such a method is present, it will be invoked. Default return from
* {@code getLastModified} is -1, meaning that the content must always be
* regenerated.
*
* <p><b>Note that all handler methods need to be public and that
* method overloading is <i>not</i> allowed.</b>
*
* <p>See also the description of the workflow performed by
* {@link AbstractController the superclass} (in that section of the class
* level Javadoc entitled 'workflow').
*
* <p><b>Note:</b> For maximum data binding flexibility, consider direct usage of a
* {@link ServletRequestDataBinder} in your controller method, instead of relying
* on a declared command argument. This allows for full control over the entire
* binder setup and usage, including the invocation of {@link Validator Validators}
* and the subsequent evaluation of binding/validation errors.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Colin Sampaleanu
* @author Rob Harrop
* @author Sam Brannen
* @see MethodNameResolver
* @see InternalPathMethodNameResolver
* @see PropertiesMethodNameResolver
* @see ParameterMethodNameResolver
* @see org.springframework.web.servlet.mvc.LastModified#getLastModified
* @see org.springframework.web.bind.ServletRequestDataBinder
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class MultiActionController extends AbstractController implements LastModified {
/** Suffix for last-modified methods */
public static final String LAST_MODIFIED_METHOD_SUFFIX = "LastModified";
/** Default command name used for binding command objects: "command" */
public static final String DEFAULT_COMMAND_NAME = "command";
/**
* Log category to use when no mapped handler is found for a request.
* @see #pageNotFoundLogger
*/
public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
/**
* Additional logger to use when no mapped handler is found for a request.
* @see #PAGE_NOT_FOUND_LOG_CATEGORY
*/
protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
/** Object we'll invoke methods on. Defaults to this. */
private Object delegate;
/** Delegate that knows how to determine method names from incoming requests */
private MethodNameResolver methodNameResolver = new InternalPathMethodNameResolver();
/** List of Validators to apply to commands */
private Validator[] validators;
/** Optional strategy for pre-initializing data binding */
private WebBindingInitializer webBindingInitializer;
/** Handler methods, keyed by name */
private final Map<String, Method> handlerMethodMap = new HashMap<String, Method>();
/** LastModified methods, keyed by handler method name (without LAST_MODIFIED_SUFFIX) */
private final Map<String, Method> lastModifiedMethodMap = new HashMap<String, Method>();
/** Methods, keyed by exception class */
private final Map<Class<?>, Method> exceptionHandlerMap = new HashMap<Class<?>, Method>();
/**
* Constructor for {@code MultiActionController} that looks for
* handler methods in the present subclass.
*/
public MultiActionController() {
this.delegate = this;
registerHandlerMethods(this.delegate);
// We'll accept no handler methods found here - a delegate might be set later on.
}
/**
* Constructor for {@code MultiActionController} that looks for
* handler methods in delegate, rather than a subclass of this class.
* @param delegate handler object. This does not need to implement any
* particular interface, as everything is done using reflection.
*/
public MultiActionController(Object delegate) {
setDelegate(delegate);
}
/**
* Set the delegate used by this class; the default is {@code this},
* assuming that handler methods have been added by a subclass.
* <p>This method does not get invoked once the class is configured.
* @param delegate an object containing handler methods
* @throws IllegalStateException if no handler methods are found
*/
public final void setDelegate(Object delegate) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
registerHandlerMethods(this.delegate);
// There must be SOME handler methods.
if (this.handlerMethodMap.isEmpty()) {
throw new IllegalStateException("No handler methods in class [" + this.delegate.getClass() + "]");
}
}
/**
* Set the method name resolver that this class should use.
* <p>Allows parameterization of handler method mappings.
*/
public final void setMethodNameResolver(MethodNameResolver methodNameResolver) {
this.methodNameResolver = methodNameResolver;
}
/**
* Return the MethodNameResolver used by this class.
*/
public final MethodNameResolver getMethodNameResolver() {
return this.methodNameResolver;
}
/**
* Set the {@link Validator Validators} for this controller.
* <p>The {@code Validators} must support the specified command class.
*/
public final void setValidators(Validator[] validators) {
this.validators = validators;
}
/**
* Return the Validators for this controller.
*/
public final Validator[] getValidators() {
return this.validators;
}
/**
* Specify a WebBindingInitializer which will apply pre-configured
* configuration to every DataBinder that this controller uses.
* <p>Allows for factoring out the entire binder configuration
* to separate objects, as an alternative to {@link #initBinder}.
*/
public final void setWebBindingInitializer(WebBindingInitializer webBindingInitializer) {
this.webBindingInitializer = webBindingInitializer;
}
/**
* Return the WebBindingInitializer (if any) which will apply pre-configured
* configuration to every DataBinder that this controller uses.
*/
public final WebBindingInitializer getWebBindingInitializer() {
return this.webBindingInitializer;
}
/**
* Registers all handlers methods on the delegate object.
*/
private void registerHandlerMethods(Object delegate) {
this.handlerMethodMap.clear();
this.lastModifiedMethodMap.clear();
this.exceptionHandlerMap.clear();
// Look at all methods in the subclass, trying to find
// methods that are validators according to our criteria
Method[] methods = delegate.getClass().getMethods();
for (Method method : methods) {
// We're looking for methods with given parameters.
if (isExceptionHandlerMethod(method)) {
registerExceptionHandlerMethod(method);
}
else if (isHandlerMethod(method)) {
registerHandlerMethod(method);
registerLastModifiedMethodIfExists(delegate, method);
}
}
}
/**
* Is the supplied method a valid handler method?
* <p>Does not consider {@code Controller.handleRequest} itself
* as handler method (to avoid potential stack overflow).
*/
private boolean isHandlerMethod(Method method) {
Class<?> returnType = method.getReturnType();
if (ModelAndView.class == returnType || Map.class == returnType || String.class == returnType ||
void.class == returnType) {
Class<?>[] parameterTypes = method.getParameterTypes();
return (parameterTypes.length >= 2 &&
HttpServletRequest.class == parameterTypes[0] &&
HttpServletResponse.class == parameterTypes[1] &&
!("handleRequest".equals(method.getName()) && parameterTypes.length == 2));
}
return false;
}
/**
* Is the supplied method a valid exception handler method?
*/
private boolean isExceptionHandlerMethod(Method method) {
return (isHandlerMethod(method) &&
method.getParameterTypes().length == 3 &&
Throwable.class.isAssignableFrom(method.getParameterTypes()[2]));
}
/**
* Registers the supplied method as a request handler.
*/
private void registerHandlerMethod(Method method) {
if (logger.isDebugEnabled()) {
logger.debug("Found action method [" + method + "]");
}
this.handlerMethodMap.put(method.getName(), method);
}
/**
* Registers a last-modified handler method for the supplied handler method
* if one exists.
*/
private void registerLastModifiedMethodIfExists(Object delegate, Method method) {
// Look for corresponding LastModified method.
try {
Method lastModifiedMethod = delegate.getClass().getMethod(
method.getName() + LAST_MODIFIED_METHOD_SUFFIX,
new Class<?>[] {HttpServletRequest.class});
Class<?> returnType = lastModifiedMethod.getReturnType();
if (!(long.class == returnType || Long.class == returnType)) {
throw new IllegalStateException("last-modified method [" + lastModifiedMethod +
"] declares an invalid return type - needs to be 'long' or 'Long'");
}
// Put in cache, keyed by handler method name.
this.lastModifiedMethodMap.put(method.getName(), lastModifiedMethod);
if (logger.isDebugEnabled()) {
logger.debug("Found last-modified method for handler method [" + method + "]");
}
}
catch (NoSuchMethodException ex) {
// No last modified method. That's ok.
}
}
/**
* Registers the supplied method as an exception handler.
*/
private void registerExceptionHandlerMethod(Method method) {
this.exceptionHandlerMap.put(method.getParameterTypes()[2], method);
if (logger.isDebugEnabled()) {
logger.debug("Found exception handler method [" + method + "]");
}
}
//---------------------------------------------------------------------
// Implementation of LastModified
//---------------------------------------------------------------------
/**
* Try to find an XXXXLastModified method, where XXXX is the name of a handler.
* Return -1 if there's no such handler, indicating that content must be updated.
* @see org.springframework.web.servlet.mvc.LastModified#getLastModified(HttpServletRequest)
*/
@Override
public long getLastModified(HttpServletRequest request) {
try {
String handlerMethodName = this.methodNameResolver.getHandlerMethodName(request);
Method lastModifiedMethod = this.lastModifiedMethodMap.get(handlerMethodName);
if (lastModifiedMethod != null) {
try {
// Invoke the last-modified method...
Long wrappedLong = (Long) lastModifiedMethod.invoke(this.delegate, request);
return (wrappedLong != null ? wrappedLong : -1);
}
catch (Exception ex) {
// We encountered an error invoking the last-modified method.
// We can't do anything useful except log this, as we can't throw an exception.
logger.error("Failed to invoke last-modified method", ex);
}
}
}
catch (NoSuchRequestHandlingMethodException ex) {
// No handler method for this request. This shouldn't happen, as this
// method shouldn't be called unless a previous invocation of this class
// has generated content. Do nothing, that's OK: We'll return default.
}
return -1L;
}
//---------------------------------------------------------------------
// Implementation of AbstractController
//---------------------------------------------------------------------
/**
* Determine a handler method and invoke it.
* @see MethodNameResolver#getHandlerMethodName
* @see #invokeNamedMethod
* @see #handleNoSuchRequestHandlingMethod
*/
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
String methodName = this.methodNameResolver.getHandlerMethodName(request);
return invokeNamedMethod(methodName, request, response);
}
catch (NoSuchRequestHandlingMethodException ex) {
return handleNoSuchRequestHandlingMethod(ex, request, response);
}
}
/**
* Handle the case where no request handler method was found.
* <p>The default implementation logs a warning and sends an HTTP 404 error.
* Alternatively, a fallback view could be chosen, or the
* NoSuchRequestHandlingMethodException could be rethrown as-is.
* @param ex the NoSuchRequestHandlingMethodException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @return a ModelAndView to render, or {@code null} if handled directly
* @throws Exception an Exception that should be thrown as result of the servlet request
*/
protected ModelAndView handleNoSuchRequestHandlingMethod(
NoSuchRequestHandlingMethodException ex, HttpServletRequest request, HttpServletResponse response)
throws Exception {
pageNotFoundLogger.warn(ex.getMessage());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
}
/**
* Invokes the named method.
* <p>Uses a custom exception handler if possible; otherwise, throw an
* unchecked exception; wrap a checked exception or Throwable.
*/
protected final ModelAndView invokeNamedMethod(
String methodName, HttpServletRequest request, HttpServletResponse response) throws Exception {
Method method = this.handlerMethodMap.get(methodName);
if (method == null) {
throw new NoSuchRequestHandlingMethodException(methodName, getClass());
}
try {
Class<?>[] paramTypes = method.getParameterTypes();
List<Object> params = new ArrayList<Object>(4);
params.add(request);
params.add(response);
if (paramTypes.length >= 3 && HttpSession.class == paramTypes[2]) {
HttpSession session = request.getSession(false);
if (session == null) {
throw new HttpSessionRequiredException(
"Pre-existing session required for handler method '" + methodName + "'");
}
params.add(session);
}
// If last parameter isn't of HttpSession type, it's a command.
if (paramTypes.length >= 3 && HttpSession.class != paramTypes[paramTypes.length - 1]) {
Object command = newCommandObject(paramTypes[paramTypes.length - 1]);
params.add(command);
bind(request, command);
}
Object returnValue = method.invoke(this.delegate, params.toArray(new Object[params.size()]));
return massageReturnValueIfNecessary(returnValue);
}
catch (InvocationTargetException ex) {
// The handler method threw an exception.
return handleException(request, response, ex.getTargetException());
}
catch (Exception ex) {
// The binding process threw an exception.
return handleException(request, response, ex);
}
}
/**
* Processes the return value of a handler method to ensure that it either returns
* {@code null} or an instance of {@link ModelAndView}. When returning a {@link Map},
* the {@link Map} instance is wrapped in a new {@link ModelAndView} instance.
*/
@SuppressWarnings("unchecked")
private ModelAndView massageReturnValueIfNecessary(Object returnValue) {
if (returnValue instanceof ModelAndView) {
return (ModelAndView) returnValue;
}
else if (returnValue instanceof Map) {
return new ModelAndView().addAllObjects((Map<String, ?>) returnValue);
}
else if (returnValue instanceof String) {
return new ModelAndView((String) returnValue);
}
else {
// Either returned null or was 'void' return.
// We'll assume that the handle method already wrote the response.
return null;
}
}
/**
* Create a new command object of the given class.
* <p>This implementation uses {@code BeanUtils.instantiateClass},
* so commands need to have public no-arg constructors.
* Subclasses can override this implementation if desired.
* @throws Exception if the command object could not be instantiated
* @see org.springframework.beans.BeanUtils#instantiateClass(Class)
*/
protected Object newCommandObject(Class<?> clazz) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Creating new command of class [" + clazz.getName() + "]");
}
return BeanUtils.instantiateClass(clazz);
}
/**
* Bind request parameters onto the given command bean
* @param request request from which parameters will be bound
* @param command command object, that must be a JavaBean
* @throws Exception in case of invalid state or arguments
*/
protected void bind(HttpServletRequest request, Object command) throws Exception {
logger.debug("Binding request parameters onto MultiActionController command");
ServletRequestDataBinder binder = createBinder(request, command);
binder.bind(request);
if (this.validators != null) {
for (Validator validator : this.validators) {
if (validator.supports(command.getClass())) {
ValidationUtils.invokeValidator(validator, command, binder.getBindingResult());
}
}
}
binder.closeNoCatch();
}
/**
* Create a new binder instance for the given command and request.
* <p>Called by {@code bind}. Can be overridden to plug in custom
* ServletRequestDataBinder subclasses.
* <p>The default implementation creates a standard ServletRequestDataBinder,
* and invokes {@code initBinder}. Note that {@code initBinder}
* will not be invoked if you override this method!
* @param request current HTTP request
* @param command the command to bind onto
* @return the new binder instance
* @throws Exception in case of invalid state or arguments
* @see #bind
* @see #initBinder
*/
protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object command) throws Exception {
ServletRequestDataBinder binder = new ServletRequestDataBinder(command, getCommandName(command));
initBinder(request, binder);
return binder;
}
/**
* Return the command name to use for the given command object.
* <p>Default is "command".
* @param command the command object
* @return the command name to use
* @see #DEFAULT_COMMAND_NAME
*/
protected String getCommandName(Object command) {
return DEFAULT_COMMAND_NAME;
}
/**
* Initialize the given binder instance, for example with custom editors.
* Called by {@code createBinder}.
* <p>This method allows you to register custom editors for certain fields of your
* command class. For instance, you will be able to transform Date objects into a
* String pattern and back, in order to allow your JavaBeans to have Date properties
* and still be able to set and display them in an HTML interface.
* <p>The default implementation is empty.
* <p>Note: the command object is not directly passed to this method, but it's available
* via {@link org.springframework.validation.DataBinder#getTarget()}
* @param request current HTTP request
* @param binder new binder instance
* @throws Exception in case of invalid state or arguments
* @see #createBinder
* @see org.springframework.validation.DataBinder#registerCustomEditor
* @see org.springframework.beans.propertyeditors.CustomDateEditor
*/
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
if (this.webBindingInitializer != null) {
this.webBindingInitializer.initBinder(binder, new ServletWebRequest(request));
}
}
/**
* Determine the exception handler method for the given exception.
* <p>Can return {@code null} if not found.
* @return a handler for the given exception type, or {@code null}
* @param exception the exception to handle
*/
protected Method getExceptionHandler(Throwable exception) {
Class<?> exceptionClass = exception.getClass();
if (logger.isDebugEnabled()) {
logger.debug("Trying to find handler for exception class [" + exceptionClass.getName() + "]");
}
Method handler = this.exceptionHandlerMap.get(exceptionClass);
while (handler == null && exceptionClass != Throwable.class) {
if (logger.isDebugEnabled()) {
logger.debug("Trying to find handler for exception superclass [" + exceptionClass.getName() + "]");
}
exceptionClass = exceptionClass.getSuperclass();
handler = this.exceptionHandlerMap.get(exceptionClass);
}
return handler;
}
/**
* We've encountered an exception thrown from a handler method.
* Invoke an appropriate exception handler method, if any.
* @param request current HTTP request
* @param response current HTTP response
* @param ex the exception that got thrown
* @return a ModelAndView to render the response
*/
private ModelAndView handleException(HttpServletRequest request, HttpServletResponse response, Throwable ex)
throws Exception {
Method handler = getExceptionHandler(ex);
if (handler != null) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking exception handler [" + handler + "] for exception: " + ex);
}
try {
Object returnValue = handler.invoke(this.delegate, request, response, ex);
return massageReturnValueIfNecessary(returnValue);
}
catch (InvocationTargetException ex2) {
logger.error("Original exception overridden by exception handling failure", ex);
ReflectionUtils.rethrowException(ex2.getTargetException());
}
catch (Exception ex2) {
logger.error("Failed to invoke exception handler method", ex2);
}
}
else {
// If we get here, there was no custom handler or we couldn't invoke it.
ReflectionUtils.rethrowException(ex);
}
throw new IllegalStateException("Should never get here");
}
}

80
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/NoSuchRequestHandlingMethodException.java

@ -1,80 +0,0 @@ @@ -1,80 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.multiaction;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.style.StylerUtils;
import org.springframework.web.util.UrlPathHelper;
/**
* Exception thrown when there is no handler method ("action" method)
* for a specific HTTP request.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see MethodNameResolver#getHandlerMethodName(javax.servlet.http.HttpServletRequest)
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
@SuppressWarnings("serial")
public class NoSuchRequestHandlingMethodException extends ServletException {
private String methodName;
/**
* Create a new NoSuchRequestHandlingMethodException for the given request.
* @param request the offending HTTP request
*/
public NoSuchRequestHandlingMethodException(HttpServletRequest request) {
this(new UrlPathHelper().getRequestUri(request), request.getMethod(), request.getParameterMap());
}
/**
* Create a new NoSuchRequestHandlingMethodException.
* @param urlPath the request URI that has been used for handler lookup
* @param method the HTTP request method of the request
* @param parameterMap the request's parameters as map
*/
public NoSuchRequestHandlingMethodException(String urlPath, String method, Map<String, String[]> parameterMap) {
super("No matching handler method found for servlet request: path '" + urlPath +
"', method '" + method + "', parameters " + StylerUtils.style(parameterMap));
}
/**
* Create a new NoSuchRequestHandlingMethodException for the given request.
* @param methodName the name of the handler method that wasn't found
* @param controllerClass the class the handler method was expected to be in
*/
public NoSuchRequestHandlingMethodException(String methodName, Class<?> controllerClass) {
super("No request handling method with name '" + methodName +
"' in class [" + controllerClass.getName() + "]");
this.methodName = methodName;
}
/**
* Return the name of the offending method, if known.
*/
public String getMethodName() {
return this.methodName;
}
}

224
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java

@ -1,224 +0,0 @@ @@ -1,224 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.multiaction;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;
/**
* Implementation of {@link MethodNameResolver} which supports several strategies
* for mapping parameter values to the names of methods to invoke.
*
* <p>The simplest strategy looks for a specific named parameter, whose value is
* considered the name of the method to invoke. The name of the parameter may be
* specified as a JavaBean property, if the default {@code action} is not
* acceptable.
*
* <p>The alternative strategy uses the very existence of a request parameter (
* i.e. a request parameter with a certain name is found) as an indication that a
* method with the same name should be dispatched to. In this case, the actual
* request parameter value is ignored. The list of parameter/method names may
* be set via the {@code methodParamNames} JavaBean property.
*
* <p>The second resolution strategy is primarily expected to be used with web
* pages containing multiple submit buttons. The 'name' attribute of each
* button should be set to the mapped method name, while the 'value' attribute
* is normally displayed as the button label by the browser, and will be
* ignored by the resolver.
*
* <p>Note that the second strategy also supports the use of submit buttons of
* type 'image'. That is, an image submit button named 'reset' will normally be
* submitted by the browser as two request parameters called 'reset.x', and
* 'reset.y'. When checking for the existence of a parameter from the
* {@code methodParamNames} list, to indicate that a specific method should
* be called, the code will look for a request parameter in the "reset" form
* (exactly as specified in the list), and in the "reset.x" form ('.x' appended
* to the name in the list). In this way it can handle both normal and image
* submit buttons. The actual method name resolved, if there is a match, will
* always be the bare form without the ".x".
*
* <p><b>Note:</b> If both strategies are configured, i.e. both "paramName"
* and "methodParamNames" are specified, then both will be checked for any given
* request. A match for an explicit request parameter in the "methodParamNames"
* list always wins over a value specified for a "paramName" action parameter.
*
* <p>For use with either strategy, the name of a default handler method to use
* when there is no match, can be specified as a JavaBean property.
*
* <p>For both resolution strategies, the method name is of course coming from
* some sort of view code, (such as a JSP page). While this may be acceptable,
* it is sometimes desirable to treat this only as a 'logical' method name,
* with a further mapping to a 'real' method name. As such, an optional
* 'logical' mapping may be specified for this purpose.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Colin Sampaleanu
* @see #setParamName
* @see #setMethodParamNames
* @see #setLogicalMappings
* @see #setDefaultMethodName
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class ParameterMethodNameResolver implements MethodNameResolver {
/**
* Default name for the parameter whose value identifies the method to invoke:
* "action".
*/
public static final String DEFAULT_PARAM_NAME = "action";
protected final Log logger = LogFactory.getLog(getClass());
private String paramName = DEFAULT_PARAM_NAME;
private String[] methodParamNames;
private Properties logicalMappings;
private String defaultMethodName;
/**
* Set the name of the parameter whose <i>value</i> identifies the name of
* the method to invoke. Default is "action".
* <p>Alternatively, specify parameter names where the very existence of each
* parameter means that a method of the same name should be invoked, via
* the "methodParamNames" property.
* @see #setMethodParamNames
*/
public void setParamName(String paramName) {
if (paramName != null) {
Assert.hasText(paramName, "'paramName' must not be empty");
}
this.paramName = paramName;
}
/**
* Set a String array of parameter names, where the <i>very existence of a
* parameter</i> in the list (with value ignored) means that a method of the
* same name should be invoked. This target method name may then be optionally
* further mapped via the {@link #logicalMappings} property, in which case it
* can be considered a logical name only.
* @see #setParamName
*/
public void setMethodParamNames(String... methodParamNames) {
this.methodParamNames = methodParamNames;
}
/**
* Specifies a set of optional logical method name mappings. For both resolution
* strategies, the method name initially comes in from the view layer. If that needs
* to be treated as a 'logical' method name, and mapped to a 'real' method name, then
* a name/value pair for that purpose should be added to this Properties instance.
* Any method name not found in this mapping will be considered to already be the
* real method name.
* <p>Note that in the case of no match, where the {@link #defaultMethodName} property
* is used if available, that method name is considered to already be the real method
* name, and is not run through the logical mapping.
* @param logicalMappings a Properties object mapping logical method names to real
* method names
*/
public void setLogicalMappings(Properties logicalMappings) {
this.logicalMappings = logicalMappings;
}
/**
* Set the name of the default handler method that should be
* used when no parameter was found in the request
*/
public void setDefaultMethodName(String defaultMethodName) {
if (defaultMethodName != null) {
Assert.hasText(defaultMethodName, "'defaultMethodName' must not be empty");
}
this.defaultMethodName = defaultMethodName;
}
@Override
public String getHandlerMethodName(HttpServletRequest request) throws NoSuchRequestHandlingMethodException {
String methodName = null;
// Check parameter names where the very existence of each parameter
// means that a method of the same name should be invoked, if any.
if (this.methodParamNames != null) {
for (String candidate : this.methodParamNames) {
if (WebUtils.hasSubmitParameter(request, candidate)) {
methodName = candidate;
if (logger.isDebugEnabled()) {
logger.debug("Determined handler method '" + methodName +
"' based on existence of explicit request parameter of same name");
}
break;
}
}
}
// Check parameter whose value identifies the method to invoke, if any.
if (methodName == null && this.paramName != null) {
methodName = request.getParameter(this.paramName);
if (methodName != null) {
if (logger.isDebugEnabled()) {
logger.debug("Determined handler method '" + methodName +
"' based on value of request parameter '" + this.paramName + "'");
}
}
}
if (methodName != null && this.logicalMappings != null) {
// Resolve logical name into real method name, if appropriate.
String originalName = methodName;
methodName = this.logicalMappings.getProperty(methodName, methodName);
if (logger.isDebugEnabled()) {
logger.debug("Resolved method name '" + originalName + "' to handler method '" + methodName + "'");
}
}
if (methodName != null && !StringUtils.hasText(methodName)) {
if (logger.isDebugEnabled()) {
logger.debug("Method name '" + methodName + "' is empty: treating it as no method name found");
}
methodName = null;
}
if (methodName == null) {
if (this.defaultMethodName != null) {
// No specific method resolved: use default method.
methodName = this.defaultMethodName;
if (logger.isDebugEnabled()) {
logger.debug("Falling back to default handler method '" + this.defaultMethodName + "'");
}
}
else {
// If resolution failed completely, throw an exception.
throw new NoSuchRequestHandlingMethodException(request);
}
}
return methodName;
}
}

101
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/PropertiesMethodNameResolver.java

@ -1,101 +0,0 @@ @@ -1,101 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.multiaction;
import java.util.Enumeration;
import java.util.Properties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
/**
* The most flexible out-of-the-box implementation of the {@link MethodNameResolver}
* interface. Uses {@code java.util.Properties} to define the mapping
* between the URL of incoming requests and the corresponding method name.
* Such properties can be held in an XML document.
*
* <p>Properties format is
* {@code
* /welcome.html=displayGenresPage
* }
* Note that method overloading isn't allowed, so there's no need to
* specify arguments.
*
* <p>Supports direct matches, e.g. a registered "/test" matches "/test",
* and a various Ant-style pattern matches, e.g. a registered "/t*" matches
* both "/test" and "/team". For details, see the AntPathMatcher javadoc.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see java.util.Properties
* @see org.springframework.util.AntPathMatcher
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class PropertiesMethodNameResolver extends AbstractUrlMethodNameResolver
implements InitializingBean {
private Properties mappings;
private PathMatcher pathMatcher = new AntPathMatcher();
/**
* Set explicit URL to method name mappings through a Properties object.
* @param mappings Properties with URL as key and method name as value
*/
public void setMappings(Properties mappings) {
this.mappings = mappings;
}
/**
* Set the PathMatcher implementation to use for matching URL paths
* against registered URL patterns. Default is AntPathMatcher.
* @see org.springframework.util.AntPathMatcher
*/
public void setPathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "PathMatcher must not be null");
this.pathMatcher = pathMatcher;
}
@Override
public void afterPropertiesSet() {
if (this.mappings == null || this.mappings.isEmpty()) {
throw new IllegalArgumentException("'mappings' property is required");
}
}
@Override
protected String getHandlerMethodNameForUrlPath(String urlPath) {
String methodName = this.mappings.getProperty(urlPath);
if (methodName != null) {
return methodName;
}
Enumeration<?> propNames = this.mappings.propertyNames();
while (propNames.hasMoreElements()) {
String registeredPath = (String) propNames.nextElement();
if (this.pathMatcher.match(registeredPath, urlPath)) {
return (String) this.mappings.get(registeredPath);
}
}
return null;
}
}

13
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/package-info.java

@ -1,13 +0,0 @@ @@ -1,13 +0,0 @@
/**
* Package allowing MVC Controller implementations to handle requests
* at <i>method</i> rather than <i>class</i> level. This is useful when
* we want to avoid having many trivial controller classes, as can
* easily happen when using an MVC framework.
*
* <p>Typically a controller that handles multiple request types will
* extend MultiActionController, and implement multiple request handling
* methods that will be invoked by reflection if they follow this class'
* naming convention. Classes are analyzed at startup and methods cached,
* so the performance overhead of reflection in this approach is negligible.
*/
package org.springframework.web.servlet.mvc.multiaction;

158
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/AbstractControllerUrlHandlerMapping.java

@ -1,158 +0,0 @@ @@ -1,158 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.support;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping;
/**
* Base class for {@link org.springframework.web.servlet.HandlerMapping} implementations
* that derive URL paths according to conventions for specific controller types.
*
* @author Juergen Hoeller
* @since 2.5.3
* @see ControllerClassNameHandlerMapping
* @see ControllerBeanNameHandlerMapping
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetectingUrlHandlerMapping {
private ControllerTypePredicate predicate = new AnnotationControllerTypePredicate();
private Set<String> excludedPackages = Collections.singleton("org.springframework.web.servlet.mvc");
private Set<Class<?>> excludedClasses = Collections.emptySet();
/**
* Set whether to activate or deactivate detection of annotated controllers.
*/
public void setIncludeAnnotatedControllers(boolean includeAnnotatedControllers) {
this.predicate = (includeAnnotatedControllers ?
new AnnotationControllerTypePredicate() : new ControllerTypePredicate());
}
/**
* Specify Java packages that should be excluded from this mapping.
* Any classes in such a package (or any of its subpackages) will be
* ignored by this HandlerMapping.
* <p>Default is to exclude the entire "org.springframework.web.servlet.mvc"
* package, including its subpackages, since none of Spring's out-of-the-box
* Controller implementations is a reasonable candidate for this mapping strategy.
* Such controllers are typically handled by a separate HandlerMapping,
* e.g. a {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping},
* alongside this ControllerClassNameHandlerMapping for application controllers.
*/
public void setExcludedPackages(String... excludedPackages) {
this.excludedPackages = (excludedPackages != null) ?
new HashSet<String>(Arrays.asList(excludedPackages)) : new HashSet<String>();
}
/**
* Specify controller classes that should be excluded from this mapping.
* Any such classes will simply be ignored by this HandlerMapping.
*/
public void setExcludedClasses(Class<?>... excludedClasses) {
this.excludedClasses = (excludedClasses != null) ?
new HashSet<Class<?>>(Arrays.asList(excludedClasses)) : new HashSet<Class<?>>();
}
/**
* This implementation delegates to {@link #buildUrlsForHandler},
* provided that {@link #isEligibleForMapping} returns {@code true}.
*/
@Override
protected String[] determineUrlsForHandler(String beanName) {
Class<?> beanClass = getApplicationContext().getType(beanName);
if (isEligibleForMapping(beanName, beanClass)) {
return buildUrlsForHandler(beanName, beanClass);
}
else {
return null;
}
}
/**
* Determine whether the specified controller is excluded from this mapping.
* @param beanName the name of the controller bean
* @param beanClass the concrete class of the controller bean
* @return whether the specified class is excluded
* @see #setExcludedPackages
* @see #setExcludedClasses
*/
protected boolean isEligibleForMapping(String beanName, Class<?> beanClass) {
if (beanClass == null) {
if (logger.isDebugEnabled()) {
logger.debug("Excluding controller bean '" + beanName + "' from class name mapping " +
"because its bean type could not be determined");
}
return false;
}
if (this.excludedClasses.contains(beanClass)) {
if (logger.isDebugEnabled()) {
logger.debug("Excluding controller bean '" + beanName + "' from class name mapping " +
"because its bean class is explicitly excluded: " + beanClass.getName());
}
return false;
}
String beanClassName = beanClass.getName();
for (String packageName : this.excludedPackages) {
if (beanClassName.startsWith(packageName)) {
if (logger.isDebugEnabled()) {
logger.debug("Excluding controller bean '" + beanName + "' from class name mapping " +
"because its bean class is defined in an excluded package: " + beanClass.getName());
}
return false;
}
}
return isControllerType(beanClass);
}
/**
* Determine whether the given bean class indicates a controller type
* that is supported by this mapping strategy.
* @param beanClass the class to introspect
*/
protected boolean isControllerType(Class<?> beanClass) {
return this.predicate.isControllerType(beanClass);
}
/**
* Determine whether the given bean class indicates a controller type
* that dispatches to multiple action methods.
* @param beanClass the class to introspect
*/
protected boolean isMultiActionControllerType(Class<?> beanClass) {
return this.predicate.isMultiActionControllerType(beanClass);
}
/**
* Abstract template method to be implemented by subclasses.
* @param beanName the name of the bean
* @param beanClass the type of the bean
* @return the URLs determined for the bean
*/
protected abstract String[] buildUrlsForHandler(String beanName, Class<?> beanClass);
}

45
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/AnnotationControllerTypePredicate.java

@ -1,45 +0,0 @@ @@ -1,45 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.support;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
/**
* Extension of {@link ControllerTypePredicate} that detects
* annotated {@code @Controller} beans as well.
*
* @author Juergen Hoeller
* @since 2.5.3
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
class AnnotationControllerTypePredicate extends ControllerTypePredicate {
@Override
public boolean isControllerType(Class<?> beanClass) {
return (super.isControllerType(beanClass) ||
AnnotationUtils.findAnnotation(beanClass, Controller.class) != null);
}
@Override
public boolean isMultiActionControllerType(Class<?> beanClass) {
return (super.isMultiActionControllerType(beanClass) ||
AnnotationUtils.findAnnotation(beanClass, Controller.class) != null);
}
}

96
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/ControllerBeanNameHandlerMapping.java

@ -1,96 +0,0 @@ @@ -1,96 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.support;
import java.util.ArrayList;
import java.util.List;
import org.springframework.util.StringUtils;
/**
* Implementation of {@link org.springframework.web.servlet.HandlerMapping} that
* follows a simple convention for generating URL path mappings from the <i>bean names</i>
* of registered {@link org.springframework.web.servlet.mvc.Controller} beans
* as well as {@code @Controller} annotated beans.
*
* <p>This is similar to {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping}
* but doesn't expect bean names to follow the URL convention: It turns plain bean names
* into URLs by prepending a slash and optionally applying a specified prefix and/or suffix.
* However, it only does so for well-known {@link #isControllerType controller types},
* as listed above (analogous to {@link ControllerClassNameHandlerMapping}).
*
* @author Juergen Hoeller
* @since 2.5.3
* @see ControllerClassNameHandlerMapping
* @see org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class ControllerBeanNameHandlerMapping extends AbstractControllerUrlHandlerMapping {
private String urlPrefix = "";
private String urlSuffix = "";
/**
* Set an optional prefix to prepend to generated URL mappings.
* <p>By default this is an empty String. If you want a prefix like
* "/myapp/", you can set it for all beans mapped by this mapping.
*/
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = (urlPrefix != null ? urlPrefix : "");
}
/**
* Set an optional suffix to append to generated URL mappings.
* <p>By default this is an empty String. If you want a suffix like
* ".do", you can set it for all beans mapped by this mapping.
*/
public void setUrlSuffix(String urlSuffix) {
this.urlSuffix = (urlSuffix != null ? urlSuffix : "");
}
@Override
protected String[] buildUrlsForHandler(String beanName, Class<?> beanClass) {
List<String> urls = new ArrayList<String>();
urls.add(generatePathMapping(beanName));
String[] aliases = getApplicationContext().getAliases(beanName);
for (String alias : aliases) {
urls.add(generatePathMapping(alias));
}
return StringUtils.toStringArray(urls);
}
/**
* Prepends a '/' if required and appends the URL suffix to the name.
*/
protected String generatePathMapping(String beanName) {
String name = (beanName.startsWith("/") ? beanName : "/" + beanName);
StringBuilder path = new StringBuilder();
if (!name.startsWith(this.urlPrefix)) {
path.append(this.urlPrefix);
}
path.append(name);
if (!name.endsWith(this.urlSuffix)) {
path.append(this.urlSuffix);
}
return path.toString();
}
}

183
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/ControllerClassNameHandlerMapping.java

@ -1,183 +0,0 @@ @@ -1,183 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.support;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Implementation of {@link org.springframework.web.servlet.HandlerMapping} that
* follows a simple convention for generating URL path mappings from the <i>class names</i>
* of registered {@link org.springframework.web.servlet.mvc.Controller} beans
* as well as {@code @Controller} annotated beans.
*
* <p>For simple {@link org.springframework.web.servlet.mvc.Controller} implementations
* (those that handle a single request type), the convention is to take the
* {@link ClassUtils#getShortName short name} of the {@code Class},
* remove the 'Controller' suffix if it exists and return the remaining text, lower-cased,
* as the mapping, with a leading {@code /}. For example:
* <ul>
* <li>{@code WelcomeController} -> {@code /welcome*}</li>
* <li>{@code HomeController} -> {@code /home*}</li>
* </ul>
*
* <p>For {@code MultiActionController MultiActionControllers} and {@code @Controller}
* beans, a similar mapping is registered, except that all sub-paths are registered
* using the trailing wildcard pattern {@code /*}. For example:
* <ul>
* <li>{@code WelcomeController} -> {@code /welcome}, {@code /welcome/*}</li>
* <li>{@code CatalogController} -> {@code /catalog}, {@code /catalog/*}</li>
* </ul>
*
* <p>For {@code MultiActionController} it is often useful to use
* this mapping strategy in conjunction with the
* {@link org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver}.
*
* <p>Thanks to Warren Oliver for suggesting the "caseSensitive", "pathPrefix"
* and "basePackage" properties which have been added in Spring 2.5.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.web.servlet.mvc.Controller
* @see org.springframework.web.servlet.mvc.multiaction.MultiActionController
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class ControllerClassNameHandlerMapping extends AbstractControllerUrlHandlerMapping {
/**
* Common suffix at the end of controller implementation classes.
* Removed when generating the URL path.
*/
private static final String CONTROLLER_SUFFIX = "Controller";
private boolean caseSensitive = false;
private String pathPrefix;
private String basePackage;
/**
* Set whether to apply case sensitivity to the generated paths,
* e.g. turning the class name "BuyForm" into "buyForm".
* <p>Default is "false", using pure lower case paths,
* e.g. turning the class name "BuyForm" into "buyform".
*/
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
/**
* Specify a prefix to prepend to the path generated from the controller name.
* <p>Default is a plain slash ("/"). A path like "/mymodule" can be specified
* in order to have controller path mappings prefixed with that path, e.g.
* "/mymodule/buyform" instead of "/buyform" for the class name "BuyForm".
*/
public void setPathPrefix(String prefixPath) {
this.pathPrefix = prefixPath;
if (StringUtils.hasLength(this.pathPrefix)) {
if (!this.pathPrefix.startsWith("/")) {
this.pathPrefix = "/" + this.pathPrefix;
}
if (this.pathPrefix.endsWith("/")) {
this.pathPrefix = this.pathPrefix.substring(0, this.pathPrefix.length() - 1);
}
}
}
/**
* Set the base package to be used for generating path mappings,
* including all subpackages underneath this packages as path elements.
* <p>Default is {@code null}, using the short class name for the
* generated path, with the controller's package not represented in the path.
* Specify a base package like "com.mycompany.myapp" to include subpackages
* within that base package as path elements, e.g. generating the path
* "/mymodule/buyform" for the class name "com.mycompany.myapp.mymodule.BuyForm".
* Subpackage hierarchies are represented as individual path elements,
* e.g. "/mymodule/mysubmodule/buyform" for the class name
* "com.mycompany.myapp.mymodule.mysubmodule.BuyForm".
*/
public void setBasePackage(String basePackage) {
this.basePackage = basePackage;
if (StringUtils.hasLength(this.basePackage) && !this.basePackage.endsWith(".")) {
this.basePackage = this.basePackage + ".";
}
}
@Override
protected String[] buildUrlsForHandler(String beanName, Class<?> beanClass) {
return generatePathMappings(beanClass);
}
/**
* Generate the actual URL paths for the given controller class.
* <p>Subclasses may choose to customize the paths that are generated
* by overriding this method.
* @param beanClass the controller bean class to generate a mapping for
* @return the URL path mappings for the given controller
*/
protected String[] generatePathMappings(Class<?> beanClass) {
StringBuilder pathMapping = buildPathPrefix(beanClass);
String className = ClassUtils.getShortName(beanClass);
String path = (className.endsWith(CONTROLLER_SUFFIX) ?
className.substring(0, className.lastIndexOf(CONTROLLER_SUFFIX)) : className);
if (path.length() > 0) {
if (this.caseSensitive) {
pathMapping.append(path.substring(0, 1).toLowerCase()).append(path.substring(1));
}
else {
pathMapping.append(path.toLowerCase());
}
}
if (isMultiActionControllerType(beanClass)) {
return new String[] {pathMapping.toString(), pathMapping.toString() + "/*"};
}
else {
return new String[] {pathMapping.toString() + "*"};
}
}
/**
* Build a path prefix for the given controller bean class.
* @param beanClass the controller bean class to generate a mapping for
* @return the path prefix, potentially including subpackage names as path elements
*/
private StringBuilder buildPathPrefix(Class<?> beanClass) {
StringBuilder pathMapping = new StringBuilder();
if (this.pathPrefix != null) {
pathMapping.append(this.pathPrefix);
pathMapping.append("/");
}
else {
pathMapping.append("/");
}
if (this.basePackage != null) {
String packageName = ClassUtils.getPackageName(beanClass);
if (packageName.startsWith(this.basePackage)) {
String subPackage = packageName.substring(this.basePackage.length()).replace('.', '/');
pathMapping.append(this.caseSensitive ? subPackage : subPackage.toLowerCase());
pathMapping.append("/");
}
}
return pathMapping;
}
}

40
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/ControllerTypePredicate.java

@ -1,40 +0,0 @@ @@ -1,40 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.support;
import org.springframework.web.servlet.mvc.Controller;
/**
* Internal helper class that identifies controller types.
*
* @author Juergen Hoeller
* @since 2.5.3
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
class ControllerTypePredicate {
public boolean isControllerType(Class<?> beanClass) {
return Controller.class.isAssignableFrom(beanClass);
}
@SuppressWarnings("deprecation")
public boolean isMultiActionControllerType(Class<?> beanClass) {
return org.springframework.web.servlet.mvc.multiaction.MultiActionController.class.isAssignableFrom(beanClass);
}
}

33
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -63,7 +63,6 @@ import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver; @@ -63,7 +63,6 @@ import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
* @see #handleNoSuchRequestHandlingMethod
* @see #handleHttpRequestMethodNotSupported
* @see #handleHttpMediaTypeNotSupported
* @see #handleMissingServletRequestParameter
@ -100,16 +99,11 @@ public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionRes @@ -100,16 +99,11 @@ public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionRes
@Override
@SuppressWarnings("deprecation")
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
try {
if (ex instanceof org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) {
return handleNoSuchRequestHandlingMethod((org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) ex,
request, response, handler);
}
else if (ex instanceof HttpRequestMethodNotSupportedException) {
if (ex instanceof HttpRequestMethodNotSupportedException) {
return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, request,
response, handler);
}
@ -168,29 +162,6 @@ public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionRes @@ -168,29 +162,6 @@ public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionRes
return null;
}
/**
* Handle the case where no request handler method was found.
* <p>The default implementation logs a warning, sends an HTTP 404 error, and returns
* an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen,
* or the NoSuchRequestHandlingMethodException could be rethrown as-is.
* @param ex the NoSuchRequestHandlingMethodException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler, or {@code null} if none chosen
* at the time of the exception (for example, if multipart resolution failed)
* @return an empty ModelAndView indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
* @deprecated as of 4.3, along with {@link org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException}
*/
@Deprecated
protected ModelAndView handleNoSuchRequestHandlingMethod(org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
pageNotFoundLogger.warn(ex.getMessage());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return new ModelAndView();
}
/**
* Handle the case where no request handler method was found for the particular HTTP request method.
* <p>The default implementation logs a warning, sends an HTTP 405 error, sets the "Allow" header,

19
spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java

@ -510,13 +510,8 @@ public class ResourceHttpRequestHandler extends WebContentGenerator @@ -510,13 +510,8 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
* @param resource the resource to check
* @return the corresponding media type, or {@code null} if none found
*/
@SuppressWarnings("deprecation")
protected MediaType getMediaType(HttpServletRequest request, Resource resource) {
// For backwards compatibility
MediaType mediaType = getMediaType(resource);
if (mediaType != null) {
return mediaType;
}
MediaType mediaType = null;
Class<PathExtensionContentNegotiationStrategy> clazz = PathExtensionContentNegotiationStrategy.class;
PathExtensionContentNegotiationStrategy strategy = this.contentNegotiationManager.getStrategy(clazz);
@ -540,18 +535,6 @@ public class ResourceHttpRequestHandler extends WebContentGenerator @@ -540,18 +535,6 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
return mediaType;
}
/**
* Determine an appropriate media type for the given resource.
* @param resource the resource to check
* @return the corresponding media type, or {@code null} if none found
* @deprecated as of 4.3 this method is deprecated; please override
* {@link #getMediaType(HttpServletRequest, Resource)} instead.
*/
@Deprecated
protected MediaType getMediaType(Resource resource) {
return null;
}
/**
* Set headers on the given servlet response.
* Called for GET requests as well as HEAD requests.

49
spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContextUtils.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -60,53 +60,6 @@ public abstract class RequestContextUtils { @@ -60,53 +60,6 @@ public abstract class RequestContextUtils {
public static final String REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME = "requestDataValueProcessor";
/**
* Look for the WebApplicationContext associated with the DispatcherServlet
* that has initiated request processing.
* @param request current HTTP request
* @return the request-specific web application context
* @throws IllegalStateException if no servlet-specific context has been found
* @see #getWebApplicationContext(ServletRequest, ServletContext)
* @deprecated as of Spring 4.2.1, in favor of
* {@link #findWebApplicationContext(HttpServletRequest)}
*/
@Deprecated
public static WebApplicationContext getWebApplicationContext(ServletRequest request) throws IllegalStateException {
return getWebApplicationContext(request, null);
}
/**
* Look for the WebApplicationContext associated with the DispatcherServlet
* that has initiated request processing, and for the global context if none
* was found associated with the current request. This method is useful to
* allow components outside the framework, such as JSP tag handlers,
* to access the most specific application context available.
* @param request current HTTP request
* @param servletContext current servlet context
* @return the request-specific WebApplicationContext, or the global one
* if no request-specific context has been found
* @throws IllegalStateException if neither a servlet-specific nor a
* global context has been found
* @see DispatcherServlet#WEB_APPLICATION_CONTEXT_ATTRIBUTE
* @see WebApplicationContextUtils#getRequiredWebApplicationContext(ServletContext)
* @deprecated as of Spring 4.2.1, in favor of
* {@link #findWebApplicationContext(HttpServletRequest, ServletContext)}
*/
@Deprecated
public static WebApplicationContext getWebApplicationContext(
ServletRequest request, ServletContext servletContext) throws IllegalStateException {
WebApplicationContext webApplicationContext = (WebApplicationContext) request.getAttribute(
DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
if (webApplicationContext == null) {
if (servletContext == null) {
throw new IllegalStateException("No WebApplicationContext found: not in a DispatcherServlet request?");
}
webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
}
return webApplicationContext;
}
/**
* Look for the WebApplicationContext associated with the DispatcherServlet
* that has initiated request processing, and for the global context if none

32
spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java

@ -143,27 +143,6 @@ public class FormTag extends AbstractHtmlElementTag { @@ -143,27 +143,6 @@ public class FormTag extends AbstractHtmlElementTag {
return this.modelAttribute;
}
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
* @see #setModelAttribute
* @deprecated as of Spring 4.3, in favor of {@link #setModelAttribute}
*/
@Deprecated
public void setCommandName(String commandName) {
this.modelAttribute = commandName;
}
/**
* Get the name of the form attribute in the model.
* @see #getModelAttribute
* @deprecated as of Spring 4.3, in favor of {@link #getModelAttribute}
*/
@Deprecated
protected String getCommandName() {
return this.modelAttribute;
}
/**
* Set the value of the '{@code name}' attribute.
* <p>May be a runtime expression.
@ -331,18 +310,7 @@ public class FormTag extends AbstractHtmlElementTag { @@ -331,18 +310,7 @@ public class FormTag extends AbstractHtmlElementTag {
* Get the name of the request param for non-browser supported HTTP methods.
* @since 4.2.3
*/
@SuppressWarnings("deprecation")
protected String getMethodParam() {
return getMethodParameter();
}
/**
* Get the name of the request param for non-browser supported HTTP methods.
* @deprecated as of 4.2.3, in favor of {@link #getMethodParam()} which is
* a proper pairing for {@link #setMethodParam(String)}
*/
@Deprecated
protected String getMethodParameter() {
return this.methodParam;
}

5
spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -397,9 +397,8 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext { @@ -397,9 +397,8 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext {
public static class ComplexLocaleChecker implements MyHandler {
@Override
@SuppressWarnings("deprecation")
public void doSomething(HttpServletRequest request) throws ServletException, IllegalAccessException {
WebApplicationContext wac = RequestContextUtils.getWebApplicationContext(request);
WebApplicationContext wac = RequestContextUtils.findWebApplicationContext(request);
if (!(wac instanceof ComplexWebApplicationContext)) {
throw new ServletException("Incorrect WebApplicationContext");
}

32
spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java

@ -699,38 +699,6 @@ public class DispatcherServletTests { @@ -699,38 +699,6 @@ public class DispatcherServletTests {
assertNull(myServlet.getServletConfig());
}
@Test
@SuppressWarnings("deprecation")
public void webApplicationContextLookup() {
MockServletContext servletContext = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/invalid.do");
try {
RequestContextUtils.getWebApplicationContext(request);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
RequestContextUtils.getWebApplicationContext(request, servletContext);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
new StaticWebApplicationContext());
try {
RequestContextUtils.getWebApplicationContext(request, servletContext);
}
catch (IllegalStateException ex) {
fail("Should not have thrown IllegalStateException: " + ex.getMessage());
}
}
@Test
public void withNoView() throws Exception {
MockServletContext servletContext = new MockServletContext();

5
spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -74,10 +74,9 @@ public class SimpleWebApplicationContext extends StaticWebApplicationContext { @@ -74,10 +74,9 @@ public class SimpleWebApplicationContext extends StaticWebApplicationContext {
public static class LocaleChecker implements Controller, LastModified {
@Override
@SuppressWarnings("deprecation")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (!(RequestContextUtils.getWebApplicationContext(request) instanceof SimpleWebApplicationContext)) {
if (!(RequestContextUtils.findWebApplicationContext(request) instanceof SimpleWebApplicationContext)) {
throw new ServletException("Incorrect WebApplicationContext");
}
if (!(RequestContextUtils.getLocaleResolver(request) instanceof AcceptHeaderLocaleResolver)) {

27
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/AdminController.java

@ -1,27 +0,0 @@ @@ -1,27 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.annotation;
import org.springframework.stereotype.Controller;
/**
* @author Juergen Hoeller
*/
@Controller
public class AdminController {
}

52
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/BookController.java

@ -1,52 +0,0 @@ @@ -1,52 +0,0 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.annotation;
import java.io.IOException;
import java.io.Writer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Used for testing the combination of ControllerClassNameHandlerMapping/SimpleUrlHandlerMapping with @RequestParam in
* {@link ServletAnnotationControllerTests}. Implemented as a top-level class (rather than an inner class) to make the
* ControllerClassNameHandlerMapping work.
*
* @author Arjen Poutsma
*/
@Controller
public class BookController {
@RequestMapping("list")
public void list(Writer writer) throws IOException {
writer.write("list");
}
@RequestMapping("show")
public void show(@RequestParam(required = true) Long id, Writer writer) throws IOException {
writer.write("show-id=" + id);
}
@RequestMapping(method = RequestMethod.POST)
public void create(Writer writer) throws IOException {
writer.write("create");
}
}

27
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/BuyForm.java

@ -1,27 +0,0 @@ @@ -1,27 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.annotation;
import org.springframework.stereotype.Controller;
/**
* @author Juergen Hoeller
*/
@Controller
public class BuyForm {
}

16
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/CgLibProxyServletAnnotationTests.java → spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/CglibProxyControllerTests.java

@ -25,7 +25,6 @@ import org.junit.Test; @@ -25,7 +25,6 @@ import org.junit.Test;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.aop.interceptor.SimpleTraceInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
@ -42,10 +41,11 @@ import static org.junit.Assert.*; @@ -42,10 +41,11 @@ import static org.junit.Assert.*;
* @author Arjen Poutsma
* @since 3.0
*/
public class CgLibProxyServletAnnotationTests {
public class CglibProxyControllerTests {
private DispatcherServlet servlet;
@Test
public void typeLevel() throws Exception {
initServlet(TypeLevelImpl.class);
@ -78,13 +78,12 @@ public class CgLibProxyServletAnnotationTests { @@ -78,13 +78,12 @@ public class CgLibProxyServletAnnotationTests {
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerclass) throws ServletException {
private void initServlet(final Class<?> controllerClass) throws ServletException {
servlet = new DispatcherServlet() {
@Override
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
throws BeansException {
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass));
wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass));
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
autoProxyCreator.setProxyTargetClass(true);
autoProxyCreator.setBeanFactory(wac.getBeanFactory());
@ -97,9 +96,6 @@ public class CgLibProxyServletAnnotationTests { @@ -97,9 +96,6 @@ public class CgLibProxyServletAnnotationTests {
servlet.init(new MockServletConfig());
}
/*
* Controllers
*/
@Controller
@RequestMapping("/test")
@ -111,6 +107,7 @@ public class CgLibProxyServletAnnotationTests { @@ -111,6 +107,7 @@ public class CgLibProxyServletAnnotationTests {
}
}
@Controller
public static class MethodLevelImpl {
@ -120,6 +117,7 @@ public class CgLibProxyServletAnnotationTests { @@ -120,6 +117,7 @@ public class CgLibProxyServletAnnotationTests {
}
}
@Controller
@RequestMapping("/hotels")
public static class TypeAndMethodLevelImpl {

40
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ControllerClassNameController.java

@ -1,40 +0,0 @@ @@ -1,40 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.annotation;
import java.io.IOException;
import java.io.Writer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/** @author Arjen Poutsma */
@Controller
public class ControllerClassNameController {
@RequestMapping(value = {"{id}", "{id}.*"}, method = RequestMethod.GET)
public void plain(Writer writer, @PathVariable("id") String id) throws IOException {
writer.write("plain-" + id);
}
@RequestMapping(value = "{id}.pdf", method = RequestMethod.GET)
public void pdf(Writer writer, @PathVariable("id") String id) throws IOException {
writer.write("pdf-" + id);
}
}

128
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ControllerClassNameHandlerMappingTests.java

@ -1,128 +0,0 @@ @@ -1,128 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.annotation;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class ControllerClassNameHandlerMappingTests {
private static final String LOCATION = "/org/springframework/web/servlet/mvc/annotation/class-mapping.xml";
private final XmlWebApplicationContext wac = new XmlWebApplicationContext();
private HandlerMapping hm, hm2, hm3, hm4;
@Before
public void setUp() throws Exception {
this.wac.setServletContext(new MockServletContext(""));
this.wac.setConfigLocations(LOCATION);
this.wac.refresh();
this.hm = (HandlerMapping) this.wac.getBean("mapping");
this.hm2 = (HandlerMapping) this.wac.getBean("mapping2");
this.hm3 = (HandlerMapping) this.wac.getBean("mapping3");
this.hm4 = (HandlerMapping) this.wac.getBean("mapping4");
}
@After
public void closeWac() {
this.wac.close();
}
@Test
public void indexUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
request = new MockHttpServletRequest("GET", "/index/product");
chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
}
@Test
public void mapSimpleUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
request = new MockHttpServletRequest("GET", "/welcome/product");
chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withContextPath() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
request.setContextPath("/myapp");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buyform");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
request = new MockHttpServletRequest("GET", "/buyform/product");
chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
@Test
public void withBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/annotation/welcome");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withBasePackageAndCaseSensitive() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/annotation/buyForm");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
@Test
public void withFullBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
HandlerExecutionChain chain = this.hm3.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withRootAsBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/org/springframework/web/servlet/mvc/annotation/welcome");
HandlerExecutionChain chain = this.hm4.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
}

37
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/IndexController.java

@ -1,37 +0,0 @@ @@ -1,37 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.annotation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Juergen Hoeller
*/
@Controller
public class IndexController {
@RequestMapping
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView("indexView");
}
}

17
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/JdkProxyServletAnnotationTests.java → spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/JdkProxyControllerTests.java

@ -25,7 +25,6 @@ import org.junit.Test; @@ -25,7 +25,6 @@ import org.junit.Test;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.aop.interceptor.SimpleTraceInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
@ -42,10 +41,11 @@ import static org.junit.Assert.*; @@ -42,10 +41,11 @@ import static org.junit.Assert.*;
* @author Arjen Poutsma
* @since 3.0
*/
public class JdkProxyServletAnnotationTests {
public class JdkProxyControllerTests {
private DispatcherServlet servlet;
@Test
public void typeLevel() throws Exception {
initServlet(TypeLevelImpl.class);
@ -81,8 +81,7 @@ public class JdkProxyServletAnnotationTests { @@ -81,8 +81,7 @@ public class JdkProxyServletAnnotationTests {
private void initServlet(final Class<?> controllerclass) throws ServletException {
servlet = new DispatcherServlet() {
@Override
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
throws BeansException {
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass));
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
@ -96,9 +95,6 @@ public class JdkProxyServletAnnotationTests { @@ -96,9 +95,6 @@ public class JdkProxyServletAnnotationTests {
servlet.init(new MockServletConfig());
}
/*
* Controllers
*/
@Controller
@RequestMapping("/test")
@ -106,9 +102,9 @@ public class JdkProxyServletAnnotationTests { @@ -106,9 +102,9 @@ public class JdkProxyServletAnnotationTests {
@RequestMapping
void doIt(Writer writer) throws IOException;
}
public static class TypeLevelImpl implements TypeLevel {
@Override
@ -123,9 +119,9 @@ public class JdkProxyServletAnnotationTests { @@ -123,9 +119,9 @@ public class JdkProxyServletAnnotationTests {
@RequestMapping("/test")
void doIt(Writer writer) throws IOException;
}
public static class MethodLevelImpl implements MethodLevel {
@Override
@ -134,15 +130,16 @@ public class JdkProxyServletAnnotationTests { @@ -134,15 +130,16 @@ public class JdkProxyServletAnnotationTests {
}
}
@Controller
@RequestMapping("/hotels")
public interface TypeAndMethodLevel {
@RequestMapping("/bookings")
void doIt(Writer writer) throws IOException;
}
public static class TypeAndMethodLevelImpl implements TypeAndMethodLevel {
@Override

53
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/MethodNameDispatchingController.java

@ -1,53 +0,0 @@ @@ -1,53 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.annotation;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author Juergen Hoeller
*/
@Controller
@RequestMapping("/*.do")
public class MethodNameDispatchingController {
@RequestMapping
public void myHandle(HttpServletResponse response) throws IOException {
response.getWriter().write("myView");
}
@RequestMapping
public void myOtherHandle(HttpServletResponse response) throws IOException {
response.getWriter().write("myOtherView");
}
@RequestMapping(method = RequestMethod.POST)
public void myLangHandle(HttpServletResponse response) throws IOException {
response.getWriter().write("myLangView");
}
@RequestMapping(method = RequestMethod.POST)
public void mySurpriseHandle(HttpServletResponse response) throws IOException {
response.getWriter().write("mySurpriseView");
}
}

37
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/WelcomeController.java

@ -1,37 +0,0 @@ @@ -1,37 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.annotation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Juergen Hoeller
*/
@Controller
public class WelcomeController {
@RequestMapping
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView("welcomeView");
}
}

26
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/AdminController.java

@ -1,26 +0,0 @@ @@ -1,26 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.mapping;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
/**
* @author Rob Harrop
*/
public class AdminController extends MultiActionController {
}

32
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/BuyForm.java

@ -1,32 +0,0 @@ @@ -1,32 +0,0 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.mapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class BuyForm implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return null;
}
}

34
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/Controller.java

@ -1,34 +0,0 @@ @@ -1,34 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.mapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Juergen Hoeller
*/
public class Controller implements org.springframework.web.servlet.mvc.Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView("indexView");
}
}

92
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerBeanNameHandlerMappingTests.java

@ -1,92 +0,0 @@ @@ -1,92 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.mapping;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class ControllerBeanNameHandlerMappingTests {
private static final String LOCATION = "/org/springframework/web/servlet/mvc/mapping/name-mapping.xml";
private final XmlWebApplicationContext wac = new XmlWebApplicationContext();
private HandlerMapping hm;
@Before
public void setUp() throws Exception {
this.wac.setServletContext(new MockServletContext(""));
this.wac.setConfigLocations(LOCATION);
this.wac.refresh();
this.hm = this.wac.getBean(HandlerMapping.class);
}
@After
public void closeWac() {
this.wac.close();
}
@Test
public void indexUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
}
@Test
public void mapSimpleUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withContextPath() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
request.setContextPath("/myapp");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withMultiActionControllerMapping() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("admin"), chain.getHandler());
}
@Test
public void withoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buy");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
}

130
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerClassNameHandlerMappingTests.java

@ -1,130 +0,0 @@ @@ -1,130 +0,0 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.mapping;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class ControllerClassNameHandlerMappingTests {
public static final String LOCATION = "/org/springframework/web/servlet/mvc/mapping/class-mapping.xml";
private XmlWebApplicationContext wac;
private HandlerMapping hm;
private HandlerMapping hm2;
private HandlerMapping hm3;
private HandlerMapping hm4;
@Before
public void setUp() throws Exception {
MockServletContext sc = new MockServletContext("");
this.wac = new XmlWebApplicationContext();
this.wac.setServletContext(sc);
this.wac.setConfigLocations(new String[] {LOCATION});
this.wac.refresh();
this.hm = (HandlerMapping) this.wac.getBean("mapping");
this.hm2 = (HandlerMapping) this.wac.getBean("mapping2");
this.hm3 = (HandlerMapping) this.wac.getBean("mapping3");
this.hm4 = (HandlerMapping) this.wac.getBean("mapping4");
}
@Test
public void indexUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
}
@Test
public void mapSimpleUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withContextPath() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
request.setContextPath("/myapp");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withMultiActionControllerMapping() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/user");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("admin"), chain.getHandler());
request = new MockHttpServletRequest("GET", "/admin/product");
chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("admin"), chain.getHandler());
}
@Test
public void withoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buyform");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
@Test
public void withBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/mapping/welcome");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withBasePackageAndCaseSensitive() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/mapping/buyForm");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
@Test
public void withFullBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
HandlerExecutionChain chain = this.hm3.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withRootAsBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/org/springframework/web/servlet/mvc/mapping/welcome");
HandlerExecutionChain chain = this.hm4.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
}

35
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/WelcomeController.java

@ -1,35 +0,0 @@ @@ -1,35 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.mapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
* @author Rob Harrop
*/
public class WelcomeController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView("welcomeView");
}
}

8
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandlerTests.java

@ -53,7 +53,6 @@ import org.springframework.web.context.request.WebRequest; @@ -53,7 +53,6 @@ import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
import static org.junit.Assert.*;
@ -103,12 +102,6 @@ public class ResponseEntityExceptionHandlerTests { @@ -103,12 +102,6 @@ public class ResponseEntityExceptionHandlerTests {
}
}
@Test
public void noSuchRequestHandlingMethod() {
Exception ex = new NoSuchRequestHandlingMethodException("GET", TestController.class);
testException(ex);
}
@Test
public void httpRequestMethodNotSupported() {
List<String> supported = Arrays.asList("POST", "DELETE");
@ -116,7 +109,6 @@ public class ResponseEntityExceptionHandlerTests { @@ -116,7 +109,6 @@ public class ResponseEntityExceptionHandlerTests {
ResponseEntity<Object> responseEntity = testException(ex);
assertEquals(EnumSet.of(HttpMethod.POST, HttpMethod.DELETE), responseEntity.getHeaders().getAllow());
}
@Test

45
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java

@ -128,7 +128,6 @@ import org.springframework.web.context.WebApplicationContext; @@ -128,7 +128,6 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
@ -1786,10 +1785,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @@ -1786,10 +1785,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
/*
* Controllers
*/
@Controller
static class ControllerWithEmptyValueMapping {
@ -2501,7 +2496,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @@ -2501,7 +2496,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
@Retention(RetentionPolicy.RUNTIME)
@Controller
public @interface MyControllerAnnotation {
}
@MyControllerAnnotation
@ -2935,7 +2929,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @@ -2935,7 +2929,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
public static class MyEntity {
}
@Controller
@ -2964,8 +2957,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @@ -2964,8 +2957,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
@RequestMapping("/multiValueMap")
public void multiValueMap(@RequestParam MultiValueMap<String, String> params, Writer writer)
throws IOException {
public void multiValueMap(@RequestParam MultiValueMap<String, String> params, Writer writer) throws IOException {
for (Iterator<Map.Entry<String, List<String>>> it1 = params.entrySet().iterator(); it1.hasNext();) {
Map.Entry<String, List<String>> entry = it1.next();
writer.write(entry.getKey() + "=[");
@ -3135,7 +3127,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @@ -3135,7 +3127,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
setValue(null);
}
}
}
@Controller
@ -3174,6 +3165,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @@ -3174,6 +3165,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
@Controller
@RequestMapping("/t1")
protected static class NoPathGetAndM2PostController {
@RequestMapping(method = RequestMethod.GET)
public void handle1(Writer writer) throws IOException {
writer.write("handle1");
@ -3309,37 +3301,4 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @@ -3309,37 +3301,4 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
}
// Test cases deleted from the original ServletAnnotationControllerTests:
// @Ignore("Controller interface => no method-level @RequestMapping annotation")
// public void standardHandleMethod() throws Exception {
// @Ignore("ControllerClassNameHandlerMapping")
// public void emptyRequestMapping() throws Exception {
// @Ignore("Controller interface => no method-level @RequestMapping annotation")
// public void proxiedStandardHandleMethod() throws Exception {
// @Ignore("ServletException no longer thrown for unmatched parameter constraints")
// public void constrainedParameterDispatchingController() throws Exception {
// @Ignore("Method name dispatching")
// public void methodNameDispatchingController() throws Exception {
// @Ignore("Method name dispatching")
// public void methodNameDispatchingControllerWithSuffix() throws Exception {
// @Ignore("ControllerClassNameHandlerMapping")
// public void controllerClassNamePlusMethodNameDispatchingController() throws Exception {
// @Ignore("Method name dispatching")
// public void postMethodNameDispatchingController() throws Exception {
// @Ignore("ControllerClassNameHandlerMapping")
// public void controllerClassNameNoTypeLevelAnn() throws Exception {
// @Ignore("SimpleUrlHandlerMapping")
// public void simpleUrlHandlerMapping() throws Exception {
}

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

Loading…
Cancel
Save