Browse Source

Polishing

pull/689/head
Juergen Hoeller 12 years ago
parent
commit
c0a4631fd1
  1. 17
      buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy
  2. 10
      buildSrc/src/main/groovy/org/springframework/build/gradle/TestSourceSetDependenciesPlugin.groovy
  3. 6
      spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java
  4. 49
      spring-aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java
  5. 4
      spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj
  6. 41
      spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj
  7. 3
      spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java
  8. 11
      spring-beans/src/main/java/org/springframework/beans/PropertyMatches.java
  9. 34
      spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
  10. 2
      spring-beans/src/main/java/org/springframework/beans/factory/xml/AbstractSimpleBeanDefinitionParser.java
  11. 31
      spring-beans/src/main/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandler.java
  12. 11
      spring-beans/src/main/java/org/springframework/beans/propertyeditors/ResourceBundleEditor.java
  13. 6
      spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java
  14. 18
      spring-context/src/main/java/org/springframework/format/AnnotationFormatterFactory.java
  15. 83
      spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java
  16. 38
      spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassPreProcessorAdapter.java
  17. 2
      spring-context/src/main/java/org/springframework/jmx/export/annotation/AnnotationJmxAttributeSource.java
  18. 4
      spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java
  19. 10
      spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java
  20. 2
      spring-context/src/main/java/org/springframework/validation/DefaultMessageCodesResolver.java
  21. 30
      spring-core/src/main/java/org/springframework/asm/package-info.java
  22. 44
      spring-core/src/main/java/org/springframework/core/convert/Property.java
  23. 14
      spring-core/src/main/java/org/springframework/core/convert/support/ArrayToArrayConverter.java
  24. 7
      spring-core/src/main/java/org/springframework/core/convert/support/ArrayToStringConverter.java
  25. 15
      spring-core/src/main/java/org/springframework/core/convert/support/MapToMapConverter.java
  26. 17
      spring-core/src/main/java/org/springframework/core/convert/support/StringToCollectionConverter.java
  27. 11
      spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java
  28. 2
      spring-core/src/main/java/org/springframework/core/convert/support/StringToUUIDConverter.java
  29. 4
      spring-core/src/main/java/org/springframework/core/io/AbstractResource.java
  30. 2
      spring-core/src/main/java/org/springframework/util/ObjectUtils.java
  31. 8
      spring-core/src/main/java/org/springframework/util/StopWatch.java
  32. 21
      spring-core/src/main/java/org/springframework/util/comparator/InstanceComparator.java
  33. 1
      spring-core/src/main/java/org/springframework/util/comparator/package-info.java
  34. 437
      spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java
  35. 57
      spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/GenericCallMetaDataProvider.java
  36. 69
      spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/GenericTableMetaDataProvider.java
  37. 24
      spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslator.java
  38. 8
      spring-jms/src/main/java/org/springframework/jms/connection/SingleConnectionFactory.java
  39. 8
      spring-jms/src/main/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactory.java
  40. 8
      spring-jms/src/main/java/org/springframework/jms/listener/endpoint/StandardJmsActivationSpecFactory.java
  41. 10
      spring-jms/src/main/java/org/springframework/jms/support/JmsAccessor.java
  42. 43
      spring-test/src/main/java/org/springframework/test/context/support/AbstractDelegatingSmartContextLoader.java
  43. 40
      spring-test/src/main/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtils.java
  44. 8
      spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java
  45. 8
      spring-web/src/main/java/org/springframework/http/converter/feed/AbstractWireFeedHttpMessageConverter.java
  46. 3
      spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java
  47. 81
      spring-web/src/main/java/org/springframework/web/filter/CompositeFilter.java
  48. 88
      spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java
  49. 2
      spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java
  50. 38
      spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java
  51. 4
      spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java
  52. 4
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/ProducesRequestCondition.java
  53. 2
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/RequestMethodsRequestCondition.java
  54. 39
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java
  55. 3
      spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/OptionsTag.java
  56. 19
      spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/PasswordInputTag.java

17
buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy

@ -21,20 +21,17 @@ import org.gradle.api.artifacts.Configuration @@ -21,20 +21,17 @@ import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ProjectDependency;
import org.gradle.api.artifacts.maven.Conf2ScopeMapping
import org.gradle.api.plugins.MavenPlugin
import org.gradle.api.tasks.*
import org.gradle.plugins.ide.eclipse.EclipsePlugin
import org.gradle.plugins.ide.eclipse.model.EclipseClasspath;
import org.gradle.plugins.ide.idea.IdeaPlugin
import org.gradle.api.invocation.*
/**
* Gradle plugin that allows projects to merged together. Primarily developed to
* allow Spring to support multiple multiple incompatible versions of third-party
* allow Spring to support multiple incompatible versions of third-party
* dependencies (for example Hibernate v3 and v4).
* <p>
* The 'merge' extension should be used to define how projects are merged, for example:
* <pre>
* <pre class="code">
* configure(subprojects) {
* apply plugin: MergePlugin
* }
@ -76,13 +73,13 @@ class MergePlugin implements Plugin<Project> { @@ -76,13 +73,13 @@ class MergePlugin implements Plugin<Project> {
// Hook to perform the actual merge logic
project.afterEvaluate{
if(it.merge.into != null) {
if (it.merge.into != null) {
setup(it)
}
}
// Hook to build runtimeMerge dependencies
if(!attachedProjectsEvaluated) {
if (!attachedProjectsEvaluated) {
project.gradle.projectsEvaluated{
postProcessProjects(it)
}
@ -102,7 +99,7 @@ class MergePlugin implements Plugin<Project> { @@ -102,7 +99,7 @@ class MergePlugin implements Plugin<Project> {
// invoking a task will invoke the task with the same name on 'into' project
["sourcesJar", "jar", "javadocJar", "javadoc", "install", "artifactoryPublish"].each {
def task = project.tasks.findByPath(it)
if(task) {
if (task) {
task.enabled = false
task.dependsOn(project.merge.into.tasks.findByPath(it))
}
@ -120,7 +117,7 @@ class MergePlugin implements Plugin<Project> { @@ -120,7 +117,7 @@ class MergePlugin implements Plugin<Project> {
private void setupMaven(Project project) {
project.configurations.each { configuration ->
Conf2ScopeMapping mapping = project.conf2ScopeMappings.getMapping([configuration])
if(mapping.scope) {
if (mapping.scope) {
Configuration intoConfiguration = project.merge.into.configurations.create(
project.name + "-" + configuration.name)
configuration.excludeRules.each {
@ -131,7 +128,7 @@ class MergePlugin implements Plugin<Project> { @@ -131,7 +128,7 @@ class MergePlugin implements Plugin<Project> {
configuration.dependencies.each {
def intoCompile = project.merge.into.configurations.getByName("compile")
// Protect against changing a compile scope dependency (SPR-10218)
if(!intoCompile.dependencies.contains(it)) {
if (!intoCompile.dependencies.contains(it)) {
intoConfiguration.dependencies.add(it)
}
}

10
buildSrc/src/main/groovy/org/springframework/build/gradle/TestSourceSetDependenciesPlugin.groovy

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@ -21,7 +21,6 @@ import org.gradle.api.Project @@ -21,7 +21,6 @@ import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ProjectDependency;
/**
* Gradle plugin that automatically updates testCompile dependencies to include
* the test source sets of project dependencies.
@ -41,11 +40,10 @@ class TestSourceSetDependenciesPlugin implements Plugin<Project> { @@ -41,11 +40,10 @@ class TestSourceSetDependenciesPlugin implements Plugin<Project> {
}
}
private void collectProjectDependencies(Set<ProjectDependency> projectDependencies,
Project project) {
for(def configurationName in ["compile", "optional", "provided", "testCompile"]) {
private void collectProjectDependencies(Set<ProjectDependency> projectDependencies, Project project) {
for (def configurationName in ["compile", "optional", "provided", "testCompile"]) {
Configuration configuration = project.getConfigurations().findByName(configurationName)
if(configuration) {
if (configuration) {
configuration.dependencies.findAll { it instanceof ProjectDependency }.each {
projectDependencies.add(it)
collectProjectDependencies(projectDependencies, it.dependencyProject)

6
spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java

@ -212,8 +212,10 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa @@ -212,8 +212,10 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
} else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);
}
else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
return retVal;
}

49
spring-aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -151,7 +151,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { @@ -151,7 +151,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor {
/**
* The {@code Set} of allowed placeholders.
*/
private static final Set ALLOWED_PLACEHOLDERS =
private static final Set<Object> ALLOWED_PLACEHOLDERS =
new Constants(CustomizableTraceInterceptor.class).getValues("PLACEHOLDER_");
@ -258,7 +258,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { @@ -258,7 +258,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor {
return returnValue;
}
catch (Throwable ex) {
if(stopWatch.isRunning()) {
if (stopWatch.isRunning()) {
stopWatch.stop();
}
exitThroughException = true;
@ -268,7 +268,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { @@ -268,7 +268,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor {
}
finally {
if (!exitThroughException) {
if(stopWatch.isRunning()) {
if (stopWatch.isRunning()) {
stopWatch.stop();
}
writeToLog(logger,
@ -325,18 +325,19 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { @@ -325,18 +325,19 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor {
while (matcher.find()) {
String match = matcher.group();
if (PLACEHOLDER_METHOD_NAME.equals(match)) {
matcher.appendReplacement(output, escape(methodInvocation.getMethod().getName()));
matcher.appendReplacement(output, Matcher.quoteReplacement(methodInvocation.getMethod().getName()));
}
else if (PLACEHOLDER_TARGET_CLASS_NAME.equals(match)) {
String className = getClassForLogging(methodInvocation.getThis()).getName();
matcher.appendReplacement(output, escape(className));
matcher.appendReplacement(output, Matcher.quoteReplacement(className));
}
else if (PLACEHOLDER_TARGET_CLASS_SHORT_NAME.equals(match)) {
String shortName = ClassUtils.getShortName(getClassForLogging(methodInvocation.getThis()));
matcher.appendReplacement(output, escape(shortName));
matcher.appendReplacement(output, Matcher.quoteReplacement(shortName));
}
else if (PLACEHOLDER_ARGUMENTS.equals(match)) {
matcher.appendReplacement(output, escape(StringUtils.arrayToCommaDelimitedString(methodInvocation.getArguments())));
matcher.appendReplacement(output,
Matcher.quoteReplacement(StringUtils.arrayToCommaDelimitedString(methodInvocation.getArguments())));
}
else if (PLACEHOLDER_ARGUMENT_TYPES.equals(match)) {
appendArgumentTypes(methodInvocation, matcher, output);
@ -345,7 +346,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { @@ -345,7 +346,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor {
appendReturnValue(methodInvocation, matcher, output, returnValue);
}
else if (throwable != null && PLACEHOLDER_EXCEPTION.equals(match)) {
matcher.appendReplacement(output, escape(throwable.toString()));
matcher.appendReplacement(output, Matcher.quoteReplacement(throwable.toString()));
}
else if (PLACEHOLDER_INVOCATION_TIME.equals(match)) {
matcher.appendReplacement(output, Long.toString(invocationTime));
@ -379,7 +380,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { @@ -379,7 +380,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor {
matcher.appendReplacement(output, "null");
}
else {
matcher.appendReplacement(output, escape(returnValue.toString()));
matcher.appendReplacement(output, Matcher.quoteReplacement(returnValue.toString()));
}
}
@ -394,12 +395,13 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { @@ -394,12 +395,13 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor {
* @param output the {@code StringBuffer} containing the output
*/
private void appendArgumentTypes(MethodInvocation methodInvocation, Matcher matcher, StringBuffer output) {
Class[] argumentTypes = methodInvocation.getMethod().getParameterTypes();
Class<?>[] argumentTypes = methodInvocation.getMethod().getParameterTypes();
String[] argumentTypeShortNames = new String[argumentTypes.length];
for (int i = 0; i < argumentTypeShortNames.length; i++) {
argumentTypeShortNames[i] = ClassUtils.getShortName(argumentTypes[i]);
}
matcher.appendReplacement(output, escape(StringUtils.arrayToCommaDelimitedString(argumentTypeShortNames)));
matcher.appendReplacement(output,
Matcher.quoteReplacement(StringUtils.arrayToCommaDelimitedString(argumentTypeShortNames)));
}
/**
@ -417,27 +419,4 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { @@ -417,27 +419,4 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor {
}
}
/**
* Replaces {@code $} in inner class names with {@code \$}.
* <p>This code is equivalent to JDK 1.5's {@code quoteReplacement}
* method in the Matcher class itself. We're keeping our own version
* here for JDK 1.4 compliance reasons only.
*/
private String escape(String input) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == '\\') {
sb.append("\\\\");
}
else if (c == '$') {
sb.append("\\$");
}
else {
sb.append(c);
}
}
return sb.toString();
}
}

4
spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj

@ -46,7 +46,7 @@ public abstract aspect AbstractDependencyInjectionAspect { @@ -46,7 +46,7 @@ public abstract aspect AbstractDependencyInjectionAspect {
* Select join points in beans to be configured prior to construction?
* By default, use post-construction injection matching the default in the Configurable annotation.
*/
public pointcut preConstructionConfiguration() : if(false);
public pointcut preConstructionConfiguration() : if (false);
/**
* Select the most-specific initialization join point
@ -54,7 +54,7 @@ public abstract aspect AbstractDependencyInjectionAspect { @@ -54,7 +54,7 @@ public abstract aspect AbstractDependencyInjectionAspect {
*/
@CodeGenerationHint(ifNameSuffix="6f1")
public pointcut mostSpecificSubTypeConstruction() :
if(thisJoinPoint.getSignature().getDeclaringType() == thisJoinPoint.getThis().getClass());
if (thisJoinPoint.getSignature().getDeclaringType() == thisJoinPoint.getThis().getClass());
/**
* Select least specific super type that is marked for DI (so that injection occurs only once with pre-construction inejection

41
spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@ -19,7 +19,7 @@ package org.springframework.beans.factory.aspectj; @@ -19,7 +19,7 @@ package org.springframework.beans.factory.aspectj;
import java.io.Serializable;
import org.aspectj.lang.annotation.control.CodeGenerationHint;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
@ -44,48 +44,47 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport; @@ -44,48 +44,47 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport;
* @see org.springframework.beans.factory.annotation.Configurable
* @see org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver
*/
public aspect AnnotationBeanConfigurerAspect
extends AbstractInterfaceDrivenDependencyInjectionAspect
public aspect AnnotationBeanConfigurerAspect extends AbstractInterfaceDrivenDependencyInjectionAspect
implements BeanFactoryAware, InitializingBean, DisposableBean {
private BeanConfigurerSupport beanConfigurerSupport = new BeanConfigurerSupport();
public pointcut inConfigurableBean() : @this(Configurable);
public pointcut preConstructionConfiguration() : preConstructionConfigurationSupport(*);
declare parents: @Configurable * implements ConfigurableObject;
public void configureBean(Object bean) {
beanConfigurerSupport.configureBean(bean);
public void setBeanFactory(BeanFactory beanFactory) {
this.beanConfigurerSupport.setBeanFactory(beanFactory);
this.beanConfigurerSupport.setBeanWiringInfoResolver(new AnnotationBeanWiringInfoResolver());
}
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
beanConfigurerSupport.setBeanFactory(beanFactory);
beanConfigurerSupport.setBeanWiringInfoResolver(new AnnotationBeanWiringInfoResolver());
public void afterPropertiesSet() throws Exception {
this.beanConfigurerSupport.afterPropertiesSet();
}
public void afterPropertiesSet() throws Exception {
beanConfigurerSupport.afterPropertiesSet();
public void configureBean(Object bean) {
this.beanConfigurerSupport.configureBean(bean);
}
public void destroy() throws Exception {
beanConfigurerSupport.destroy();
this.beanConfigurerSupport.destroy();
}
public pointcut inConfigurableBean() : @this(Configurable);
public pointcut preConstructionConfiguration() : preConstructionConfigurationSupport(*);
/*
* An intermediary to match preConstructionConfiguration signature (that doesn't expose the annotation object)
*/
@CodeGenerationHint(ifNameSuffix="bb0")
private pointcut preConstructionConfigurationSupport(Configurable c) : @this(c) && if(c.preConstruction());
private pointcut preConstructionConfigurationSupport(Configurable c) : @this(c) && if (c.preConstruction());
declare parents: @Configurable * implements ConfigurableObject;
/*
* This declaration shouldn't be needed,
* except for an AspectJ bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=214559)
*/
declare parents: @Configurable Serializable+
implements ConfigurableDeserializationSupport;
declare parents: @Configurable Serializable+ implements ConfigurableDeserializationSupport;
}

3
spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java

@ -389,7 +389,8 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra @@ -389,7 +389,8 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
if (pd.getReadMethod() != null || pd.getWriteMethod() != null) {
return TypeDescriptor.nested(property(pd), tokens.keys.length);
}
} else {
}
else {
if (pd.getReadMethod() != null || pd.getWriteMethod() != null) {
return new TypeDescriptor(property(pd));
}

11
spring-beans/src/main/java/org/springframework/beans/PropertyMatches.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -49,7 +49,7 @@ final class PropertyMatches { @@ -49,7 +49,7 @@ final class PropertyMatches {
* @param propertyName the name of the property to find possible matches for
* @param beanClass the bean class to search for matches
*/
public static PropertyMatches forProperty(String propertyName, Class beanClass) {
public static PropertyMatches forProperty(String propertyName, Class<?> beanClass) {
return forProperty(propertyName, beanClass, DEFAULT_MAX_DISTANCE);
}
@ -59,7 +59,7 @@ final class PropertyMatches { @@ -59,7 +59,7 @@ final class PropertyMatches {
* @param beanClass the bean class to search for matches
* @param maxDistance the maximum property distance allowed for matches
*/
public static PropertyMatches forProperty(String propertyName, Class beanClass, int maxDistance) {
public static PropertyMatches forProperty(String propertyName, Class<?> beanClass, int maxDistance) {
return new PropertyMatches(propertyName, beanClass, maxDistance);
}
@ -76,7 +76,7 @@ final class PropertyMatches { @@ -76,7 +76,7 @@ final class PropertyMatches {
/**
* Create a new PropertyMatches instance for the given property.
*/
private PropertyMatches(String propertyName, Class beanClass, int maxDistance) {
private PropertyMatches(String propertyName, Class<?> beanClass, int maxDistance) {
this.propertyName = propertyName;
this.possibleMatches = calculateMatches(BeanUtils.getPropertyDescriptors(beanClass), maxDistance);
}
@ -172,7 +172,8 @@ final class PropertyMatches { @@ -172,7 +172,8 @@ final class PropertyMatches {
char t_j = s2.charAt(j - 1);
if (s_i == t_j) {
cost = 0;
} else {
}
else {
cost = 1;
}
d[i][j] = Math.min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1),

34
spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java

@ -200,13 +200,13 @@ class TypeConverterDelegate { @@ -200,13 +200,13 @@ class TypeConverterDelegate {
else if (convertedValue instanceof Collection) {
// Convert elements to target type, if determined.
convertedValue = convertToTypedCollection(
(Collection) convertedValue, propertyName, requiredType, typeDescriptor);
(Collection<?>) convertedValue, propertyName, requiredType, typeDescriptor);
standardConversion = true;
}
else if (convertedValue instanceof Map) {
// Convert keys and values to respective target type, if determined.
convertedValue = convertToTypedMap(
(Map) convertedValue, propertyName, requiredType, typeDescriptor);
(Map<?, ?>) convertedValue, propertyName, requiredType, typeDescriptor);
standardConversion = true;
}
if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
@ -296,12 +296,12 @@ class TypeConverterDelegate { @@ -296,12 +296,12 @@ class TypeConverterDelegate {
convertedValue = enumField.get(null);
}
catch (ClassNotFoundException ex) {
if(logger.isTraceEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Enum class [" + enumType + "] cannot be loaded", ex);
}
}
catch (Throwable ex) {
if(logger.isTraceEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Field [" + fieldName + "] isn't an enum value for type [" + enumType + "]", ex);
}
}
@ -459,10 +459,10 @@ class TypeConverterDelegate { @@ -459,10 +459,10 @@ class TypeConverterDelegate {
private Object convertToTypedArray(Object input, String propertyName, Class<?> componentType) {
if (input instanceof Collection) {
// Convert Collection elements to array elements.
Collection coll = (Collection) input;
Collection<?> coll = (Collection<?>) input;
Object result = Array.newInstance(componentType, coll.size());
int i = 0;
for (Iterator it = coll.iterator(); it.hasNext(); i++) {
for (Iterator<?> it = coll.iterator(); it.hasNext(); i++) {
Object value = convertIfNecessary(
buildIndexedPropertyName(propertyName, i), null, it.next(), componentType);
Array.set(result, i, value);
@ -495,8 +495,8 @@ class TypeConverterDelegate { @@ -495,8 +495,8 @@ class TypeConverterDelegate {
}
@SuppressWarnings("unchecked")
private Collection convertToTypedCollection(
Collection original, String propertyName, Class<?> requiredType, TypeDescriptor typeDescriptor) {
private Collection<?> convertToTypedCollection(
Collection<?> original, String propertyName, Class<?> requiredType, TypeDescriptor typeDescriptor) {
if (!Collection.class.isAssignableFrom(requiredType)) {
return original;
@ -519,7 +519,7 @@ class TypeConverterDelegate { @@ -519,7 +519,7 @@ class TypeConverterDelegate {
return original;
}
Iterator it;
Iterator<?> it;
try {
it = original.iterator();
if (it == null) {
@ -538,13 +538,13 @@ class TypeConverterDelegate { @@ -538,13 +538,13 @@ class TypeConverterDelegate {
return original;
}
Collection convertedCopy;
Collection<Object> convertedCopy;
try {
if (approximable) {
convertedCopy = CollectionFactory.createApproximateCollection(original, original.size());
}
else {
convertedCopy = (Collection) requiredType.newInstance();
convertedCopy = (Collection<Object>) requiredType.newInstance();
}
}
catch (Throwable ex) {
@ -577,8 +577,8 @@ class TypeConverterDelegate { @@ -577,8 +577,8 @@ class TypeConverterDelegate {
}
@SuppressWarnings("unchecked")
private Map convertToTypedMap(
Map original, String propertyName, Class<?> requiredType, TypeDescriptor typeDescriptor) {
private Map<?, ?> convertToTypedMap(
Map<?, ?> original, String propertyName, Class<?> requiredType, TypeDescriptor typeDescriptor) {
if (!Map.class.isAssignableFrom(requiredType)) {
return original;
@ -602,7 +602,7 @@ class TypeConverterDelegate { @@ -602,7 +602,7 @@ class TypeConverterDelegate {
return original;
}
Iterator it;
Iterator<?> it;
try {
it = original.entrySet().iterator();
if (it == null) {
@ -621,13 +621,13 @@ class TypeConverterDelegate { @@ -621,13 +621,13 @@ class TypeConverterDelegate {
return original;
}
Map convertedCopy;
Map<Object, Object> convertedCopy;
try {
if (approximable) {
convertedCopy = CollectionFactory.createApproximateMap(original, original.size());
}
else {
convertedCopy = (Map) requiredType.newInstance();
convertedCopy = (Map<Object, Object>) requiredType.newInstance();
}
}
catch (Throwable ex) {
@ -639,7 +639,7 @@ class TypeConverterDelegate { @@ -639,7 +639,7 @@ class TypeConverterDelegate {
}
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
String keyedPropertyName = buildKeyedPropertyName(propertyName, key);

2
spring-beans/src/main/java/org/springframework/beans/factory/xml/AbstractSimpleBeanDefinitionParser.java

@ -149,7 +149,7 @@ public abstract class AbstractSimpleBeanDefinitionParser extends AbstractSingleB @@ -149,7 +149,7 @@ public abstract class AbstractSimpleBeanDefinitionParser extends AbstractSingleB
*/
protected boolean isEligibleAttribute(Attr attribute, ParserContext parserContext) {
boolean eligible = isEligibleAttribute(attribute);
if(!eligible) {
if (!eligible) {
String fullName = attribute.getName();
eligible = (!fullName.equals("xmlns") && !fullName.startsWith("xmlns:") &&
isEligibleAttribute(parserContext.getDelegate().getLocalName(attribute)));

31
spring-beans/src/main/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandler.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -13,20 +13,22 @@ @@ -13,20 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.xml;
import java.util.Collection;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.core.Conventions;
import org.springframework.util.StringUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Simple {@code NamespaceHandler} implementation that maps custom
@ -34,8 +36,7 @@ import org.w3c.dom.Node; @@ -34,8 +36,7 @@ import org.w3c.dom.Node;
* that this {@code NamespaceHandler} does not have a corresponding schema
* since there is no way to know in advance all possible attribute names.
*
* <p>
* An example of the usage of this {@code NamespaceHandler} is shown below:
* <p>An example of the usage of this {@code NamespaceHandler} is shown below:
*
* <pre class="code">
* &lt;bean id=&quot;author&quot; class=&quot;..TestBean&quot; c:name=&quot;Enescu&quot; c:work-ref=&quot;compositions&quot;/&gt;
@ -51,14 +52,17 @@ import org.w3c.dom.Node; @@ -51,14 +52,17 @@ import org.w3c.dom.Node;
* support for indexes or types. Further more, the names are used as hints by
* the container which, by default, does type introspection.
*
* @see SimplePropertyNamespaceHandler
* @author Costin Leau
* @since 3.1
* @see SimplePropertyNamespaceHandler
*/
public class SimpleConstructorNamespaceHandler implements NamespaceHandler {
private static final String REF_SUFFIX = "-ref";
private static final String DELIMITER_PREFIX = "_";
public void init() {
}
@ -99,7 +103,8 @@ public class SimpleConstructorNamespaceHandler implements NamespaceHandler { @@ -99,7 +103,8 @@ public class SimpleConstructorNamespaceHandler implements NamespaceHandler {
int index = -1;
try {
index = Integer.parseInt(arg);
} catch (NumberFormatException ex) {
}
catch (NumberFormatException ex) {
parserContext.getReaderContext().error(
"Constructor argument '" + argName + "' specifies an invalid integer", attr);
}
@ -133,11 +138,8 @@ public class SimpleConstructorNamespaceHandler implements NamespaceHandler { @@ -133,11 +138,8 @@ public class SimpleConstructorNamespaceHandler implements NamespaceHandler {
}
private boolean containsArgWithName(String name, ConstructorArgumentValues cvs) {
if (!checkName(name, cvs.getGenericArgumentValues())) {
return checkName(name, cvs.getIndexedArgumentValues().values());
}
return true;
return (checkName(name, cvs.getGenericArgumentValues()) ||
checkName(name, cvs.getIndexedArgumentValues().values()));
}
private boolean checkName(String name, Collection<ValueHolder> values) {
@ -148,4 +150,5 @@ public class SimpleConstructorNamespaceHandler implements NamespaceHandler { @@ -148,4 +150,5 @@ public class SimpleConstructorNamespaceHandler implements NamespaceHandler {
}
return false;
}
}

11
spring-beans/src/main/java/org/springframework/beans/propertyeditors/ResourceBundleEditor.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -16,13 +16,13 @@ @@ -16,13 +16,13 @@
package org.springframework.beans.propertyeditors;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;
import java.util.Locale;
import java.util.ResourceBundle;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* {@link java.beans.PropertyEditor} implementation for
* {@link java.util.ResourceBundle ResourceBundles}.
@ -87,7 +87,8 @@ public class ResourceBundleEditor extends PropertyEditorSupport { @@ -87,7 +87,8 @@ public class ResourceBundleEditor extends PropertyEditorSupport {
int indexOfBaseNameSeparator = rawBaseName.indexOf(BASE_NAME_SEPARATOR);
if (indexOfBaseNameSeparator == -1) {
bundle = ResourceBundle.getBundle(rawBaseName);
} else {
}
else {
// it potentially has locale information
String baseName = rawBaseName.substring(0, indexOfBaseNameSeparator);
if (!StringUtils.hasText(baseName)) {

6
spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java

@ -310,7 +310,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe @@ -310,7 +310,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe
* reference into the JobDataMap but rather into the SchedulerContext.
* @param schedulerContextAsMap Map with String keys and any objects as
* values (for example Spring-managed beans)
* @see JobDetailBean#setJobDataAsMap
* @see JobDetailFactoryBean#setJobDataAsMap
*/
public void setSchedulerContextAsMap(Map<String, ?> schedulerContextAsMap) {
this.schedulerContextMap = schedulerContextAsMap;
@ -328,8 +328,8 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe @@ -328,8 +328,8 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe
* correspond to a "setApplicationContext" method in that scenario.
* <p>Note that BeanFactory callback interfaces like ApplicationContextAware
* are not automatically applied to Quartz Job instances, because Quartz
* itself is reponsible for the lifecycle of its Jobs.
* @see JobDetailBean#setApplicationContextJobDataKey
* itself is responsible for the lifecycle of its Jobs.
* @see JobDetailFactoryBean#setApplicationContextJobDataKey
* @see org.springframework.context.ApplicationContext
*/
public void setApplicationContextSchedulerContextKey(String applicationContextSchedulerContextKey) {

18
spring-context/src/main/java/org/springframework/format/AnnotationFormatterFactory.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -13,13 +13,15 @@ @@ -13,13 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.format;
import java.lang.annotation.Annotation;
import java.util.Set;
/**
* A factory that creates formatters to format values of fields annotated with a particular {@link Annotation}.
* A factory that creates formatters to format values of fields annotated with a particular
* {@link Annotation}.
*
* <p>For example, a {@code DateTimeFormatAnnotationFormatterFactory} might create a formatter
* that formats {@code Date} values set on fields annotated with {@code @DateTimeFormat}.
@ -36,8 +38,10 @@ public interface AnnotationFormatterFactory<A extends Annotation> { @@ -36,8 +38,10 @@ public interface AnnotationFormatterFactory<A extends Annotation> {
Set<Class<?>> getFieldTypes();
/**
* Get the Printer to print the value of a field of {@code fieldType} annotated with {@code annotation}.
* If the type &lt;T&gt; the printer accepts is not assignable to {@code fieldType}, a coersion from {@code fieldType} to &lt;T&gt; will be attempted before the Printer is invoked.
* Get the Printer to print the value of a field of {@code fieldType} annotated with
* {@code annotation}.
* <p>If the type T the printer accepts is not assignable to {@code fieldType}, a
* coercion from {@code fieldType} to T will be attempted before the Printer is invoked.
* @param annotation the annotation instance
* @param fieldType the type of field that was annotated
* @return the printer
@ -45,8 +49,10 @@ public interface AnnotationFormatterFactory<A extends Annotation> { @@ -45,8 +49,10 @@ public interface AnnotationFormatterFactory<A extends Annotation> {
Printer<?> getPrinter(A annotation, Class<?> fieldType);
/**
* Get the Parser to parse a submitted value for a field of {@code fieldType} annotated with {@code annotation}.
* If the object the parser returns is not assignable to {@code fieldType}, a coersion to {@code fieldType} will be attempted before the field is set.
* Get the Parser to parse a submitted value for a field of {@code fieldType}
* annotated with {@code annotation}.
* <p>If the object the parser returns is not assignable to {@code fieldType},
* a coercion to {@code fieldType} will be attempted before the field is set.
* @param annotation the annotation instance
* @param fieldType the type of field that was annotated
* @return the parser

83
spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -85,7 +85,7 @@ public class FormattingConversionService extends GenericConversionService @@ -85,7 +85,7 @@ public class FormattingConversionService extends GenericConversionService
@SuppressWarnings({ "unchecked", "rawtypes" })
public void addFormatterForFieldAnnotation(AnnotationFormatterFactory annotationFormatterFactory) {
final Class<? extends Annotation> annotationType = (Class<? extends Annotation>)
Class<? extends Annotation> annotationType = (Class<? extends Annotation>)
GenericTypeResolver.resolveTypeArgument(annotationFormatterFactory.getClass(), AnnotationFormatterFactory.class);
if (annotationType == null) {
throw new IllegalArgumentException("Unable to extract parameterized Annotation type argument from AnnotationFormatterFactory [" +
@ -95,7 +95,7 @@ public class FormattingConversionService extends GenericConversionService @@ -95,7 +95,7 @@ public class FormattingConversionService extends GenericConversionService
((EmbeddedValueResolverAware) annotationFormatterFactory).setEmbeddedValueResolver(this.embeddedValueResolver);
}
Set<Class<?>> fieldTypes = annotationFormatterFactory.getFieldTypes();
for (final Class<?> fieldType : fieldTypes) {
for (Class<?> fieldType : fieldTypes) {
addConverter(new AnnotationPrinterConverter(annotationType, annotationFormatterFactory, fieldType));
addConverter(new AnnotationParserConverter(annotationType, annotationFormatterFactory, fieldType));
}
@ -104,14 +104,14 @@ public class FormattingConversionService extends GenericConversionService @@ -104,14 +104,14 @@ public class FormattingConversionService extends GenericConversionService
private static class PrinterConverter implements GenericConverter {
private Class<?> fieldType;
private final Class<?> fieldType;
private TypeDescriptor printerObjectType;
private final TypeDescriptor printerObjectType;
@SuppressWarnings("rawtypes")
private Printer printer;
private final Printer printer;
private ConversionService conversionService;
private final ConversionService conversionService;
public PrinterConverter(Class<?> fieldType, Printer<?> printer, ConversionService conversionService) {
this.fieldType = fieldType;
@ -139,6 +139,7 @@ public class FormattingConversionService extends GenericConversionService @@ -139,6 +139,7 @@ public class FormattingConversionService extends GenericConversionService
return GenericTypeResolver.resolveTypeArgument(printer.getClass(), Printer.class);
}
@Override
public String toString() {
return this.fieldType.getName() + " -> " + String.class.getName() + " : " + this.printer;
}
@ -147,11 +148,11 @@ public class FormattingConversionService extends GenericConversionService @@ -147,11 +148,11 @@ public class FormattingConversionService extends GenericConversionService
private static class ParserConverter implements GenericConverter {
private Class<?> fieldType;
private final Class<?> fieldType;
private Parser<?> parser;
private final Parser<?> parser;
private ConversionService conversionService;
private final ConversionService conversionService;
public ParserConverter(Class<?> fieldType, Parser<?> parser, ConversionService conversionService) {
this.fieldType = fieldType;
@ -185,6 +186,7 @@ public class FormattingConversionService extends GenericConversionService @@ -185,6 +186,7 @@ public class FormattingConversionService extends GenericConversionService
return result;
}
@Override
public String toString() {
return String.class.getName() + " -> " + this.fieldType.getName() + ": " + this.parser;
}
@ -193,55 +195,56 @@ public class FormattingConversionService extends GenericConversionService @@ -193,55 +195,56 @@ public class FormattingConversionService extends GenericConversionService
private class AnnotationPrinterConverter implements ConditionalGenericConverter {
private Class<? extends Annotation> annotationType;
private final Class<? extends Annotation> annotationType;
private AnnotationFormatterFactory annotationFormatterFactory;
private final AnnotationFormatterFactory annotationFormatterFactory;
private Class<?> fieldType;
private final Class<?> fieldType;
public AnnotationPrinterConverter(Class<? extends Annotation> annotationType,
AnnotationFormatterFactory annotationFormatterFactory, Class<?> fieldType) {
AnnotationFormatterFactory<?> annotationFormatterFactory, Class<?> fieldType) {
this.annotationType = annotationType;
this.annotationFormatterFactory = annotationFormatterFactory;
this.fieldType = fieldType;
}
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(fieldType, String.class));
return Collections.singleton(new ConvertiblePair(this.fieldType, String.class));
}
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return sourceType.hasAnnotation(annotationType);
return sourceType.hasAnnotation(this.annotationType);
}
@SuppressWarnings("unchecked")
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
AnnotationConverterKey converterKey =
new AnnotationConverterKey(sourceType.getAnnotation(annotationType), sourceType.getObjectType());
new AnnotationConverterKey(sourceType.getAnnotation(this.annotationType), sourceType.getObjectType());
GenericConverter converter = cachedPrinters.get(converterKey);
if (converter == null) {
Printer<?> printer = annotationFormatterFactory.getPrinter(
Printer<?> printer = this.annotationFormatterFactory.getPrinter(
converterKey.getAnnotation(), converterKey.getFieldType());
converter = new PrinterConverter(fieldType, printer, FormattingConversionService.this);
converter = new PrinterConverter(this.fieldType, printer, FormattingConversionService.this);
cachedPrinters.put(converterKey, converter);
}
return converter.convert(source, sourceType, targetType);
}
@Override
public String toString() {
return "@" + annotationType.getName() + " " + fieldType.getName() + " -> " +
String.class.getName() + ": " + annotationFormatterFactory;
return "@" + this.annotationType.getName() + " " + this.fieldType.getName() + " -> " +
String.class.getName() + ": " + this.annotationFormatterFactory;
}
}
private class AnnotationParserConverter implements ConditionalGenericConverter {
private Class<? extends Annotation> annotationType;
private final Class<? extends Annotation> annotationType;
private AnnotationFormatterFactory annotationFormatterFactory;
private final AnnotationFormatterFactory annotationFormatterFactory;
private Class<?> fieldType;
private final Class<?> fieldType;
public AnnotationParserConverter(Class<? extends Annotation> annotationType,
AnnotationFormatterFactory<?> annotationFormatterFactory, Class<?> fieldType) {
@ -255,26 +258,27 @@ public class FormattingConversionService extends GenericConversionService @@ -255,26 +258,27 @@ public class FormattingConversionService extends GenericConversionService
}
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return targetType.hasAnnotation(annotationType);
return targetType.hasAnnotation(this.annotationType);
}
@SuppressWarnings("unchecked")
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
AnnotationConverterKey converterKey =
new AnnotationConverterKey(targetType.getAnnotation(annotationType), targetType.getObjectType());
new AnnotationConverterKey(targetType.getAnnotation(this.annotationType), targetType.getObjectType());
GenericConverter converter = cachedParsers.get(converterKey);
if (converter == null) {
Parser<?> parser = annotationFormatterFactory.getParser(
Parser<?> parser = this.annotationFormatterFactory.getParser(
converterKey.getAnnotation(), converterKey.getFieldType());
converter = new ParserConverter(fieldType, parser, FormattingConversionService.this);
converter = new ParserConverter(this.fieldType, parser, FormattingConversionService.this);
cachedParsers.put(converterKey, converter);
}
return converter.convert(source, sourceType, targetType);
}
@Override
public String toString() {
return String.class.getName() + " -> @" + annotationType.getName() + " " +
fieldType.getName() + ": " + annotationFormatterFactory;
return String.class.getName() + " -> @" + this.annotationType.getName() + " " +
this.fieldType.getName() + ": " + this.annotationFormatterFactory;
}
}
@ -291,23 +295,28 @@ public class FormattingConversionService extends GenericConversionService @@ -291,23 +295,28 @@ public class FormattingConversionService extends GenericConversionService
}
public Annotation getAnnotation() {
return annotation;
return this.annotation;
}
public Class<?> getFieldType() {
return fieldType;
return this.fieldType;
}
public boolean equals(Object o) {
if (!(o instanceof AnnotationConverterKey)) {
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof AnnotationConverterKey)) {
return false;
}
AnnotationConverterKey key = (AnnotationConverterKey) o;
return this.annotation.equals(key.annotation) && this.fieldType.equals(key.fieldType);
AnnotationConverterKey otherKey = (AnnotationConverterKey) other;
return (this.annotation.equals(otherKey.annotation) && this.fieldType.equals(otherKey.fieldType));
}
@Override
public int hashCode() {
return this.annotation.hashCode() + 29 * this.fieldType.hashCode();
return (this.annotation.hashCode() + 29 * this.fieldType.hashCode());
}
}

38
spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassPreProcessorAdapter.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -39,10 +39,11 @@ class WebLogicClassPreProcessorAdapter implements InvocationHandler { @@ -39,10 +39,11 @@ class WebLogicClassPreProcessorAdapter implements InvocationHandler {
private final ClassLoader loader;
/**
* Creates a new {@link WebLogicClassPreProcessorAdapter}.
* @param transformer the {@link ClassFileTransformer} to be adapted (must
* not be {@code null})
* @param transformer the {@link ClassFileTransformer} to be adapted
* (must not be {@code null})
*/
public WebLogicClassPreProcessorAdapter(ClassFileTransformer transformer, ClassLoader loader) {
this.transformer = transformer;
@ -51,40 +52,43 @@ class WebLogicClassPreProcessorAdapter implements InvocationHandler { @@ -51,40 +52,43 @@ class WebLogicClassPreProcessorAdapter implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
if ("equals".equals(name)) {
return (Boolean.valueOf(proxy == args[0]));
} else if ("hashCode".equals(name)) {
return (proxy == args[0]);
}
else if ("hashCode".equals(name)) {
return hashCode();
} else if ("toString".equals(name)) {
}
else if ("toString".equals(name)) {
return toString();
} else if ("initialize".equals(name)) {
initialize((Hashtable) args[0]);
}
else if ("initialize".equals(name)) {
initialize((Hashtable<?, ?>) args[0]);
return null;
} else if ("preProcess".equals(name)) {
}
else if ("preProcess".equals(name)) {
return preProcess((String) args[0], (byte[]) args[1]);
} else {
}
else {
throw new IllegalArgumentException("Unknown method: " + method);
}
}
public void initialize(Hashtable params) {
public void initialize(Hashtable<?, ?> params) {
}
public byte[] preProcess(String className, byte[] classBytes) {
try {
byte[] result = this.transformer.transform(this.loader, className, null, null, classBytes);
return (result != null ? result : classBytes);
} catch (IllegalClassFormatException ex) {
}
catch (IllegalClassFormatException ex) {
throw new IllegalStateException("Cannot transform due to illegal class format", ex);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(getClass().getName());
builder.append(" for transformer: ");
builder.append(this.transformer);
return builder.toString();
return getClass().getName() + " for transformer: " + this.transformer;
}
}

2
spring-context/src/main/java/org/springframework/jmx/export/annotation/AnnotationJmxAttributeSource.java

@ -141,7 +141,7 @@ public class AnnotationJmxAttributeSource implements JmxAttributeSource, BeanFac @@ -141,7 +141,7 @@ public class AnnotationJmxAttributeSource implements JmxAttributeSource, BeanFac
public ManagedNotification[] getManagedNotifications(Class<?> clazz) throws InvalidMetadataException {
ManagedNotifications notificationsAnn = clazz.getAnnotation(ManagedNotifications.class);
if(notificationsAnn == null) {
if (notificationsAnn == null) {
return new ManagedNotification[0];
}
Annotation[] notifications = notificationsAnn.value();

4
spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java

@ -434,7 +434,7 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean @@ -434,7 +434,7 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean
* @see #getClassToExpose(Class)
* @see org.springframework.aop.framework.AopProxyUtils#proxiedUserInterfaces(Object)
*/
protected Class getClassForDescriptor(Object managedBean) {
protected Class<?> getClassForDescriptor(Object managedBean) {
if (AopUtils.isJdkDynamicProxy(managedBean)) {
return AopProxyUtils.proxiedUserInterfaces(managedBean)[0];
}
@ -514,7 +514,7 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean @@ -514,7 +514,7 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean
MBeanParameterInfo[] info = new MBeanParameterInfo[paramNames.length];
Class<?>[] typeParameters = method.getParameterTypes();
for(int i = 0; i < info.length; i++) {
for (int i = 0; i < info.length; i++) {
info[i] = new MBeanParameterInfo(paramNames[i], typeParameters[i].getName(), paramNames[i]);
}

10
spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java

@ -151,7 +151,7 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem @@ -151,7 +151,7 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem
protected boolean includeOperation(Method method, String beanKey) {
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);
if (pd != null) {
if(hasManagedAttribute(method)) {
if (hasManagedAttribute(method)) {
return true;
}
}
@ -261,7 +261,7 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem @@ -261,7 +261,7 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem
}
MBeanParameterInfo[] parameterInfo = new MBeanParameterInfo[params.length];
Class[] methodParameters = method.getParameterTypes();
Class<?>[] methodParameters = method.getParameterTypes();
for (int i = 0; i < params.length; i++) {
ManagedOperationParameter param = params[i];
parameterInfo[i] =
@ -332,7 +332,7 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem @@ -332,7 +332,7 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem
*/
@Override
protected void populateAttributeDescriptor(Descriptor desc, Method getter, Method setter, String beanKey) {
if(getter != null && hasManagedMetric(getter)) {
if (getter != null && hasManagedMetric(getter)) {
populateMetricDescriptor(desc, this.attributeSource.getManagedMetric(getter));
}
else {
@ -374,11 +374,11 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem @@ -374,11 +374,11 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem
desc.setField(FIELD_DISPLAY_NAME, metric.getDisplayName());
}
if(StringUtils.hasLength(metric.getUnit())) {
if (StringUtils.hasLength(metric.getUnit())) {
desc.setField(FIELD_UNITS, metric.getUnit());
}
if(StringUtils.hasLength(metric.getCategory())) {
if (StringUtils.hasLength(metric.getCategory())) {
desc.setField(FIELD_METRIC_CATEGORY, metric.getCategory());
}

2
spring-context/src/main/java/org/springframework/validation/DefaultMessageCodesResolver.java

@ -243,7 +243,7 @@ public class DefaultMessageCodesResolver implements MessageCodesResolver, Serial @@ -243,7 +243,7 @@ public class DefaultMessageCodesResolver implements MessageCodesResolver, Serial
public static String toDelimitedString(String... elements) {
StringBuilder rtn = new StringBuilder();
for (String element : elements) {
if(StringUtils.hasLength(element)) {
if (StringUtils.hasLength(element)) {
rtn.append(rtn.length() == 0 ? "" : CODE_SEPARATOR);
rtn.append(element);
}

30
spring-core/src/main/java/org/springframework/asm/package-info.java

@ -1,28 +1,16 @@ @@ -1,28 +1,16 @@
/*
* 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.
*/
/**
* Spring's repackaging of <a href="http://asm.ow2.org">org.objectweb.asm 4</a> (for
* internal use only).
* Spring's repackaging of
* <a href="http://asm.ow2.org">org.objectweb.asm 5.0</a>
* (for internal use only).
*
* <p>This repackaging technique avoids any potential conflicts with
* dependencies on ASM at the application level or from other third-party
* dependencies on ASM at the application level or from third-party
* libraries and frameworks.
* <p>As this repackaging happens at the classfile level, sources and Javadoc
* are not available here. See the original ObjectWeb
* <a href="http://asm.ow2.org/asm40/javadoc/user">ASM 4 Javadoc</a>
*
* <p>As this repackaging happens at the class file level, sources
* and javadocs are not available here. See the original ObjectWeb
* <a href="http://asm.ow2.org/asm50/javadoc/user">ASM 5.0 javadocs</a>
* for details when working with these classes.
*
* @since 3.2

44
spring-core/src/main/java/org/springframework/core/convert/Property.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -62,6 +62,7 @@ public final class Property { @@ -62,6 +62,7 @@ public final class Property {
private Annotation[] annotations;
public Property(Class<?> objectType, Method readMethod, Method writeMethod) {
this(objectType, readMethod, writeMethod, null);
}
@ -118,7 +119,7 @@ public final class Property { @@ -118,7 +119,7 @@ public final class Property {
}
Annotation[] getAnnotations() {
if(this.annotations == null) {
if (this.annotations == null) {
this.annotations = resolveAnnotations();
}
return this.annotations;
@ -192,7 +193,7 @@ public final class Property { @@ -192,7 +193,7 @@ public final class Property {
private Annotation[] resolveAnnotations() {
Annotation[] annotations = annotationCache.get(this);
if(annotations == null) {
if (annotations == null) {
Map<Class<? extends Annotation>, Annotation> annotationMap = new LinkedHashMap<Class<? extends Annotation>, Annotation>();
addAnnotationsToMap(annotationMap, getReadMethod());
addAnnotationsToMap(annotationMap, getWriteMethod());
@ -241,34 +242,25 @@ public final class Property { @@ -241,34 +242,25 @@ public final class Property {
}
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ObjectUtils.nullSafeHashCode(objectType);
hashCode = prime * hashCode + ObjectUtils.nullSafeHashCode(readMethod);
hashCode = prime * hashCode + ObjectUtils.nullSafeHashCode(writeMethod);
hashCode = prime * hashCode + ObjectUtils.nullSafeHashCode(name);
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
if (!(other instanceof Property)) {
return false;
}
Property other = (Property) obj;
boolean equals = true;
equals &= ObjectUtils.nullSafeEquals(objectType, other.objectType);
equals &= ObjectUtils.nullSafeEquals(readMethod, other.readMethod);
equals &= ObjectUtils.nullSafeEquals(writeMethod, other.writeMethod);
equals &= ObjectUtils.nullSafeEquals(name, other.name);
return equals;
Property otherProperty = (Property) other;
return (ObjectUtils.nullSafeEquals(this.objectType, otherProperty.objectType) &&
ObjectUtils.nullSafeEquals(this.name, otherProperty.name) &&
ObjectUtils.nullSafeEquals(this.readMethod, otherProperty.readMethod) &&
ObjectUtils.nullSafeEquals(this.writeMethod, otherProperty.writeMethod));
}
@Override
public int hashCode() {
return (ObjectUtils.nullSafeHashCode(this.objectType) * 31 + ObjectUtils.nullSafeHashCode(this.name));
}
}

14
spring-core/src/main/java/org/springframework/core/convert/support/ArrayToArrayConverter.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -40,11 +40,13 @@ final class ArrayToArrayConverter implements ConditionalGenericConverter { @@ -40,11 +40,13 @@ final class ArrayToArrayConverter implements ConditionalGenericConverter {
private final ConversionService conversionService;
public ArrayToArrayConverter(ConversionService conversionService) {
this.helperConverter = new CollectionToArrayConverter(conversionService);
this.conversionService = conversionService;
}
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object[].class, Object[].class));
}
@ -53,12 +55,10 @@ final class ArrayToArrayConverter implements ConditionalGenericConverter { @@ -53,12 +55,10 @@ final class ArrayToArrayConverter implements ConditionalGenericConverter {
return this.helperConverter.matches(sourceType, targetType);
}
public Object convert(Object source, TypeDescriptor sourceType,
TypeDescriptor targetType) {
if ((conversionService instanceof GenericConversionService)
&& ((GenericConversionService) conversionService).canBypassConvert(
sourceType.getElementTypeDescriptor(),
targetType.getElementTypeDescriptor())) {
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (this.conversionService instanceof GenericConversionService &&
((GenericConversionService) this.conversionService).canBypassConvert(
sourceType.getElementTypeDescriptor(), targetType.getElementTypeDescriptor())) {
return source;
}
List<Object> sourceList = Arrays.asList(ObjectUtils.toObjectArray(source));

7
spring-core/src/main/java/org/springframework/core/convert/support/ArrayToStringConverter.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2009 the original author or authors.
* 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.
@ -27,7 +27,8 @@ import org.springframework.util.ObjectUtils; @@ -27,7 +27,8 @@ import org.springframework.util.ObjectUtils;
/**
* Converts an Array to a comma-delimited String.
* This implementation first adapts the source Array to a List, then delegates to {@link CollectionToStringConverter} to perform the target String conversion.
* This implementation first adapts the source Array to a List,
* then delegates to {@link CollectionToStringConverter} to perform the target String conversion.
*
* @author Keith Donald
* @since 3.0
@ -36,10 +37,12 @@ final class ArrayToStringConverter implements ConditionalGenericConverter { @@ -36,10 +37,12 @@ final class ArrayToStringConverter implements ConditionalGenericConverter {
private final CollectionToStringConverter helperConverter;
public ArrayToStringConverter(ConversionService conversionService) {
this.helperConverter = new CollectionToStringConverter(conversionService);
}
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object[].class, String.class));
}

15
spring-core/src/main/java/org/springframework/core/convert/support/MapToMapConverter.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -42,10 +42,12 @@ final class MapToMapConverter implements ConditionalGenericConverter { @@ -42,10 +42,12 @@ final class MapToMapConverter implements ConditionalGenericConverter {
private final ConversionService conversionService;
public MapToMapConverter(ConversionService conversionService) {
this.conversionService = conversionService;
}
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Map.class, Map.class));
}
@ -75,7 +77,7 @@ final class MapToMapConverter implements ConditionalGenericConverter { @@ -75,7 +77,7 @@ final class MapToMapConverter implements ConditionalGenericConverter {
copyRequired = true;
}
}
if(!copyRequired) {
if (!copyRequired) {
return sourceMap;
}
Map<Object, Object> targetMap = CollectionFactory.createMap(targetType.getType(), sourceMap.size());
@ -85,6 +87,7 @@ final class MapToMapConverter implements ConditionalGenericConverter { @@ -85,6 +87,7 @@ final class MapToMapConverter implements ConditionalGenericConverter {
return targetMap;
}
// internal helpers
private boolean canConvertKey(TypeDescriptor sourceType, TypeDescriptor targetType) {
@ -111,10 +114,12 @@ final class MapToMapConverter implements ConditionalGenericConverter { @@ -111,10 +114,12 @@ final class MapToMapConverter implements ConditionalGenericConverter {
return this.conversionService.convert(sourceValue, sourceType.getMapValueTypeDescriptor(sourceValue), targetType);
}
private static class MapEntry {
private Object key;
private Object value;
private final Object key;
private final Object value;
public MapEntry(Object key, Object value) {
this.key = key;
@ -122,7 +127,7 @@ final class MapToMapConverter implements ConditionalGenericConverter { @@ -122,7 +127,7 @@ final class MapToMapConverter implements ConditionalGenericConverter {
}
public void addToMap(Map<Object, Object> map) {
map.put(key, value);
map.put(this.key, this.value);
}
}

17
spring-core/src/main/java/org/springframework/core/convert/support/StringToCollectionConverter.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@ -28,7 +28,8 @@ import org.springframework.util.StringUtils; @@ -28,7 +28,8 @@ import org.springframework.util.StringUtils;
/**
* Converts a comma-delimited String to a Collection.
* If the target collection element type is declared, only matches if String.class can be converted to it.
* If the target collection element type is declared, only matches if
* {@code String.class} can be converted to it.
*
* @author Keith Donald
* @since 3.0
@ -37,20 +38,19 @@ final class StringToCollectionConverter implements ConditionalGenericConverter { @@ -37,20 +38,19 @@ final class StringToCollectionConverter implements ConditionalGenericConverter {
private final ConversionService conversionService;
public StringToCollectionConverter(ConversionService conversionService) {
this.conversionService = conversionService;
}
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(String.class, Collection.class));
}
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
if (targetType.getElementTypeDescriptor() != null) {
return this.conversionService.canConvert(sourceType, targetType.getElementTypeDescriptor());
} else {
return true;
}
return (targetType.getElementTypeDescriptor() == null ||
this.conversionService.canConvert(sourceType, targetType.getElementTypeDescriptor()));
}
@SuppressWarnings("unchecked")
@ -65,7 +65,8 @@ final class StringToCollectionConverter implements ConditionalGenericConverter { @@ -65,7 +65,8 @@ final class StringToCollectionConverter implements ConditionalGenericConverter {
for (String field : fields) {
target.add(field.trim());
}
} else {
}
else {
for (String field : fields) {
Object targetElement = this.conversionService.convert(field.trim(), sourceType, targetType.getElementTypeDescriptor());
target.add(targetElement);

11
spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@ -18,7 +18,6 @@ package org.springframework.core.convert.support; @@ -18,7 +18,6 @@ package org.springframework.core.convert.support;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.util.Assert;
/**
* Converts from a String to a java.lang.Enum by calling {@link Enum#valueOf(Class, String)}.
@ -31,14 +30,16 @@ final class StringToEnumConverterFactory implements ConverterFactory<String, Enu @@ -31,14 +30,16 @@ final class StringToEnumConverterFactory implements ConverterFactory<String, Enu
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
Class<?> enumType = targetType;
while(enumType != null && !enumType.isEnum()) {
while (enumType != null && !enumType.isEnum()) {
enumType = enumType.getSuperclass();
}
Assert.notNull(enumType, "The target type " + targetType.getName()
+ " does not refer to an enum");
if (enumType == null) {
throw new IllegalArgumentException("The target type " + targetType.getName() + " does not refer to an enum");
}
return new StringToEnum(enumType);
}
private class StringToEnum<T extends Enum> implements Converter<String, T> {
private final Class<T> enumType;

2
spring-core/src/main/java/org/springframework/core/convert/support/StringToUUIDConverter.java

@ -30,7 +30,7 @@ import org.springframework.util.StringUtils; @@ -30,7 +30,7 @@ import org.springframework.util.StringUtils;
final class StringToUUIDConverter implements Converter<String, UUID> {
public UUID convert(String source) {
if(StringUtils.hasLength(source)) {
if (StringUtils.hasLength(source)) {
return UUID.fromString(source.trim());
}
return null;

4
spring-core/src/main/java/org/springframework/core/io/AbstractResource.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -122,7 +122,7 @@ public abstract class AbstractResource implements Resource { @@ -122,7 +122,7 @@ public abstract class AbstractResource implements Resource {
long size = 0;
byte[] buf = new byte[255];
int read;
while((read = is.read(buf)) != -1) {
while ((read = is.read(buf)) != -1) {
size += read;
}
return size;

2
spring-core/src/main/java/org/springframework/util/ObjectUtils.java

@ -155,7 +155,7 @@ public abstract class ObjectUtils { @@ -155,7 +155,7 @@ public abstract class ObjectUtils {
*/
public static <E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues, String constant) {
for (E candidate : enumValues) {
if(candidate.toString().equalsIgnoreCase(constant)) {
if (candidate.toString().equalsIgnoreCase(constant)) {
return candidate;
}
}

8
spring-core/src/main/java/org/springframework/util/StopWatch.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -229,7 +229,8 @@ public class StopWatch { @@ -229,7 +229,8 @@ public class StopWatch {
sb.append('\n');
if (!this.keepTaskList) {
sb.append("No task info kept");
} else {
}
else {
sb.append("-----------------------------------------\n");
sb.append("ms % Task name\n");
sb.append("-----------------------------------------\n");
@ -261,7 +262,8 @@ public class StopWatch { @@ -261,7 +262,8 @@ public class StopWatch {
long percent = Math.round((100.0 * task.getTimeSeconds()) / getTotalTimeSeconds());
sb.append(" = ").append(percent).append("%");
}
} else {
}
else {
sb.append("; no task info kept");
}
return sb.toString();

21
spring-core/src/main/java/org/springframework/util/comparator/InstanceComparator.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -31,23 +31,22 @@ import org.springframework.util.Assert; @@ -31,23 +31,22 @@ import org.springframework.util.Assert;
* is required.
*
* @author Phillip Webb
* @param <T> The type of objects being compared
* @see CompoundComparator
* @since 3.2
* @param <T> the type of objects being compared
* @see CompoundComparator
*/
public class InstanceComparator<T> implements Comparator<T> {
private Class<?>[] instanceOrder;
private final Class<?>[] instanceOrder;
/**
* Create a new {@link InstanceComparator} instance.
*
* @param instanceOrder the ordered list of classes that should be used when comparing
* objects. Classes earlier in the list will be be given a higher priority.
*/
public InstanceComparator(Class<?>... instanceOrder) {
Assert.notNull(instanceOrder, "InstanceOrder must not be null");
Assert.notNull(instanceOrder, "'instanceOrder' must not be null");
this.instanceOrder = instanceOrder;
}
@ -59,14 +58,14 @@ public class InstanceComparator<T> implements Comparator<T> { @@ -59,14 +58,14 @@ public class InstanceComparator<T> implements Comparator<T> {
}
private int getOrder(T object) {
if(object != null) {
for (int i = 0; i < instanceOrder.length; i++) {
if (instanceOrder[i].isInstance(object)) {
if (object != null) {
for (int i = 0; i < this.instanceOrder.length; i++) {
if (this.instanceOrder[i].isInstance(object)) {
return i;
}
}
}
return instanceOrder.length;
return this.instanceOrder.length;
}
}
}

1
spring-core/src/main/java/org/springframework/util/comparator/package-info.java

@ -1,3 +1,4 @@ @@ -1,3 +1,4 @@
/**
*
* Useful generic {@code java.util.Comparator} implementations,

437
spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java

@ -44,6 +44,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -44,6 +44,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
private static final Pattern VALID_QUALIFIED_ID_PATTERN = Pattern.compile("[\\p{L}\\p{N}_$]+");
// The expression being parsed
private String expressionString;
@ -57,9 +58,9 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -57,9 +58,9 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
private int tokenStreamPointer;
// For rules that build nodes, they are stacked here for return
private Stack<SpelNodeImpl> constructedNodes = new Stack<SpelNodeImpl>();
private final Stack<SpelNodeImpl> constructedNodes = new Stack<SpelNodeImpl>();
private SpelParserConfiguration configuration;
private final SpelParserConfiguration configuration;
/**
@ -77,16 +78,16 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -77,16 +78,16 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
this.expressionString = expressionString;
Tokenizer tokenizer = new Tokenizer(expressionString);
tokenizer.process();
tokenStream = tokenizer.getTokens();
tokenStreamLength = tokenStream.size();
tokenStreamPointer = 0;
constructedNodes.clear();
this.tokenStream = tokenizer.getTokens();
this.tokenStreamLength = this.tokenStream.size();
this.tokenStreamPointer = 0;
this.constructedNodes.clear();
SpelNodeImpl ast = eatExpression();
if (moreTokens()) {
throw new SpelParseException(peekToken().startpos,SpelMessage.MORE_INPUT,toString(nextToken()));
}
Assert.isTrue(constructedNodes.isEmpty());
return new SpelExpression(expressionString, ast, configuration);
Assert.isTrue(this.constructedNodes.isEmpty());
return new SpelExpression(expressionString, ast, this.configuration);
}
catch (InternalParseException ipe) {
throw ipe.getCause();
@ -110,7 +111,9 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -110,7 +111,9 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
nextToken();
SpelNodeImpl assignedValue = eatLogicalOrExpression();
return new Assign(toPos(t),expr,assignedValue);
} else if (t.kind==TokenKind.ELVIS) { // a?:b (a if it isn't null, otherwise b)
}
if (t.kind==TokenKind.ELVIS) { // a?:b (a if it isn't null, otherwise b)
if (expr==null) {
expr = new NullLiteral(toPos(t.startpos-1,t.endpos-2));
}
@ -120,7 +123,9 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -120,7 +123,9 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
valueIfNull = new NullLiteral(toPos(t.startpos+1,t.endpos+1));
}
return new Elvis(toPos(t),expr,valueIfNull);
} else if (t.kind==TokenKind.QMARK) { // a?b:c
}
if (t.kind==TokenKind.QMARK) { // a?b:c
if (expr==null) {
expr = new NullLiteral(toPos(t.startpos-1,t.endpos-1));
}
@ -167,31 +172,38 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -167,31 +172,38 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
SpelNodeImpl rhExpr = eatSumExpression();
checkOperands(t,expr,rhExpr);
TokenKind tk = relationalOperatorToken.kind;
if (relationalOperatorToken.isNumericRelationalOperator()) {
int pos = toPos(t);
if (tk==TokenKind.GT) {
return new OpGT(pos,expr,rhExpr);
} else if (tk==TokenKind.LT) {
return new OpLT(pos,expr,rhExpr);
} else if (tk==TokenKind.LE) {
return new OpLE(pos,expr,rhExpr);
} else if (tk==TokenKind.GE) {
return new OpGE(pos,expr,rhExpr);
} else if (tk == TokenKind.EQ) {
return new OpEQ(pos,expr,rhExpr);
} else {
Assert.isTrue(tk == TokenKind.NE);
return new OpNE(pos,expr,rhExpr);
if (tk == TokenKind.GT) {
return new OpGT(pos, expr, rhExpr);
}
if (tk == TokenKind.LT) {
return new OpLT(pos, expr, rhExpr);
}
if (tk == TokenKind.LE) {
return new OpLE(pos, expr, rhExpr);
}
if (tk == TokenKind.GE) {
return new OpGE(pos, expr, rhExpr);
}
if (tk == TokenKind.EQ) {
return new OpEQ(pos, expr, rhExpr);
}
Assert.isTrue(tk == TokenKind.NE);
return new OpNE(pos, expr, rhExpr);
}
if (tk == TokenKind.INSTANCEOF) {
return new OperatorInstanceof(toPos(t), expr, rhExpr);
}
if (tk==TokenKind.INSTANCEOF) {
return new OperatorInstanceof(toPos(t),expr,rhExpr);
} else if (tk==TokenKind.MATCHES) {
return new OperatorMatches(toPos(t),expr,rhExpr);
} else {
Assert.isTrue(tk==TokenKind.BETWEEN);
return new org.springframework.expression.spel.ast.OperatorBetween(toPos(t),expr,rhExpr);
if (tk == TokenKind.MATCHES) {
return new OperatorMatches(toPos(t), expr, rhExpr);
}
Assert.isTrue(tk == TokenKind.BETWEEN);
return new OperatorBetween(toPos(t), expr, rhExpr);
}
return expr;
}
@ -199,14 +211,15 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -199,14 +211,15 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
//sumExpression: productExpression ( (PLUS^ | MINUS^) productExpression)*;
private SpelNodeImpl eatSumExpression() {
SpelNodeImpl expr = eatProductExpression();
while (peekToken(TokenKind.PLUS,TokenKind.MINUS,TokenKind.INC)) {
while (peekToken(TokenKind.PLUS, TokenKind.MINUS, TokenKind.INC)) {
Token t = nextToken();//consume PLUS or MINUS or INC
SpelNodeImpl rhExpr = eatProductExpression();
checkRightOperand(t,rhExpr);
if (t.kind==TokenKind.PLUS) {
expr = new OpPlus(toPos(t),expr,rhExpr);
} else if (t.kind==TokenKind.MINUS) {
expr = new OpMinus(toPos(t),expr,rhExpr);
if (t.kind == TokenKind.PLUS) {
expr = new OpPlus(toPos(t), expr, rhExpr);
}
else if (t.kind == TokenKind.MINUS) {
expr = new OpMinus(toPos(t), expr, rhExpr);
}
}
return expr;
@ -215,17 +228,19 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -215,17 +228,19 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
// productExpression: powerExpr ((STAR^ | DIV^| MOD^) powerExpr)* ;
private SpelNodeImpl eatProductExpression() {
SpelNodeImpl expr = eatPowerIncDecExpression();
while (peekToken(TokenKind.STAR,TokenKind.DIV,TokenKind.MOD)) {
while (peekToken(TokenKind.STAR, TokenKind.DIV, TokenKind.MOD)) {
Token t = nextToken(); // consume STAR/DIV/MOD
SpelNodeImpl rhExpr = eatPowerIncDecExpression();
checkOperands(t,expr,rhExpr);
if (t.kind==TokenKind.STAR) {
expr = new OpMultiply(toPos(t),expr,rhExpr);
} else if (t.kind==TokenKind.DIV) {
expr = new OpDivide(toPos(t),expr,rhExpr);
} else {
Assert.isTrue(t.kind==TokenKind.MOD);
expr = new OpModulus(toPos(t),expr,rhExpr);
if (t.kind == TokenKind.STAR) {
expr = new OpMultiply(toPos(t), expr, rhExpr);
}
else if (t.kind == TokenKind.DIV) {
expr = new OpDivide(toPos(t), expr, rhExpr);
}
else {
Assert.isTrue(t.kind == TokenKind.MOD);
expr = new OpModulus(toPos(t), expr, rhExpr);
}
}
return expr;
@ -239,41 +254,45 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -239,41 +254,45 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
SpelNodeImpl rhExpr = eatUnaryExpression();
checkRightOperand(t,rhExpr);
return new OperatorPower(toPos(t),expr, rhExpr);
} else if (expr!=null && peekToken(TokenKind.INC,TokenKind.DEC)) {
}
if (expr!=null && peekToken(TokenKind.INC,TokenKind.DEC)) {
Token t = nextToken();//consume INC/DEC
if (t.getKind()==TokenKind.INC) {
return new OpInc(toPos(t),true,expr);
} else {
return new OpDec(toPos(t),true,expr);
}
return new OpDec(toPos(t),true,expr);
}
return expr;
}
// unaryExpression: (PLUS^ | MINUS^ | BANG^ | INC^ | DEC^) unaryExpression | primaryExpression ;
private SpelNodeImpl eatUnaryExpression() {
if (peekToken(TokenKind.PLUS,TokenKind.MINUS,TokenKind.NOT)) {
if (peekToken(TokenKind.PLUS, TokenKind.MINUS, TokenKind.NOT)) {
Token t = nextToken();
SpelNodeImpl expr = eatUnaryExpression();
if (t.kind==TokenKind.NOT) {
return new OperatorNot(toPos(t),expr);
} else if (t.kind==TokenKind.PLUS) {
return new OpPlus(toPos(t),expr);
} else {
Assert.isTrue(t.kind==TokenKind.MINUS);
return new OpMinus(toPos(t),expr);
}
} else if (peekToken(TokenKind.INC,TokenKind.DEC)) {
if (t.kind == TokenKind.NOT) {
return new OperatorNot(toPos(t), expr);
}
if (t.kind == TokenKind.PLUS) {
return new OpPlus(toPos(t), expr);
}
Assert.isTrue(t.kind == TokenKind.MINUS);
return new OpMinus(toPos(t), expr);
}
if (peekToken(TokenKind.INC, TokenKind.DEC)) {
Token t = nextToken();
SpelNodeImpl expr = eatUnaryExpression();
if (t.getKind()==TokenKind.INC) {
return new OpInc(toPos(t),false,expr);
} else {
return new OpDec(toPos(t),false,expr);
if (t.getKind() == TokenKind.INC) {
return new OpInc(toPos(t), false, expr);
}
} else {
return eatPrimaryExpression();
return new OpDec(toPos(t), false, expr);
}
return eatPrimaryExpression();
}
// primaryExpression : startNode (node)? -> ^(EXPRESSION startNode (node)?);
@ -284,11 +303,12 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -284,11 +303,12 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
while (maybeEatNode()) {
nodes.add(pop());
}
if (nodes.size()==1) {
if (nodes.size() == 1) {
return nodes.get(0);
} else {
return new CompoundExpression(toPos(start.getStartPosition(),nodes.get(nodes.size()-1).getEndPosition()),nodes.toArray(new SpelNodeImpl[nodes.size()]));
}
return new CompoundExpression(toPos(start.getStartPosition(),
nodes.get(nodes.size() - 1).getEndPosition()),
nodes.toArray(new SpelNodeImpl[nodes.size()]));
}
// node : ((DOT dottedNode) | (SAFE_NAVI dottedNode) | nonDottedNode)+;
@ -296,12 +316,15 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -296,12 +316,15 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
SpelNodeImpl expr = null;
if (peekToken(TokenKind.DOT,TokenKind.SAFE_NAVI)) {
expr = eatDottedNode();
} else {
}
else {
expr = maybeEatNonDottedNode();
}
if (expr==null) {
return false;
} else {
}
else {
push(expr);
return true;
}
@ -328,15 +351,19 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -328,15 +351,19 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
// ;
private SpelNodeImpl eatDottedNode() {
Token t = nextToken();// it was a '.' or a '?.'
boolean nullSafeNavigation = t.kind==TokenKind.SAFE_NAVI;
if (maybeEatMethodOrProperty(nullSafeNavigation) || maybeEatFunctionOrVar() || maybeEatProjection(nullSafeNavigation) || maybeEatSelection(nullSafeNavigation)) {
boolean nullSafeNavigation = t.kind == TokenKind.SAFE_NAVI;
if (maybeEatMethodOrProperty(nullSafeNavigation) || maybeEatFunctionOrVar()
|| maybeEatProjection(nullSafeNavigation)
|| maybeEatSelection(nullSafeNavigation)) {
return pop();
}
if (peekToken()==null) {
if (peekToken() == null) {
// unexpectedly ran out of data
raiseInternalException(t.startpos,SpelMessage.OOD);
} else {
raiseInternalException(t.startpos,SpelMessage.UNEXPECTED_DATA_AFTER_DOT,toString(peekToken()));
raiseInternalException(t.startpos, SpelMessage.OOD);
}
else {
raiseInternalException(t.startpos, SpelMessage.UNEXPECTED_DATA_AFTER_DOT,
toString(peekToken()));
}
return null;
}
@ -354,13 +381,15 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -354,13 +381,15 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
Token t = nextToken();
Token functionOrVariableName = eatToken(TokenKind.IDENTIFIER);
SpelNodeImpl[] args = maybeEatMethodArgs();
if (args==null) {
push(new VariableReference(functionOrVariableName.data,toPos(t.startpos,functionOrVariableName.endpos)));
return true;
} else {
push(new FunctionReference(functionOrVariableName.data,toPos(t.startpos,functionOrVariableName.endpos),args));
if (args == null) {
push(new VariableReference(functionOrVariableName.data, toPos(t.startpos,
functionOrVariableName.endpos)));
return true;
}
push(new FunctionReference(functionOrVariableName.data, toPos(t.startpos,
functionOrVariableName.endpos), args));
return true;
}
// methodArgs : LPAREN! (argument (COMMA! argument)* (COMMA!)?)? RPAREN!;
@ -376,7 +405,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -376,7 +405,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
private void eatConstructorArgs(List<SpelNodeImpl> accumulatedArguments) {
if (!peekToken(TokenKind.LPAREN)) {
throw new InternalParseException(new SpelParseException(expressionString,positionOf(peekToken()),SpelMessage.MISSING_CONSTRUCTOR_ARGS));
throw new InternalParseException(new SpelParseException(this.expressionString,positionOf(peekToken()),SpelMessage.MISSING_CONSTRUCTOR_ARGS));
}
consumeArguments(accumulatedArguments);
eatToken(TokenKind.RPAREN);
@ -391,27 +420,28 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -391,27 +420,28 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
do {
nextToken();// consume ( (first time through) or comma (subsequent times)
Token t = peekToken();
if (t==null) {
raiseInternalException(pos,SpelMessage.RUN_OUT_OF_ARGUMENTS);
if (t == null) {
raiseInternalException(pos, SpelMessage.RUN_OUT_OF_ARGUMENTS);
}
if (t.kind!=TokenKind.RPAREN) {
if (t.kind != TokenKind.RPAREN) {
accumulatedArguments.add(eatExpression());
}
next = peekToken();
} while (next!=null && next.kind==TokenKind.COMMA);
if (next==null) {
raiseInternalException(pos,SpelMessage.RUN_OUT_OF_ARGUMENTS);
}
while (next != null && next.kind == TokenKind.COMMA);
if (next == null) {
raiseInternalException(pos, SpelMessage.RUN_OUT_OF_ARGUMENTS);
}
}
private int positionOf(Token t) {
if (t==null) {
if (t == null) {
// if null assume the problem is because the right token was
// not found at the end of the expression
return expressionString.length();
} else {
return t.startpos;
return this.expressionString.length();
}
return t.startpos;
}
//startNode
@ -428,17 +458,26 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -428,17 +458,26 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
private SpelNodeImpl eatStartNode() {
if (maybeEatLiteral()) {
return pop();
} else if (maybeEatParenExpression()) {
}
else if (maybeEatParenExpression()) {
return pop();
} else if (maybeEatTypeReference() || maybeEatNullReference() || maybeEatConstructorReference() || maybeEatMethodOrProperty(false) || maybeEatFunctionOrVar()) {
}
else if (maybeEatTypeReference() || maybeEatNullReference()
|| maybeEatConstructorReference() || maybeEatMethodOrProperty(false)
|| maybeEatFunctionOrVar()) {
return pop();
} else if (maybeEatBeanReference()) {
}
else if (maybeEatBeanReference()) {
return pop();
} else if (maybeEatProjection(false) || maybeEatSelection(false) || maybeEatIndexer()) {
}
else if (maybeEatProjection(false) || maybeEatSelection(false)
|| maybeEatIndexer()) {
return pop();
} else if (maybeEatInlineList()) {
}
else if (maybeEatInlineList()) {
return pop();
} else {
}
else {
return null;
}
}
@ -453,16 +492,19 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -453,16 +492,19 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
if (peekToken(TokenKind.IDENTIFIER)) {
beanNameToken = eatToken(TokenKind.IDENTIFIER);
beanname = beanNameToken.data;
} else if (peekToken(TokenKind.LITERAL_STRING)) {
}
else if (peekToken(TokenKind.LITERAL_STRING)) {
beanNameToken = eatToken(TokenKind.LITERAL_STRING);
beanname = beanNameToken.stringValue();
beanname = beanname.substring(1, beanname.length() - 1);
} else {
raiseInternalException(beanRefToken.startpos,SpelMessage.INVALID_BEAN_REFERENCE);
}
else {
raiseInternalException(beanRefToken.startpos,
SpelMessage.INVALID_BEAN_REFERENCE);
}
BeanReference beanReference = new BeanReference(toPos(beanNameToken),beanname);
constructedNodes.push(beanReference);
this.constructedNodes.push(beanReference);
return true;
}
return false;
@ -485,7 +527,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -485,7 +527,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
dims++;
}
eatToken(TokenKind.RPAREN);
constructedNodes.push(new TypeReference(toPos(typeName),node,dims));
this.constructedNodes.push(new TypeReference(toPos(typeName),node,dims));
return true;
}
return false;
@ -498,7 +540,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -498,7 +540,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
return false;
}
nextToken();
constructedNodes.push(new NullLiteral(toPos(nullToken)));
this.constructedNodes.push(new NullLiteral(toPos(nullToken)));
return true;
}
return false;
@ -507,46 +549,49 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -507,46 +549,49 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
//projection: PROJECT^ expression RCURLY!;
private boolean maybeEatProjection(boolean nullSafeNavigation) {
Token t = peekToken();
if (!peekToken(TokenKind.PROJECT,true)) {
if (!peekToken(TokenKind.PROJECT, true)) {
return false;
}
SpelNodeImpl expr = eatExpression();
eatToken(TokenKind.RSQUARE);
constructedNodes.push(new Projection(nullSafeNavigation, toPos(t), expr));
this.constructedNodes.push(new Projection(nullSafeNavigation, toPos(t), expr));
return true;
}
// list = LCURLY (element (COMMA element)*) RCURLY
private boolean maybeEatInlineList() {
Token t = peekToken();
if (!peekToken(TokenKind.LCURLY,true)) {
if (!peekToken(TokenKind.LCURLY, true)) {
return false;
}
SpelNodeImpl expr = null;
Token closingCurly = peekToken();
if (peekToken(TokenKind.RCURLY,true)) {
if (peekToken(TokenKind.RCURLY, true)) {
// empty list '[]'
expr = new InlineList(toPos(t.startpos,closingCurly.endpos));
} else {
}
else {
List<SpelNodeImpl> listElements = new ArrayList<SpelNodeImpl>();
do {
listElements.add(eatExpression());
} while (peekToken(TokenKind.COMMA,true));
}
while (peekToken(TokenKind.COMMA,true));
closingCurly = eatToken(TokenKind.RCURLY);
expr = new InlineList(toPos(t.startpos,closingCurly.endpos),listElements.toArray(new SpelNodeImpl[listElements.size()]));
}
constructedNodes.push(expr);
this.constructedNodes.push(expr);
return true;
}
private boolean maybeEatIndexer() {
Token t = peekToken();
if (!peekToken(TokenKind.LSQUARE,true)) {
if (!peekToken(TokenKind.LSQUARE, true)) {
return false;
}
SpelNodeImpl expr = eatExpression();
eatToken(TokenKind.RSQUARE);
constructedNodes.push(new Indexer(toPos(t),expr));
this.constructedNodes.push(new Indexer(toPos(t),expr));
return true;
}
@ -557,16 +602,18 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -557,16 +602,18 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
}
nextToken();
SpelNodeImpl expr = eatExpression();
if(expr == null) {
if (expr == null) {
raiseInternalException(toPos(t), SpelMessage.MISSING_SELECTION_EXPRESSION);
}
eatToken(TokenKind.RSQUARE);
if (t.kind==TokenKind.SELECT_FIRST) {
constructedNodes.push(new Selection(nullSafeNavigation,Selection.FIRST,toPos(t),expr));
} else if (t.kind==TokenKind.SELECT_LAST) {
constructedNodes.push(new Selection(nullSafeNavigation,Selection.LAST,toPos(t),expr));
} else {
constructedNodes.push(new Selection(nullSafeNavigation,Selection.ALL,toPos(t),expr));
if (t.kind == TokenKind.SELECT_FIRST) {
this.constructedNodes.push(new Selection(nullSafeNavigation, Selection.FIRST, toPos(t), expr));
}
else if (t.kind == TokenKind.SELECT_LAST) {
this.constructedNodes.push(new Selection(nullSafeNavigation, Selection.LAST, toPos(t), expr));
}
else {
this.constructedNodes.push(new Selection(nullSafeNavigation, Selection.ALL, toPos(t), expr));
}
return true;
}
@ -580,14 +627,14 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -580,14 +627,14 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
Token node = peekToken();
while (isValidQualifiedId(node)) {
nextToken();
if(node.kind != TokenKind.DOT) {
if (node.kind != TokenKind.DOT) {
qualifiedIdPieces.add(new Identifier(node.stringValue(),toPos(node)));
}
node = peekToken();
}
if(qualifiedIdPieces.isEmpty()) {
if(node == null) {
raiseInternalException( expressionString.length(), SpelMessage.OOD);
if (qualifiedIdPieces.isEmpty()) {
if (node == null) {
raiseInternalException( this.expressionString.length(), SpelMessage.OOD);
}
raiseInternalException(node.startpos, SpelMessage.NOT_EXPECTED_TOKEN,
"qualified ID", node.getKind().toString().toLowerCase());
@ -597,10 +644,10 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -597,10 +644,10 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
}
private boolean isValidQualifiedId(Token node) {
if(node == null || node.kind == TokenKind.LITERAL_STRING) {
if (node == null || node.kind == TokenKind.LITERAL_STRING) {
return false;
}
if(node.kind == TokenKind.DOT || node.kind == TokenKind.IDENTIFIER) {
if (node.kind == TokenKind.DOT || node.kind == TokenKind.IDENTIFIER) {
return true;
}
String value = node.stringValue();
@ -617,19 +664,17 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -617,19 +664,17 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
// property
push(new PropertyOrFieldReference(nullSafeNavigation, methodOrPropertyName.data,toPos(methodOrPropertyName)));
return true;
} else {
// methodreference
push(new MethodReference(nullSafeNavigation, methodOrPropertyName.data,toPos(methodOrPropertyName),args));
// TODO what is the end position for a method reference? the name or the last arg?
return true;
}
// methodreference
push(new MethodReference(nullSafeNavigation, methodOrPropertyName.data,toPos(methodOrPropertyName),args));
// TODO what is the end position for a method reference? the name or the last arg?
return true;
}
return false;
}
//constructor
//: ('new' qualifiedId LPAREN) => 'new' qualifiedId ctorArgs -> ^(CONSTRUCTOR qualifiedId ctorArgs)
//: ('new' qualifiedId LPAREN) => 'new' qualifiedId ctorArgs -> ^(CONSTRUCTOR qualifiedId ctorArgs)
private boolean maybeEatConstructorReference() {
if (peekIdentifierToken("new")) {
Token newToken = nextToken();
@ -642,7 +687,8 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -642,7 +687,8 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
while (peekToken(TokenKind.LSQUARE,true)) {
if (!peekToken(TokenKind.RSQUARE)) {
dimensions.add(eatExpression());
} else {
}
else {
dimensions.add(null);
}
eatToken(TokenKind.RSQUARE);
@ -652,11 +698,13 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -652,11 +698,13 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
}
push(new ConstructorReference(toPos(newToken), dimensions.toArray(new SpelNodeImpl[dimensions.size()]),
nodes.toArray(new SpelNodeImpl[nodes.size()])));
} else {
}
else {
// regular constructor invocation
eatConstructorArgs(nodes);
// TODO correct end position?
push(new ConstructorReference(toPos(newToken), nodes.toArray(new SpelNodeImpl[nodes.size()])));
push(new ConstructorReference(toPos(newToken),
nodes.toArray(new SpelNodeImpl[nodes.size()])));
}
return true;
}
@ -664,11 +712,11 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -664,11 +712,11 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
}
private void push(SpelNodeImpl newNode) {
constructedNodes.push(newNode);
this.constructedNodes.push(newNode);
}
private SpelNodeImpl pop() {
return constructedNodes.pop();
return this.constructedNodes.pop();
}
// literal
@ -684,25 +732,34 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -684,25 +732,34 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
if (t==null) {
return false;
}
if (t.kind==TokenKind.LITERAL_INT) {
if (t.kind == TokenKind.LITERAL_INT) {
push(Literal.getIntLiteral(t.data, toPos(t), 10));
} else if (t.kind==TokenKind.LITERAL_LONG) {
}
else if (t.kind == TokenKind.LITERAL_LONG) {
push(Literal.getLongLiteral(t.data, toPos(t), 10));
} else if (t.kind==TokenKind.LITERAL_HEXINT) {
}
else if (t.kind == TokenKind.LITERAL_HEXINT) {
push(Literal.getIntLiteral(t.data, toPos(t), 16));
} else if (t.kind==TokenKind.LITERAL_HEXLONG) {
}
else if (t.kind == TokenKind.LITERAL_HEXLONG) {
push(Literal.getLongLiteral(t.data, toPos(t), 16));
} else if (t.kind==TokenKind.LITERAL_REAL) {
push(Literal.getRealLiteral(t.data, toPos(t),false));
} else if (t.kind==TokenKind.LITERAL_REAL_FLOAT) {
}
else if (t.kind == TokenKind.LITERAL_REAL) {
push(Literal.getRealLiteral(t.data, toPos(t), false));
}
else if (t.kind == TokenKind.LITERAL_REAL_FLOAT) {
push(Literal.getRealLiteral(t.data, toPos(t), true));
} else if (peekIdentifierToken("true")) {
push(new BooleanLiteral(t.data,toPos(t),true));
} else if (peekIdentifierToken("false")) {
push(new BooleanLiteral(t.data,toPos(t),false));
} else if (t.kind==TokenKind.LITERAL_STRING) {
push(new StringLiteral(t.data,toPos(t),t.data));
} else {
}
else if (peekIdentifierToken("true")) {
push(new BooleanLiteral(t.data, toPos(t), true));
}
else if (peekIdentifierToken("false")) {
push(new BooleanLiteral(t.data, toPos(t), false));
}
else if (t.kind == TokenKind.LITERAL_STRING) {
push(new StringLiteral(t.data, toPos(t), t.data));
}
else {
return false;
}
nextToken();
@ -717,7 +774,8 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -717,7 +774,8 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
eatToken(TokenKind.RPAREN);
push(expr);
return true;
} else {
}
else {
return false;
}
}
@ -727,7 +785,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -727,7 +785,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
// | GREATER_THAN_OR_EQUAL | INSTANCEOF | BETWEEN | MATCHES
private Token maybeEatRelationalOperator() {
Token t = peekToken();
if (t==null) {
if (t == null) {
return null;
}
if (t.isNumericRelationalOperator()) {
@ -737,9 +795,11 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -737,9 +795,11 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
String idString = t.stringValue();
if (idString.equalsIgnoreCase("instanceof")) {
return t.asInstanceOfToken();
} else if (idString.equalsIgnoreCase("matches")) {
}
if (idString.equalsIgnoreCase("matches")) {
return t.asMatchesToken();
} else if (idString.equalsIgnoreCase("between")) {
}
if (idString.equalsIgnoreCase("between")) {
return t.asBetweenToken();
}
}
@ -748,10 +808,10 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -748,10 +808,10 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
private Token eatToken(TokenKind expectedKind) {
Token t = nextToken();
if (t==null) {
raiseInternalException( expressionString.length(), SpelMessage.OOD);
if (t == null) {
raiseInternalException( this.expressionString.length(), SpelMessage.OOD);
}
if (t.kind!=expectedKind) {
if (t.kind != expectedKind) {
raiseInternalException(t.startpos,SpelMessage.NOT_EXPECTED_TOKEN, expectedKind.toString().toLowerCase(),t.getKind().toString().toLowerCase());
}
return t;
@ -766,34 +826,38 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -766,34 +826,38 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
return false;
}
Token t = peekToken();
if (t.kind==desiredTokenKind) {
if (t.kind == desiredTokenKind) {
if (consumeIfMatched) {
tokenStreamPointer++;
this.tokenStreamPointer++;
}
return true;
} else {
if (desiredTokenKind == TokenKind.IDENTIFIER) {
// might be one of the textual forms of the operators (e.g. NE for != ) - in which case we can treat it as an identifier
// The list is represented here: Tokenizer.alternativeOperatorNames and those ones are in order in the TokenKind enum
if (t.kind.ordinal()>=TokenKind.DIV.ordinal() && t.kind.ordinal()<=TokenKind.NOT.ordinal() && t.data!=null) {
// if t.data were null, we'd know it wasn't the textual form, it was the symbol form
return true;
}
}
if (desiredTokenKind == TokenKind.IDENTIFIER) {
// might be one of the textual forms of the operators (e.g. NE for != ) - in which case we can treat it as an identifier
// The list is represented here: Tokenizer.alternativeOperatorNames and those ones are in order in the TokenKind enum
if (t.kind.ordinal() >= TokenKind.DIV.ordinal() && t.kind.ordinal() <= TokenKind.NOT.ordinal() && t.data != null) {
// if t.data were null, we'd know it wasn't the textual form, it was the symbol form
return true;
}
return false;
}
return false;
}
private boolean peekToken(TokenKind possible1,TokenKind possible2) {
if (!moreTokens()) return false;
if (!moreTokens()) {
return false;
}
Token t = peekToken();
return t.kind==possible1 || t.kind==possible2;
return (t.kind == possible1 || t.kind == possible2);
}
private boolean peekToken(TokenKind possible1,TokenKind possible2, TokenKind possible3) {
if (!moreTokens()) return false;
if (!moreTokens()) {
return false;
}
Token t = peekToken();
return t.kind==possible1 || t.kind==possible2 || t.kind==possible3;
return t.kind == possible1 || t.kind == possible2 || t.kind == possible3;
}
private boolean peekIdentifierToken(String identifierString) {
@ -805,39 +869,42 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -805,39 +869,42 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
}
private boolean peekSelectToken() {
if (!moreTokens()) return false;
if (!moreTokens()) {
return false;
}
Token t = peekToken();
return t.kind==TokenKind.SELECT || t.kind==TokenKind.SELECT_FIRST || t.kind==TokenKind.SELECT_LAST;
return t.kind == TokenKind.SELECT || t.kind == TokenKind.SELECT_FIRST
|| t.kind == TokenKind.SELECT_LAST;
}
private boolean moreTokens() {
return tokenStreamPointer<tokenStream.size();
return this.tokenStreamPointer<this.tokenStream.size();
}
private Token nextToken() {
if (tokenStreamPointer>=tokenStreamLength) {
if (this.tokenStreamPointer >= this.tokenStreamLength) {
return null;
}
return tokenStream.get(tokenStreamPointer++);
return this.tokenStream.get(this.tokenStreamPointer++);
}
private Token peekToken() {
if (tokenStreamPointer>=tokenStreamLength) {
if (this.tokenStreamPointer >= this.tokenStreamLength) {
return null;
}
return tokenStream.get(tokenStreamPointer);
return this.tokenStream.get(this.tokenStreamPointer);
}
private void raiseInternalException(int pos, SpelMessage message,Object... inserts) {
throw new InternalParseException(new SpelParseException(expressionString,pos,message,inserts));
private void raiseInternalException(int pos, SpelMessage message, Object... inserts) {
throw new InternalParseException(new SpelParseException(this.expressionString,
pos, message, inserts));
}
public String toString(Token t) {
if (t.getKind().hasPayload()) {
return t.stringValue();
} else {
return t.kind.toString().toLowerCase();
}
return t.kind.toString().toLowerCase();
}
private void checkOperands(Token token, SpelNodeImpl left, SpelNodeImpl right) {
@ -858,14 +925,14 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -858,14 +925,14 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
}
/**
* Compress the start and end of a token into a single int
* Compress the start and end of a token into a single int.
*/
private int toPos(Token t) {
return (t.startpos<<16)+t.endpos;
return (t.startpos<<16) + t.endpos;
}
private int toPos(int start,int end) {
return (start<<16)+end;
return (start<<16) + end;
}
}

57
spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/GenericCallMetaDataProvider.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -72,26 +72,34 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider { @@ -72,26 +72,34 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider {
try {
setSupportsCatalogsInProcedureCalls(databaseMetaData.supportsCatalogsInProcedureCalls());
}
catch (SQLException se) {
logger.warn("Error retrieving 'DatabaseMetaData.supportsCatalogsInProcedureCalls' - " + se.getMessage());
catch (SQLException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Error retrieving 'DatabaseMetaData.supportsCatalogsInProcedureCalls' - " + ex.getMessage());
}
}
try {
setSupportsSchemasInProcedureCalls(databaseMetaData.supportsSchemasInProcedureCalls());
}
catch (SQLException se) {
logger.warn("Error retrieving 'DatabaseMetaData.supportsSchemasInProcedureCalls' - " + se.getMessage());
catch (SQLException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Error retrieving 'DatabaseMetaData.supportsSchemasInProcedureCalls' - " + ex.getMessage());
}
}
try {
setStoresUpperCaseIdentifiers(databaseMetaData.storesUpperCaseIdentifiers());
}
catch (SQLException se) {
logger.warn("Error retrieving 'DatabaseMetaData.storesUpperCaseIdentifiers' - " + se.getMessage());
catch (SQLException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Error retrieving 'DatabaseMetaData.storesUpperCaseIdentifiers' - " + ex.getMessage());
}
}
try {
setStoresLowerCaseIdentifiers(databaseMetaData.storesLowerCaseIdentifiers());
}
catch (SQLException se) {
logger.warn("Error retrieving 'DatabaseMetaData.storesLowerCaseIdentifiers' - " + se.getMessage());
catch (SQLException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Error retrieving 'DatabaseMetaData.storesLowerCaseIdentifiers' - " + ex.getMessage());
}
}
}
@ -113,7 +121,7 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider { @@ -113,7 +121,7 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider {
else if (isStoresUpperCaseIdentifiers()) {
return procedureName.toUpperCase();
}
else if(isStoresLowerCaseIdentifiers()) {
else if (isStoresLowerCaseIdentifiers()) {
return procedureName.toLowerCase();
}
else {
@ -128,7 +136,7 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider { @@ -128,7 +136,7 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider {
else if (isStoresUpperCaseIdentifiers()) {
return catalogName.toUpperCase();
}
else if(isStoresLowerCaseIdentifiers()) {
else if (isStoresLowerCaseIdentifiers()) {
return catalogName.toLowerCase();
}
else {
@ -143,7 +151,7 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider { @@ -143,7 +151,7 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider {
else if (isStoresUpperCaseIdentifiers()) {
return schemaName.toUpperCase();
}
else if(isStoresLowerCaseIdentifiers()) {
else if (isStoresLowerCaseIdentifiers()) {
return schemaName.toLowerCase();
}
else {
@ -176,7 +184,7 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider { @@ -176,7 +184,7 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider {
else if (isStoresUpperCaseIdentifiers()) {
return parameterName.toUpperCase();
}
else if(isStoresLowerCaseIdentifiers()) {
else if (isStoresLowerCaseIdentifiers()) {
return parameterName.toLowerCase();
}
else {
@ -321,12 +329,8 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider { @@ -321,12 +329,8 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider {
columnType == DatabaseMetaData.procedureColumnInOut ||
columnType == DatabaseMetaData.procedureColumnOut)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping metadata for: "
+ columnName +
" " + columnType +
" " + procs.getInt("DATA_TYPE") +
" " + procs.getString("TYPE_NAME") +
" " + procs.getBoolean("NULLABLE") +
logger.debug("Skipping metadata for: " + columnType + " " + procs.getInt("DATA_TYPE") +
" " + procs.getString("TYPE_NAME") + " " + procs.getBoolean("NULLABLE") +
" (probably a member of a collection)"
);
}
@ -335,18 +339,19 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider { @@ -335,18 +339,19 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider {
CallParameterMetaData meta = new CallParameterMetaData(columnName, columnType,
procs.getInt("DATA_TYPE"), procs.getString("TYPE_NAME"), procs.getBoolean("NULLABLE")
);
callParameterMetaData.add(meta);
this.callParameterMetaData.add(meta);
if (logger.isDebugEnabled()) {
logger.debug("Retrieved metadata: " + meta.getParameterName() + " " +
meta.getParameterType() + " " + meta.getSqlType() +
" " + meta.getTypeName() + " " + meta.isNullable()
);
meta.getParameterType() + " " + meta.getSqlType() + " " +
meta.getTypeName() + " " + meta.isNullable());
}
}
}
}
catch (SQLException ex) {
logger.warn("Error while retrieving metadata for procedure columns: " + ex);
if (logger.isWarnEnabled()) {
logger.warn("Error while retrieving metadata for procedure columns: " + ex);
}
}
finally {
try {
@ -355,7 +360,9 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider { @@ -355,7 +360,9 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider {
}
}
catch (SQLException ex) {
logger.warn("Problem closing ResultSet for procedure column metadata: " + ex);
if (logger.isWarnEnabled()) {
logger.warn("Problem closing ResultSet for procedure column metadata: " + ex);
}
}
}
}

69
spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/GenericTableMetaDataProvider.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@ -85,34 +85,23 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -85,34 +85,23 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
}
/**
* Specify whether identifiers use upper case
*/
public void setStoresUpperCaseIdentifiers(boolean storesUpperCaseIdentifiers) {
this.storesUpperCaseIdentifiers = storesUpperCaseIdentifiers;
}
/**
* Get whether identifiers use upper case
*/
public boolean isStoresUpperCaseIdentifiers() {
return this.storesUpperCaseIdentifiers;
}
/**
* Specify whether identifiers use lower case.
*/
public void setStoresLowerCaseIdentifiers(boolean storesLowerCaseIdentifiers) {
this.storesLowerCaseIdentifiers = storesLowerCaseIdentifiers;
}
/**
* Get whether identifiers use lower case
*/
public boolean isStoresLowerCaseIdentifiers() {
return this.storesLowerCaseIdentifiers;
}
public boolean isTableColumnMetaDataUsed() {
return this.tableColumnMetaDataUsed;
}
@ -133,16 +122,10 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -133,16 +122,10 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
return null;
}
/**
* Specify whether a column name array is supported for generated keys
*/
public void setGetGeneratedKeysSupported(boolean getGeneratedKeysSupported) {
this.getGeneratedKeysSupported = getGeneratedKeysSupported;
}
/**
* Specify whether a column name array is supported for generated keys
*/
public void setGeneratedKeysColumnNameArraySupported(boolean generatedKeysColumnNameArraySupported) {
this.generatedKeysColumnNameArraySupported = generatedKeysColumnNameArraySupported;
}
@ -171,8 +154,8 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -171,8 +154,8 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
setGetGeneratedKeysSupported(false);
}
}
catch (SQLException se) {
logger.warn("Error retrieving 'DatabaseMetaData.getGeneratedKeys' - " + se.getMessage());
catch (SQLException ex) {
logger.warn("Error retrieving 'DatabaseMetaData.getGeneratedKeys' - " + ex.getMessage());
}
try {
String databaseProductName = databaseMetaData.getDatabaseProductName();
@ -190,26 +173,26 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -190,26 +173,26 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
}
}
}
catch (SQLException se) {
logger.warn("Error retrieving 'DatabaseMetaData.getDatabaseProductName' - " + se.getMessage());
catch (SQLException ex) {
logger.warn("Error retrieving 'DatabaseMetaData.getDatabaseProductName' - " + ex.getMessage());
}
try {
this.databaseVersion = databaseMetaData.getDatabaseProductVersion();
}
catch (SQLException se) {
logger.warn("Error retrieving 'DatabaseMetaData.getDatabaseProductVersion' - " + se.getMessage());
catch (SQLException ex) {
logger.warn("Error retrieving 'DatabaseMetaData.getDatabaseProductVersion' - " + ex.getMessage());
}
try {
setStoresUpperCaseIdentifiers(databaseMetaData.storesUpperCaseIdentifiers());
}
catch (SQLException se) {
logger.warn("Error retrieving 'DatabaseMetaData.storesUpperCaseIdentifiers' - " + se.getMessage());
catch (SQLException ex) {
logger.warn("Error retrieving 'DatabaseMetaData.storesUpperCaseIdentifiers' - " + ex.getMessage());
}
try {
setStoresLowerCaseIdentifiers(databaseMetaData.storesLowerCaseIdentifiers());
}
catch (SQLException se) {
logger.warn("Error retrieving 'DatabaseMetaData.storesLowerCaseIdentifiers' - " + se.getMessage());
catch (SQLException ex) {
logger.warn("Error retrieving 'DatabaseMetaData.storesLowerCaseIdentifiers' - " + ex.getMessage());
}
}
@ -228,7 +211,7 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -228,7 +211,7 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
else if (isStoresUpperCaseIdentifiers()) {
return tableName.toUpperCase();
}
else if(isStoresLowerCaseIdentifiers()) {
else if (isStoresLowerCaseIdentifiers()) {
return tableName.toLowerCase();
}
else {
@ -243,7 +226,7 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -243,7 +226,7 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
else if (isStoresUpperCaseIdentifiers()) {
return catalogName.toUpperCase();
}
else if(isStoresLowerCaseIdentifiers()) {
else if (isStoresLowerCaseIdentifiers()) {
return catalogName.toLowerCase();
}
else {
@ -258,7 +241,7 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -258,7 +241,7 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
else if (isStoresUpperCaseIdentifiers()) {
return schemaName.toUpperCase();
}
else if(isStoresLowerCaseIdentifiers()) {
else if (isStoresLowerCaseIdentifiers()) {
return schemaName.toLowerCase();
}
else {
@ -311,22 +294,23 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -311,22 +294,23 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
tmd.setSchemaName(tables.getString("TABLE_SCHEM"));
tmd.setTableName(tables.getString("TABLE_NAME"));
if (tmd.getSchemaName() == null) {
tableMeta.put(userName != null ? userName.toUpperCase() : "", tmd);
tableMeta.put(this.userName != null ? this.userName.toUpperCase() : "", tmd);
}
else {
tableMeta.put(tmd.getSchemaName().toUpperCase(), tmd);
}
}
}
catch (SQLException se) {
logger.warn("Error while accessing table meta data results" + se.getMessage());
catch (SQLException ex) {
logger.warn("Error while accessing table meta data results" + ex.getMessage());
}
finally {
if (tables != null) {
try {
tables.close();
} catch (SQLException e) {
logger.warn("Error while closing table meta data reults" + e.getMessage());
}
catch (SQLException ex) {
logger.warn("Error while closing table meta data results" + ex.getMessage());
}
}
}
@ -365,7 +349,7 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -365,7 +349,7 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
}
/**
* Method supporting the metedata processing for a table's columns
* Method supporting the metadata processing for a table's columns
*/
private void processTableColumns(DatabaseMetaData databaseMetaData, TableMetaData tmd) {
ResultSet tableColumns = null;
@ -417,16 +401,16 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -417,16 +401,16 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
}
}
}
catch (SQLException se) {
logger.warn("Error while retrieving metadata for table columns: " + se.getMessage());
catch (SQLException ex) {
logger.warn("Error while retrieving metadata for table columns: " + ex.getMessage());
}
finally {
try {
if (tableColumns != null)
tableColumns.close();
}
catch (SQLException se) {
logger.warn("Problem closing ResultSet for table column metadata " + se.getMessage());
catch (SQLException ex) {
logger.warn("Problem closing ResultSet for table column metadata " + ex.getMessage());
}
}
@ -444,7 +428,6 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { @@ -444,7 +428,6 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider {
private String tableName;
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}

24
spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslator.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -65,22 +65,22 @@ public class SQLExceptionSubclassTranslator extends AbstractFallbackSQLException @@ -65,22 +65,22 @@ public class SQLExceptionSubclassTranslator extends AbstractFallbackSQLException
@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
if (ex instanceof SQLTransientException) {
if (ex instanceof SQLTransactionRollbackException) {
return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
}
if (ex instanceof SQLTransientConnectionException) {
return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
}
if (ex instanceof SQLTimeoutException) {
else if (ex instanceof SQLTransactionRollbackException) {
return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
}
else if (ex instanceof SQLTimeoutException) {
return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
}
}
else if (ex instanceof SQLNonTransientException) {
if (ex instanceof SQLDataException) {
return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
if (ex instanceof SQLNonTransientConnectionException) {
return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
}
else if (ex instanceof SQLFeatureNotSupportedException) {
return new InvalidDataAccessApiUsageException(buildMessage(task, sql, ex), ex);
else if (ex instanceof SQLDataException) {
return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
}
else if (ex instanceof SQLIntegrityConstraintViolationException) {
return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
@ -88,12 +88,12 @@ public class SQLExceptionSubclassTranslator extends AbstractFallbackSQLException @@ -88,12 +88,12 @@ public class SQLExceptionSubclassTranslator extends AbstractFallbackSQLException
else if (ex instanceof SQLInvalidAuthorizationSpecException) {
return new PermissionDeniedDataAccessException(buildMessage(task, sql, ex), ex);
}
else if (ex instanceof SQLNonTransientConnectionException) {
return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
}
else if (ex instanceof SQLSyntaxErrorException) {
return new BadSqlGrammarException(task, sql, ex);
}
else if (ex instanceof SQLFeatureNotSupportedException) {
return new InvalidDataAccessApiUsageException(buildMessage(task, sql, ex), ex);
}
}
else if (ex instanceof SQLRecoverableException) {
return new RecoverableDataAccessException(buildMessage(task, sql, ex), ex);

8
spring-jms/src/main/java/org/springframework/jms/connection/SingleConnectionFactory.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -384,7 +384,7 @@ public class SingleConnectionFactory @@ -384,7 +384,7 @@ public class SingleConnectionFactory
/**
* Create a default Session for this ConnectionFactory,
* adaptign to JMS 1.0.2 style queue/topic mode if necessary.
* adapting to JMS 1.0.2 style queue/topic mode if necessary.
* @param con the JMS Connection to operate on
* @param mode the Session acknowledgement mode
* ({@code Session.TRANSACTED} or one of the common modes)
@ -443,7 +443,7 @@ public class SingleConnectionFactory @@ -443,7 +443,7 @@ public class SingleConnectionFactory
* @return the wrapped Connection
*/
protected Connection getSharedConnectionProxy(Connection target) {
List<Class> classes = new ArrayList<Class>(3);
List<Class<?>> classes = new ArrayList<Class<?>>(3);
classes.add(Connection.class);
if (target instanceof QueueConnection) {
classes.add(QueueConnection.class);
@ -453,7 +453,7 @@ public class SingleConnectionFactory @@ -453,7 +453,7 @@ public class SingleConnectionFactory
}
return (Connection) Proxy.newProxyInstance(
Connection.class.getClassLoader(),
classes.toArray(new Class[classes.size()]),
classes.toArray(new Class<?>[classes.size()]),
new SharedConnectionInvocationHandler(target));
}

8
spring-jms/src/main/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactory.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -26,7 +26,7 @@ import org.springframework.beans.BeanWrapper; @@ -26,7 +26,7 @@ import org.springframework.beans.BeanWrapper;
/**
* Default implementation of the {@link JmsActivationSpecFactory} interface.
* Supports the standard JMS properties as defined by the JMS 1.5 specification,
* Supports the standard JMS properties as defined by the JCA 1.5 specification,
* as well as Spring's extended "maxConcurrency" and "prefetchSize" settings
* through autodetection of well-known vendor-specific provider properties.
*
@ -72,7 +72,7 @@ public class DefaultJmsActivationSpecFactory extends StandardJmsActivationSpecFa @@ -72,7 +72,7 @@ public class DefaultJmsActivationSpecFactory extends StandardJmsActivationSpecFa
* "ActiveMQActivationSpec" in the same package, or a class named
* "ActivationSpecImpl" in the same package as the ResourceAdapter class.
*/
protected Class determineActivationSpecClass(ResourceAdapter adapter) {
protected Class<?> determineActivationSpecClass(ResourceAdapter adapter) {
String adapterClassName = adapter.getClass().getName();
if (adapterClassName.endsWith(RESOURCE_ADAPTER_SUFFIX)) {
@ -156,7 +156,7 @@ public class DefaultJmsActivationSpecFactory extends StandardJmsActivationSpecFa @@ -156,7 +156,7 @@ public class DefaultJmsActivationSpecFactory extends StandardJmsActivationSpecFa
// JORAM
bw.setPropertyValue("maxMessages", Integer.toString(config.getPrefetchSize()));
}
else if(bw.isWritableProperty("maxBatchSize")){
else if (bw.isWritableProperty("maxBatchSize")){
// WebSphere
bw.setPropertyValue("maxBatchSize", Integer.toString(config.getPrefetchSize()));
}

8
spring-jms/src/main/java/org/springframework/jms/listener/endpoint/StandardJmsActivationSpecFactory.java

@ -50,7 +50,7 @@ import org.springframework.jms.support.destination.DestinationResolver; @@ -50,7 +50,7 @@ import org.springframework.jms.support.destination.DestinationResolver;
*/
public class StandardJmsActivationSpecFactory implements JmsActivationSpecFactory {
private Class activationSpecClass;
private Class<?> activationSpecClass;
private Map<String, String> defaultProperties;
@ -61,7 +61,7 @@ public class StandardJmsActivationSpecFactory implements JmsActivationSpecFactor @@ -61,7 +61,7 @@ public class StandardJmsActivationSpecFactory implements JmsActivationSpecFactor
* Specify the fully-qualified ActivationSpec class name for the target
* provider (e.g. "org.apache.activemq.ra.ActiveMQActivationSpec").
*/
public void setActivationSpecClass(Class activationSpecClass) {
public void setActivationSpecClass(Class<?> activationSpecClass) {
this.activationSpecClass = activationSpecClass;
}
@ -92,7 +92,7 @@ public class StandardJmsActivationSpecFactory implements JmsActivationSpecFactor @@ -92,7 +92,7 @@ public class StandardJmsActivationSpecFactory implements JmsActivationSpecFactor
public ActivationSpec createActivationSpec(ResourceAdapter adapter, JmsActivationSpecConfig config) {
Class activationSpecClassToUse = this.activationSpecClass;
Class<?> activationSpecClassToUse = this.activationSpecClass;
if (activationSpecClassToUse == null) {
activationSpecClassToUse = determineActivationSpecClass(adapter);
if (activationSpecClassToUse == null) {
@ -117,7 +117,7 @@ public class StandardJmsActivationSpecFactory implements JmsActivationSpecFactor @@ -117,7 +117,7 @@ public class StandardJmsActivationSpecFactory implements JmsActivationSpecFactor
* if not determinable
* @see #setActivationSpecClass
*/
protected Class determineActivationSpecClass(ResourceAdapter adapter) {
protected Class<?> determineActivationSpecClass(ResourceAdapter adapter) {
return null;
}

10
spring-jms/src/main/java/org/springframework/jms/support/JmsAccessor.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -86,7 +86,7 @@ public abstract class JmsAccessor implements InitializingBean { @@ -86,7 +86,7 @@ public abstract class JmsAccessor implements InitializingBean {
* <p>Setting this flag to "true" will use a short local JMS transaction
* when running outside of a managed transaction, and a synchronized local
* JMS transaction in case of a managed transaction (other than an XA
* transaction) being present. The latter has the effect of a local JMS
* transaction) being present. This has the effect of a local JMS
* transaction being managed alongside the main transaction (which might
* be a native JDBC transaction), with the JMS transaction committing
* right after the main transaction.
@ -109,7 +109,7 @@ public abstract class JmsAccessor implements InitializingBean { @@ -109,7 +109,7 @@ public abstract class JmsAccessor implements InitializingBean {
* Set the JMS acknowledgement mode by the name of the corresponding constant
* in the JMS {@link Session} interface, e.g. "CLIENT_ACKNOWLEDGE".
* <p>If you want to use vendor-specific extensions to the acknowledgment mode,
* use {@link #setSessionAcknowledgeModeName(String)} instead.
* use {@link #setSessionAcknowledgeMode(int)} instead.
* @param constantName the name of the {@link Session} acknowledge mode constant
* @see javax.jms.Session#AUTO_ACKNOWLEDGE
* @see javax.jms.Session#CLIENT_ACKNOWLEDGE
@ -125,8 +125,8 @@ public abstract class JmsAccessor implements InitializingBean { @@ -125,8 +125,8 @@ public abstract class JmsAccessor implements InitializingBean {
* {@link Session} to send a message.
* <p>Default is {@link Session#AUTO_ACKNOWLEDGE}.
* <p>Vendor-specific extensions to the acknowledgment mode can be set here as well.
* <p>Note that that inside an EJB the parameters to
* create(Queue/Topic)Session(boolean transacted, int acknowledgeMode) method
* <p>Note that that inside an EJB, the parameters to the
* {@code create(Queue/Topic)Session(boolean transacted, int acknowledgeMode)} method
* are not taken into account. Depending on the transaction context in the EJB,
* the container makes its own decisions on these values. See section 17.3.5
* of the EJB spec.

43
spring-test/src/main/java/org/springframework/test/context/support/AbstractDelegatingSmartContextLoader.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -57,7 +57,7 @@ import org.springframework.util.ObjectUtils; @@ -57,7 +57,7 @@ import org.springframework.util.ObjectUtils;
* files nor annotated classes and instead declare only {@linkplain
* ContextConfiguration#initializers application context initializers}. In such
* cases, an attempt will still be made to detect defaults, but their absence will
* not result an an exception.
* not result in an exception.
*
* @author Sam Brannen
* @since 3.2
@ -78,6 +78,7 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -78,6 +78,7 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
*/
protected abstract SmartContextLoader getAnnotationConfigLoader();
// --- SmartContextLoader --------------------------------------------------
private static String name(SmartContextLoader loader) {
@ -94,6 +95,7 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -94,6 +95,7 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
private static ApplicationContext delegateLoading(SmartContextLoader loader, MergedContextConfiguration mergedConfig)
throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Delegating to %s to load context from %s.", name(loader), mergedConfig));
}
@ -103,7 +105,8 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -103,7 +105,8 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
private boolean supports(SmartContextLoader loader, MergedContextConfiguration mergedConfig) {
if (loader == getAnnotationConfigLoader()) {
return ObjectUtils.isEmpty(mergedConfig.getLocations()) && !ObjectUtils.isEmpty(mergedConfig.getClasses());
} else {
}
else {
return !ObjectUtils.isEmpty(mergedConfig.getLocations()) && ObjectUtils.isEmpty(mergedConfig.getClasses());
}
}
@ -111,12 +114,10 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -111,12 +114,10 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
/**
* Delegates to candidate {@code SmartContextLoaders} to process the supplied
* {@link ContextConfigurationAttributes}.
*
* <p>Delegation is based on explicit knowledge of the implementations of the
* default loaders for {@link #getXmlLoader() XML configuration files} and
* {@link #getAnnotationConfigLoader() annotated classes}. Specifically, the
* delegation algorithm is as follows:
*
* <ul>
* <li>If the resource locations or annotated classes in the supplied
* {@code ContextConfigurationAttributes} are not empty, the appropriate
@ -131,7 +132,6 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -131,7 +132,6 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
* If the annotation-based loader detects default configuration
* classes, an {@code info} message will be logged.</li>
* </ul>
*
* @param configAttributes the context configuration attributes to process
* @throws IllegalArgumentException if the supplied configuration attributes are
* {@code null}, or if the supplied configuration attributes include both
@ -146,17 +146,19 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -146,17 +146,19 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
Assert.notNull(configAttributes, "configAttributes must not be null");
Assert.isTrue(!(configAttributes.hasLocations() && configAttributes.hasClasses()), String.format(
"Cannot process locations AND classes for context "
+ "configuration %s; configure one or the other, but not both.", configAttributes));
"Cannot process locations AND classes for context configuration %s; configure one or the other, but not both.",
configAttributes));
// If the original locations or classes were not empty, there's no
// need to bother with default detection checks; just let the
// appropriate loader process the configuration.
if (configAttributes.hasLocations()) {
delegateProcessing(getXmlLoader(), configAttributes);
} else if (configAttributes.hasClasses()) {
}
else if (configAttributes.hasClasses()) {
delegateProcessing(getAnnotationConfigLoader(), configAttributes);
} else {
}
else {
// Else attempt to detect defaults...
// Let the XML loader process the configuration.
@ -197,15 +199,15 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -197,15 +199,15 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
// throw an exception.
if (!configAttributes.hasResources() && ObjectUtils.isEmpty(configAttributes.getInitializers())) {
throw new IllegalStateException(String.format(
"Neither %s nor %s was able to detect defaults, and no ApplicationContextInitializers "
+ "were declared for context configuration %s", name(getXmlLoader()),
"Neither %s nor %s was able to detect defaults, and no ApplicationContextInitializers " +
"were declared for context configuration %s", name(getXmlLoader()),
name(getAnnotationConfigLoader()), configAttributes));
}
if (configAttributes.hasLocations() && configAttributes.hasClasses()) {
String message = String.format(
"Configuration error: both default locations AND default configuration classes "
+ "were detected for context configuration %s; configure one or the other, but not both.",
"Configuration error: both default locations AND default configuration classes " +
"were detected for context configuration %s; configure one or the other, but not both.",
configAttributes);
logger.error(message);
throw new IllegalStateException(message);
@ -216,12 +218,10 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -216,12 +218,10 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
/**
* Delegates to an appropriate candidate {@code SmartContextLoader} to load
* an {@link ApplicationContext}.
*
* <p>Delegation is based on explicit knowledge of the implementations of the
* default loaders for {@link #getXmlLoader() XML configuration files} and
* {@link #getAnnotationConfigLoader() annotated classes}. Specifically, the
* delegation algorithm is as follows:
*
* <ul>
* <li>If the resource locations in the supplied {@code MergedContextConfiguration}
* are not empty and the annotated classes are empty,
@ -230,7 +230,6 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -230,7 +230,6 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
* are not empty and the resource locations are empty,
* the annotation-based loader will load the {@code ApplicationContext}.</li>
* </ul>
*
* @param mergedConfig the merged context configuration to use to load the application context
* @throws IllegalArgumentException if the supplied merged configuration is {@code null}
* @throws IllegalStateException if neither candidate loader is capable of loading an
@ -238,7 +237,6 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -238,7 +237,6 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
*/
public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {
Assert.notNull(mergedConfig, "mergedConfig must not be null");
List<SmartContextLoader> candidates = Arrays.asList(getXmlLoader(), getAnnotationConfigLoader());
for (SmartContextLoader loader : candidates) {
@ -260,6 +258,7 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -260,6 +258,7 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
name(getAnnotationConfigLoader()), mergedConfig));
}
// --- ContextLoader -------------------------------------------------------
/**
@ -269,8 +268,8 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -269,8 +268,8 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
* @throws UnsupportedOperationException
*/
public final String[] processLocations(Class<?> clazz, String... locations) {
throw new UnsupportedOperationException("DelegatingSmartContextLoaders do not support the ContextLoader SPI. "
+ "Call processContextConfiguration(ContextConfigurationAttributes) instead.");
throw new UnsupportedOperationException("DelegatingSmartContextLoaders do not support the ContextLoader SPI. " +
"Call processContextConfiguration(ContextConfigurationAttributes) instead.");
}
/**
@ -280,8 +279,8 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte @@ -280,8 +279,8 @@ public abstract class AbstractDelegatingSmartContextLoader implements SmartConte
* @throws UnsupportedOperationException
*/
public final ApplicationContext loadContext(String... locations) throws Exception {
throw new UnsupportedOperationException("DelegatingSmartContextLoaders do not support the ContextLoader SPI. "
+ "Call loadContext(MergedContextConfiguration) instead.");
throw new UnsupportedOperationException("DelegatingSmartContextLoaders do not support the ContextLoader SPI. " +
"Call loadContext(MergedContextConfiguration) instead.");
}
}

40
spring-test/src/main/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtils.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -22,6 +22,7 @@ import java.util.List; @@ -22,6 +22,7 @@ import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.SmartContextLoader;
import org.springframework.util.Assert;
@ -38,22 +39,10 @@ public abstract class AnnotationConfigContextLoaderUtils { @@ -38,22 +39,10 @@ public abstract class AnnotationConfigContextLoaderUtils {
private static final Log logger = LogFactory.getLog(AnnotationConfigContextLoaderUtils.class);
private AnnotationConfigContextLoaderUtils() {
/* no-op */
}
private static boolean isStaticNonPrivateAndNonFinal(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
int modifiers = clazz.getModifiers();
return (Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers) && !Modifier.isFinal(modifiers));
}
/**
* Determine if the supplied {@link Class} meets the criteria for being
* considered a <em>default configuration class</em> candidate.
*
* <p>Specifically, such candidates:
*
* <ul>
* <li>must not be {@code null}</li>
* <li>must not be {@code private}</li>
@ -61,7 +50,6 @@ public abstract class AnnotationConfigContextLoaderUtils { @@ -61,7 +50,6 @@ public abstract class AnnotationConfigContextLoaderUtils {
* <li>must be {@code static}</li>
* <li>must be annotated with {@code @Configuration}</li>
* </ul>
*
* @param clazz the class to check
* @return {@code true} if the supplied class meets the candidate criteria
*/
@ -69,38 +57,42 @@ public abstract class AnnotationConfigContextLoaderUtils { @@ -69,38 +57,42 @@ public abstract class AnnotationConfigContextLoaderUtils {
return clazz != null && isStaticNonPrivateAndNonFinal(clazz) && clazz.isAnnotationPresent(Configuration.class);
}
private static boolean isStaticNonPrivateAndNonFinal(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
int modifiers = clazz.getModifiers();
return (Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers) && !Modifier.isFinal(modifiers));
}
/**
* Detect the default configuration classes for the supplied test class.
*
* <p>The returned class array will contain all static inner classes of
* the supplied class that meet the requirements for {@code @Configuration}
* class implementations as specified in the documentation for
* {@link Configuration @Configuration}.
*
* <p>The implementation of this method adheres to the contract defined in the
* {@link org.springframework.test.context.SmartContextLoader SmartContextLoader}
* SPI. Specifically, this method uses introspection to detect default
* configuration classes that comply with the constraints required of
* {@code @Configuration} class implementations. If a potential candidate
* configuration class does not meet these requirements, this method will log a
* warning, and the potential candidate class will be ignored.
* debug message, and the potential candidate class will be ignored.
* @param declaringClass the test class that declared {@code @ContextConfiguration}
* @return an array of default configuration classes, potentially empty but
* never {@code null}
*/
public static Class<?>[] detectDefaultConfigurationClasses(Class<?> declaringClass) {
Assert.notNull(declaringClass, "Declaring class must not be null");
List<Class<?>> configClasses = new ArrayList<Class<?>>();
for (Class<?> candidate : declaringClass.getDeclaredClasses()) {
if (isDefaultConfigurationClassCandidate(candidate)) {
configClasses.add(candidate);
} else {
}
else {
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"Ignoring class [%s]; it must be static, non-private, non-final, and annotated "
+ "with @Configuration to be considered a default configuration class.",
"Ignoring class [%s]; it must be static, non-private, non-final, and annotated " +
"with @Configuration to be considered a default configuration class.",
candidate.getName()));
}
}
@ -108,9 +100,9 @@ public abstract class AnnotationConfigContextLoaderUtils { @@ -108,9 +100,9 @@ public abstract class AnnotationConfigContextLoaderUtils {
if (configClasses.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Could not detect default configuration classes for test class [%s]: "
+ "%s does not declare any static, non-private, non-final, inner classes "
+ "annotated with @Configuration.", declaringClass.getName(), declaringClass.getSimpleName()));
logger.info(String.format("Could not detect default configuration classes for test class [%s]: " +
"%s does not declare any static, non-private, non-final, inner classes " +
"annotated with @Configuration.", declaringClass.getName(), declaringClass.getSimpleName()));
}
}

8
spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@ -47,13 +47,13 @@ final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest { @@ -47,13 +47,13 @@ final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest {
private final boolean outputStreaming;
SimpleStreamingClientHttpRequest(HttpURLConnection connection, int chunkSize,
boolean outputStreaming) {
SimpleStreamingClientHttpRequest(HttpURLConnection connection, int chunkSize, boolean outputStreaming) {
this.connection = connection;
this.chunkSize = chunkSize;
this.outputStreaming = outputStreaming;
}
public HttpMethod getMethod() {
return HttpMethod.valueOf(this.connection.getRequestMethod());
}
@ -70,7 +70,7 @@ final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest { @@ -70,7 +70,7 @@ final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest {
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
if (this.body == null) {
if(this.outputStreaming) {
if (this.outputStreaming) {
int contentLength = (int) headers.getContentLength();
if (contentLength >= 0) {
this.connection.setFixedLengthStreamingMode(contentLength);

8
spring-web/src/main/java/org/springframework/http/converter/feed/AbstractWireFeedHttpMessageConverter.java

@ -62,12 +62,8 @@ public abstract class AbstractWireFeedHttpMessageConverter<T extends WireFeed> e @@ -62,12 +62,8 @@ public abstract class AbstractWireFeedHttpMessageConverter<T extends WireFeed> e
WireFeedInput feedInput = new WireFeedInput();
MediaType contentType = inputMessage.getHeaders().getContentType();
Charset charset;
if (contentType != null && contentType.getCharSet() != null) {
charset = contentType.getCharSet();
} else {
charset = DEFAULT_CHARSET;
}
Charset charset =
(contentType != null && contentType.getCharSet() != null? contentType.getCharSet() : DEFAULT_CHARSET);
try {
Reader reader = new InputStreamReader(inputMessage.getBody(), charset);
return (T) feedInput.build(reader);

3
spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java

@ -186,7 +186,8 @@ public class ContentNegotiationManagerFactoryBean @@ -186,7 +186,8 @@ public class ContentNegotiationManagerFactoryBean
PathExtensionContentNegotiationStrategy strategy;
if (this.servletContext != null) {
strategy = new ServletPathExtensionContentNegotiationStrategy(this.servletContext, this.mediaTypes);
} else {
}
else {
strategy = new PathExtensionContentNegotiationStrategy(this.mediaTypes);
}
if (this.useJaf != null) {

81
spring-web/src/main/java/org/springframework/web/filter/CompositeFilter.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -19,7 +19,6 @@ package org.springframework.web.filter; @@ -19,7 +19,6 @@ package org.springframework.web.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
@ -28,81 +27,87 @@ import javax.servlet.ServletRequest; @@ -28,81 +27,87 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* A generic composite servlet {@link Filter} that just delegates its behaviour to a chain (list) of user supplied
* filters, achieving the functionality of a {@link FilterChain}, but conveniently using only {@link Filter} instances.
* This is useful for filters that require dependency injection, and can therefore be set up in a Spring application
* context. Typically this composite would be used in conjunction with {@link DelegatingFilterProxy}, so that it can be
* declared in Spring but applied to a servlet context.
* A generic composite servlet {@link Filter} that just delegates its behavior
* to a chain (list) of user-supplied filters, achieving the functionality of a
* {@link FilterChain}, but conveniently using only {@link Filter} instances.
*
* @since 3.1
* <p>This is useful for filters that require dependency injection, and can
* therefore be set up in a Spring application context. Typically, this
* composite would be used in conjunction with {@link DelegatingFilterProxy},
* so that it can be declared in Spring but applied to a servlet context.
*
* @author Dave Syer
*
* @since 3.1
*/
public class CompositeFilter implements Filter {
private List<? extends Filter> filters = new ArrayList<Filter>();
public void setFilters(List<? extends Filter> filters) {
this.filters = new ArrayList<Filter>(filters);
}
/**
* Clean up all the filters supplied, calling each one's destroy method in turn, but in reverse order.
*
* @see Filter#init(FilterConfig)
*/
public void destroy() {
for (int i = filters.size(); i-- > 0;) {
Filter filter = filters.get(i);
filter.destroy();
}
}
/**
* Initialize all the filters, calling each one's init method in turn in the order supplied.
*
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig config) throws ServletException {
for (Filter filter : filters) {
for (Filter filter : this.filters) {
filter.init(config);
}
}
/**
* Forms a temporary chain from the list of delegate filters supplied ({@link #setFilters(List)}) and executes them
* in order. Each filter delegates to the next one in the list, achieving the normal behaviour of a
* {@link FilterChain}, despite the fact that this is a {@link Filter}.
*
* Forms a temporary chain from the list of delegate filters supplied ({@link #setFilters})
* and executes them in order. Each filter delegates to the next one in the list, achieving
* the normal behavior of a {@link FilterChain}, despite the fact that this is a {@link Filter}.
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
new VirtualFilterChain(chain, filters).doFilter(request, response);
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
new VirtualFilterChain(chain, this.filters).doFilter(request, response);
}
/**
* Clean up all the filters supplied, calling each one's destroy method in turn, but in reverse order.
* @see Filter#init(FilterConfig)
*/
public void destroy() {
for (int i = this.filters.size(); i-- > 0;) {
Filter filter = this.filters.get(i);
filter.destroy();
}
}
private static class VirtualFilterChain implements FilterChain {
private final FilterChain originalChain;
private final List<? extends Filter> additionalFilters;
private int currentPosition = 0;
private VirtualFilterChain(FilterChain chain, List<? extends Filter> additionalFilters) {
public VirtualFilterChain(FilterChain chain, List<? extends Filter> additionalFilters) {
this.originalChain = chain;
this.additionalFilters = additionalFilters;
}
public void doFilter(final ServletRequest request, final ServletResponse response) throws IOException,
ServletException {
if (currentPosition == additionalFilters.size()) {
originalChain.doFilter(request, response);
} else {
currentPosition++;
Filter nextFilter = additionalFilters.get(currentPosition - 1);
public void doFilter(final ServletRequest request, final ServletResponse response)
throws IOException, ServletException {
if (this.currentPosition == this.additionalFilters.size()) {
this.originalChain.doFilter(request, response);
}
else {
this.currentPosition++;
Filter nextFilter = this.additionalFilters.get(this.currentPosition - 1);
nextFilter.doFilter(request, response, this);
}
}
}
}

88
spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -53,49 +53,30 @@ public class ControllerAdviceBean implements Ordered { @@ -53,49 +53,30 @@ public class ControllerAdviceBean implements Ordered {
* @param beanFactory a BeanFactory that can be used later to resolve the bean
*/
public ControllerAdviceBean(String beanName, BeanFactory beanFactory) {
Assert.hasText(beanName, "'beanName' must not be null");
Assert.notNull(beanFactory, "'beanFactory' must not be null");
Assert.isTrue(beanFactory.containsBean(beanName),
"Bean factory [" + beanFactory + "] does not contain bean " + "with name [" + beanName + "]");
Assert.hasText(beanName, "Bean name must not be null");
Assert.notNull(beanFactory, "BeanFactory must not be null");
if (!beanFactory.containsBean(beanName)) {
throw new IllegalArgumentException(
"BeanFactory [" + beanFactory + "] does not contain bean with name '" + beanName + "'");
}
this.bean = beanName;
this.beanFactory = beanFactory;
this.order = initOrderFromBeanType(this.beanFactory.getType(beanName));
}
private static int initOrderFromBeanType(Class<?> beanType) {
Order annot = AnnotationUtils.findAnnotation(beanType, Order.class);
return (annot != null) ? annot.value() : Ordered.LOWEST_PRECEDENCE;
}
/**
* Create an instance using the given bean instance.
* @param bean the bean
*/
public ControllerAdviceBean(Object bean) {
Assert.notNull(bean, "'bean' must not be null");
Assert.notNull(bean, "Bean must not be null");
this.bean = bean;
this.order = initOrderFromBean(bean);
this.beanFactory = null;
}
private static int initOrderFromBean(Object bean) {
return (bean instanceof Ordered) ? ((Ordered) bean).getOrder() : initOrderFromBeanType(bean.getClass());
}
/**
* Find the names of beans annotated with
* {@linkplain ControllerAdvice @ControllerAdvice} in the given
* ApplicationContext and wrap them as {@code ControllerAdviceBean} instances.
*/
public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext applicationContext) {
List<ControllerAdviceBean> beans = new ArrayList<ControllerAdviceBean>();
for (String name : applicationContext.getBeanDefinitionNames()) {
if (applicationContext.findAnnotationOnBean(name, ControllerAdvice.class) != null) {
beans.add(new ControllerAdviceBean(name, applicationContext));
}
}
return beans;
}
/**
* Returns the order value extracted from the {@link ControllerAdvice}
@ -110,9 +91,8 @@ public class ControllerAdviceBean implements Ordered { @@ -110,9 +91,8 @@ public class ControllerAdviceBean implements Ordered {
* If the bean type is a CGLIB-generated class, the original, user-defined class is returned.
*/
public Class<?> getBeanType() {
Class<?> clazz = (this.bean instanceof String)
? this.beanFactory.getType((String) this.bean) : this.bean.getClass();
Class<?> clazz = (this.bean instanceof String ?
this.beanFactory.getType((String) this.bean) : this.bean.getClass());
return ClassUtils.getUserClass(clazz);
}
@ -120,29 +100,49 @@ public class ControllerAdviceBean implements Ordered { @@ -120,29 +100,49 @@ public class ControllerAdviceBean implements Ordered {
* Return a bean instance if necessary resolving the bean name through the BeanFactory.
*/
public Object resolveBean() {
return (this.bean instanceof String) ? this.beanFactory.getBean((String) this.bean) : this.bean;
return (this.bean instanceof String ? this.beanFactory.getBean((String) this.bean) : this.bean);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o != null && o instanceof ControllerAdviceBean) {
ControllerAdviceBean other = (ControllerAdviceBean) o;
return this.bean.equals(other.bean);
}
return false;
public boolean equals(Object other) {
return (this == other ||
(other instanceof ControllerAdviceBean && this.bean.equals(((ControllerAdviceBean) other).bean)));
}
@Override
public int hashCode() {
return 31 * this.bean.hashCode();
return this.bean.hashCode();
}
@Override
public String toString() {
return bean.toString();
return this.bean.toString();
}
/**
* Find the names of beans annotated with
* {@linkplain ControllerAdvice @ControllerAdvice} in the given
* ApplicationContext and wrap them as {@code ControllerAdviceBean} instances.
*/
public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext applicationContext) {
List<ControllerAdviceBean> beans = new ArrayList<ControllerAdviceBean>();
for (String name : applicationContext.getBeanDefinitionNames()) {
if (applicationContext.findAnnotationOnBean(name, ControllerAdvice.class) != null) {
beans.add(new ControllerAdviceBean(name, applicationContext));
}
}
return beans;
}
private static int initOrderFromBean(Object bean) {
return (bean instanceof Ordered ? ((Ordered) bean).getOrder() : initOrderFromBeanType(bean.getClass()));
}
private static int initOrderFromBeanType(Class<?> beanType) {
Order ann = AnnotationUtils.findAnnotation(beanType, Order.class);
return (ann != null ? ann.value() : Ordered.LOWEST_PRECEDENCE);
}
}

2
spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java

@ -147,7 +147,7 @@ public class ExceptionHandlerMethodResolver { @@ -147,7 +147,7 @@ public class ExceptionHandlerMethodResolver {
*/
private Method getMappedMethod(Class<? extends Exception> exceptionType) {
List<Class<? extends Throwable>> matches = new ArrayList<Class<? extends Throwable>>();
for(Class<? extends Throwable> mappedException : this.mappedMethods.keySet()) {
for (Class<? extends Throwable> mappedException : this.mappedMethods.keySet()) {
if (mappedException.isAssignableFrom(exceptionType)) {
matches.add(mappedException);
}

38
spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -20,7 +20,6 @@ import java.beans.PropertyEditor; @@ -20,7 +20,6 @@ import java.beans.PropertyEditor;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -72,34 +71,35 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod @@ -72,34 +71,35 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
private final boolean useDefaultResolution;
/**
* @param beanFactory a bean factory used for resolving ${...} placeholder
* and #{...} SpEL expressions in default values, or {@code null} if default
* values are not expected to contain expressions
* @param useDefaultResolution in default resolution mode a method argument
* that is a simple type, as defined in {@link BeanUtils#isSimpleProperty},
* is treated as a request parameter even if it itsn't annotated, the
* is treated as a request parameter even if it it isn't annotated, the
* request parameter name is derived from the method parameter name.
*/
public RequestParamMethodArgumentResolver(ConfigurableBeanFactory beanFactory,
boolean useDefaultResolution) {
public RequestParamMethodArgumentResolver(ConfigurableBeanFactory beanFactory, boolean useDefaultResolution) {
super(beanFactory);
this.useDefaultResolution = useDefaultResolution;
}
/**
* Supports the following:
* <ul>
* <li>@RequestParam-annotated method arguments.
* This excludes {@link Map} params where the annotation doesn't
* specify a name. See {@link RequestParamMapMethodArgumentResolver}
* instead for such params.
* <li>Arguments of type {@link MultipartFile}
* unless annotated with @{@link RequestPart}.
* <li>Arguments of type {@code javax.servlet.http.Part}
* unless annotated with @{@link RequestPart}.
* <li>In default resolution mode, simple type arguments
* even if not with @{@link RequestParam}.
* <li>@RequestParam-annotated method arguments.
* This excludes {@link Map} params where the annotation doesn't
* specify a name. See {@link RequestParamMapMethodArgumentResolver}
* instead for such params.
* <li>Arguments of type {@link MultipartFile}
* unless annotated with @{@link RequestPart}.
* <li>Arguments of type {@code javax.servlet.http.Part}
* unless annotated with @{@link RequestPart}.
* <li>In default resolution mode, simple type arguments
* even if not with @{@link RequestParam}.
* </ul>
*/
public boolean supportsParameter(MethodParameter parameter) {
@ -139,7 +139,6 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod @@ -139,7 +139,6 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
@Override
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest webRequest) throws Exception {
Object arg;
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
@ -202,13 +201,14 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod @@ -202,13 +201,14 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
throw new MissingServletRequestParameterException(paramName, parameter.getParameterType().getSimpleName());
}
private class RequestParamNamedValueInfo extends NamedValueInfo {
private RequestParamNamedValueInfo() {
private static class RequestParamNamedValueInfo extends NamedValueInfo {
public RequestParamNamedValueInfo() {
super("", false, ValueConstants.DEFAULT_NONE);
}
private RequestParamNamedValueInfo(RequestParam annotation) {
public RequestParamNamedValueInfo(RequestParam annotation) {
super(annotation.value(), annotation.required(), annotation.defaultValue());
}
}

4
spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java

@ -392,7 +392,7 @@ final class HierarchicalUriComponents extends UriComponents { @@ -392,7 +392,7 @@ final class HierarchicalUriComponents extends UriComponents {
String path = getPath();
if (StringUtils.hasLength(path) && path.charAt(0) != PATH_DELIMITER) {
// Only prefix the path delimiter if something exists before it
if(getScheme() != null || getUserInfo() != null || getHost() != null || getPort() != -1) {
if (getScheme() != null || getUserInfo() != null || getHost() != null || getPort() != -1) {
path = PATH_DELIMITER + path;
}
}
@ -605,7 +605,7 @@ final class HierarchicalUriComponents extends UriComponents { @@ -605,7 +605,7 @@ final class HierarchicalUriComponents extends UriComponents {
}
public String getPath() {
return path;
return this.path;
}
public List<String> getPathSegments() {

4
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/ProducesRequestCondition.java

@ -103,7 +103,7 @@ public final class ProducesRequestCondition extends AbstractRequestCondition<Pro @@ -103,7 +103,7 @@ public final class ProducesRequestCondition extends AbstractRequestCondition<Pro
for (String header : headers) {
HeaderExpression expr = new HeaderExpression(header);
if ("Accept".equalsIgnoreCase(expr.name)) {
for( MediaType mediaType : MediaType.parseMediaTypes(expr.value)) {
for (MediaType mediaType : MediaType.parseMediaTypes(expr.value)) {
result.add(new ProduceMediaTypeExpression(mediaType, expr.isNegated));
}
}
@ -160,7 +160,7 @@ public final class ProducesRequestCondition extends AbstractRequestCondition<Pro @@ -160,7 +160,7 @@ public final class ProducesRequestCondition extends AbstractRequestCondition<Pro
* overrides a type-level "produces" condition.
*/
public ProducesRequestCondition combine(ProducesRequestCondition other) {
return !other.expressions.isEmpty() ? other : this;
return (!other.expressions.isEmpty() ? other : this);
}
/**

2
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/RequestMethodsRequestCondition.java

@ -97,7 +97,7 @@ public final class RequestMethodsRequestCondition extends AbstractRequestConditi @@ -97,7 +97,7 @@ public final class RequestMethodsRequestCondition extends AbstractRequestConditi
return this;
}
RequestMethod incomingRequestMethod = getRequestMethod(request);
if(incomingRequestMethod != null) {
if (incomingRequestMethod != null) {
for (RequestMethod method : this.methods) {
if (method.equals(incomingRequestMethod)) {
return new RequestMethodsRequestCondition(method);

39
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -28,7 +28,6 @@ import javax.servlet.http.HttpServletRequest; @@ -28,7 +28,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
@ -68,34 +67,31 @@ import org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionRes @@ -68,34 +67,31 @@ import org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionRes
* @author Rossen Stoyanchev
* @since 3.1
*/
public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExceptionResolver implements
InitializingBean, ApplicationContextAware {
public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExceptionResolver
implements InitializingBean, ApplicationContextAware {
private List<HandlerMethodArgumentResolver> customArgumentResolvers;
private HandlerMethodArgumentResolverComposite argumentResolvers;
private List<HandlerMethodReturnValueHandler> customReturnValueHandlers;
private HandlerMethodReturnValueHandlerComposite returnValueHandlers;
private List<HttpMessageConverter<?>> messageConverters;
private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();
private ApplicationContext applicationContext;
private final Map<Class<?>, ExceptionHandlerMethodResolver> exceptionHandlerCache =
new ConcurrentHashMap<Class<?>, ExceptionHandlerMethodResolver>(64);
private final Map<ControllerAdviceBean, ExceptionHandlerMethodResolver> exceptionHandlerAdviceCache =
new LinkedHashMap<ControllerAdviceBean, ExceptionHandlerMethodResolver>();
private HandlerMethodArgumentResolverComposite argumentResolvers;
private HandlerMethodReturnValueHandlerComposite returnValueHandlers;
private ApplicationContext applicationContext;
/**
* Default constructor.
*/
public ExceptionHandlerExceptionResolver() {
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false); // See SPR-7316
@ -106,6 +102,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce @@ -106,6 +102,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
/**
* Provide resolvers for custom argument types. Custom resolvers are ordered
* after built-in ones. To override the built-in support for argument
@ -194,7 +191,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce @@ -194,7 +191,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
* Return the configured message body converters.
*/
public List<HttpMessageConverter<?>> getMessageConverters() {
return messageConverters;
return this.messageConverters;
}
/**
@ -205,7 +202,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce @@ -205,7 +202,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
this.contentNegotiationManager = contentNegotiationManager;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@ -213,6 +210,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce @@ -213,6 +210,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
return this.applicationContext;
}
public void afterPropertiesSet() {
if (this.argumentResolvers == null) {
List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();
@ -291,11 +289,14 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce @@ -291,11 +289,14 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(bean.getBeanType());
if (resolver.hasExceptionMappings()) {
this.exceptionHandlerAdviceCache.put(bean, resolver);
logger.info("Detected @ExceptionHandler methods in " + bean);
if (logger.isDebugEnabled()) {
logger.debug("Detected @ExceptionHandler methods in " + bean);
}
}
}
}
/**
* Find an {@code @ExceptionHandler} method and invoke it to handle the raised exception.
*/
@ -321,7 +322,9 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce @@ -321,7 +322,9 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception);
}
catch (Exception invocationEx) {
logger.error("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx);
if (logger.isErrorEnabled()) {
logger.error("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx);
}
return null;
}
@ -361,12 +364,14 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce @@ -361,12 +364,14 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
return new ServletInvocableHandlerMethod(handlerMethod.getBean(), method);
}
}
for (Entry<ControllerAdviceBean, ExceptionHandlerMethodResolver> entry : this.exceptionHandlerAdviceCache.entrySet()) {
Method method = entry.getValue().resolveMethod(exception);
if (method != null) {
return new ServletInvocableHandlerMethod(entry.getKey().resolveBean(), method);
}
}
return null;
}

3
spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/OptionsTag.java

@ -150,7 +150,8 @@ public class OptionsTag extends AbstractHtmlElementTag { @@ -150,7 +150,8 @@ public class OptionsTag extends AbstractHtmlElementTag {
Object itemsObject = null;
if (items != null) {
itemsObject = (items instanceof String ? evaluate("items", items) : items);
} else {
}
else {
Class<?> selectTagBoundType = selectTag.getBindStatus().getValueType();
if (selectTagBoundType != null && selectTagBoundType.isEnum()) {
itemsObject = selectTagBoundType.getEnumConstants();

19
spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/PasswordInputTag.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* 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.
@ -35,20 +35,21 @@ public class PasswordInputTag extends InputTag { @@ -35,20 +35,21 @@ public class PasswordInputTag extends InputTag {
/**
* Is the password value to be rendered?
* @return {@code true} if the password value to be rendered.
* @param showPassword {@code true} if the password value is to be rendered
*/
public boolean isShowPassword() {
return this.showPassword;
public void setShowPassword(boolean showPassword) {
this.showPassword = showPassword;
}
/**
* Is the password value to be rendered?
* @param showPassword {@code true} if the password value is to be rendered.
* @return {@code true} if the password value to be rendered
*/
public void setShowPassword(boolean showPassword) {
this.showPassword = showPassword;
public boolean isShowPassword() {
return this.showPassword;
}
/**
* Flags "type" as an illegal dynamic attribute.
*/
@ -75,8 +76,10 @@ public class PasswordInputTag extends InputTag { @@ -75,8 +76,10 @@ public class PasswordInputTag extends InputTag {
protected void writeValue(TagWriter tagWriter) throws JspException {
if (this.showPassword) {
super.writeValue(tagWriter);
} else {
}
else {
tagWriter.writeAttribute("value", processFieldValue(getName(), "", getType()));
}
}
}

Loading…
Cancel
Save