diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactory.java b/spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactory.java index 51f8d01f53..db1e19a359 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactory.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactory.java @@ -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,6 @@ package org.springframework.aop.framework; import org.aopalliance.intercept.Interceptor; import org.springframework.aop.TargetSource; -import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** @@ -47,9 +46,8 @@ public class ProxyFactory extends ProxyCreatorSupport { * @param target the target object to be proxied */ public ProxyFactory(Object target) { - Assert.notNull(target, "Target object must not be null"); - setInterfaces(ClassUtils.getAllInterfaces(target)); setTarget(target); + setInterfaces(ClassUtils.getAllInterfaces(target)); } /** diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java b/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java index f7b5677635..4893c0d74e 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java @@ -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. @@ -239,7 +239,7 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser { return new RegexPatternTypeFilter(Pattern.compile(expression)); } else if ("custom".equals(filterType)) { - Class filterClass = classLoader.loadClass(expression); + Class filterClass = classLoader.loadClass(expression); if (!TypeFilter.class.isAssignableFrom(filterClass)) { throw new IllegalArgumentException( "Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression); @@ -256,8 +256,8 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser { } @SuppressWarnings("unchecked") - private Object instantiateUserDefinedStrategy(String className, Class strategyType, ClassLoader classLoader) { - Object result = null; + private Object instantiateUserDefinedStrategy(String className, Class strategyType, ClassLoader classLoader) { + Object result; try { result = classLoader.loadClass(className).newInstance(); } @@ -267,7 +267,7 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser { } catch (Exception ex) { throw new IllegalArgumentException("Unable to instantiate class [" + className + "] for strategy [" + - strategyType.getName() + "]. A zero-argument constructor is required", ex); + strategyType.getName() + "]: a zero-argument constructor is required", ex); } if (!strategyType.isAssignableFrom(result.getClass())) { diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClass.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClass.java index 644065e5dc..0b16e6bfca 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClass.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClass.java @@ -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. @@ -179,7 +179,7 @@ final class ConfigurationClass { for (BeanMethod beanMethod : this.beanMethods) { String fqMethodName = beanMethod.getFullyQualifiedMethodName(); Integer currentCount = methodNameCounts.get(fqMethodName); - int newCount = currentCount != null ? currentCount + 1 : 1; + int newCount = (currentCount != null ? currentCount + 1 : 1); methodNameCounts.put(fqMethodName, newCount); } for (String fqMethodName : methodNameCounts.keySet()) { diff --git a/spring-core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java b/spring-core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java index d846d4fdae..953cce667a 100644 --- a/spring-core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java +++ b/spring-core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java @@ -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. @@ -101,8 +101,8 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD // We couldn't load the class file, which is not fatal as it // simply means this method of discovering parameter names won't work. if (logger.isDebugEnabled()) { - logger.debug("Cannot find '.class' file for class [" + clazz - + "] - unable to determine constructors/methods parameter names"); + logger.debug("Cannot find '.class' file for class [" + clazz + + "] - unable to determine constructor/method parameter names"); } return NO_DEBUG_INFO_MAP; } @@ -115,14 +115,14 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD catch (IOException ex) { if (logger.isDebugEnabled()) { logger.debug("Exception thrown while reading '.class' file for class [" + clazz + - "] - unable to determine constructors/methods parameter names", ex); + "] - unable to determine constructor/method parameter names", ex); } } catch (IllegalArgumentException ex) { if (logger.isDebugEnabled()) { logger.debug("ASM ClassReader failed to parse class file [" + clazz + "], probably due to a new Java class file version that isn't supported yet " + - "- unable to determine constructors/methods parameter names", ex); + "- unable to determine constructor/method parameter names", ex); } } finally { @@ -146,6 +146,7 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD private static final String STATIC_CLASS_INIT = ""; private final Class clazz; + private final Map memberMap; public ParameterNameDiscoveringVisitor(Class clazz, Map memberMap) { @@ -178,12 +179,17 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD private static final String CONSTRUCTOR = ""; private final Class clazz; + private final Map memberMap; + private final String name; + private final Type[] args; + + private final String[] parameterNames; + private final boolean isStatic; - private String[] parameterNames; private boolean hasLvtInfo = false; /* @@ -192,25 +198,22 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD */ private final int[] lvtSlotIndex; - public LocalVariableTableVisitor(Class clazz, Map map, String name, String desc, - boolean isStatic) { + public LocalVariableTableVisitor(Class clazz, Map map, String name, String desc, boolean isStatic) { super(SpringAsmInfo.ASM_VERSION); this.clazz = clazz; this.memberMap = map; this.name = name; - // determine args - args = Type.getArgumentTypes(desc); - this.parameterNames = new String[args.length]; + this.args = Type.getArgumentTypes(desc); + this.parameterNames = new String[this.args.length]; this.isStatic = isStatic; - this.lvtSlotIndex = computeLvtSlotIndices(isStatic, args); + this.lvtSlotIndex = computeLvtSlotIndices(isStatic, this.args); } @Override - public void visitLocalVariable(String name, String description, String signature, Label start, Label end, - int index) { + public void visitLocalVariable(String name, String description, String signature, Label start, Label end, int index) { this.hasLvtInfo = true; - for (int i = 0; i < lvtSlotIndex.length; i++) { - if (lvtSlotIndex[i] == index) { + for (int i = 0; i < this.lvtSlotIndex.length; i++) { + if (this.lvtSlotIndex[i] == index) { this.parameterNames[i] = name; } } @@ -223,27 +226,25 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD // which doesn't use any local variables. // This means that hasLvtInfo could be false for that kind of methods // even if the class has local variable info. - memberMap.put(resolveMember(), parameterNames); + this.memberMap.put(resolveMember(), this.parameterNames); } } private Member resolveMember() { - ClassLoader loader = clazz.getClassLoader(); - Class[] classes = new Class[args.length]; - - // resolve args - for (int i = 0; i < args.length; i++) { - classes[i] = ClassUtils.resolveClassName(args[i].getClassName(), loader); + ClassLoader loader = this.clazz.getClassLoader(); + Class[] argTypes = new Class[this.args.length]; + for (int i = 0; i < this.args.length; i++) { + argTypes[i] = ClassUtils.resolveClassName(this.args[i].getClassName(), loader); } try { - if (CONSTRUCTOR.equals(name)) { - return clazz.getDeclaredConstructor(classes); + if (CONSTRUCTOR.equals(this.name)) { + return this.clazz.getDeclaredConstructor(argTypes); } - - return clazz.getDeclaredMethod(name, classes); - } catch (NoSuchMethodException ex) { - throw new IllegalStateException("Method [" + name - + "] was discovered in the .class file but cannot be resolved in the class object", ex); + return this.clazz.getDeclaredMethod(this.name, argTypes); + } + catch (NoSuchMethodException ex) { + throw new IllegalStateException("Method [" + this.name + + "] was discovered in the .class file but cannot be resolved in the class object", ex); } } @@ -254,7 +255,8 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD lvtIndex[i] = nextIndex; if (isWideType(paramTypes[i])) { nextIndex += 2; - } else { + } + else { nextIndex++; } } diff --git a/spring-core/src/main/java/org/springframework/core/io/FileSystemResource.java b/spring-core/src/main/java/org/springframework/core/io/FileSystemResource.java index 57da655a5d..05202a3b09 100644 --- a/spring-core/src/main/java/org/springframework/core/io/FileSystemResource.java +++ b/spring-core/src/main/java/org/springframework/core/io/FileSystemResource.java @@ -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. @@ -45,7 +45,7 @@ public class FileSystemResource extends AbstractResource implements WritableReso /** - * Create a new FileSystemResource from a File handle. + * Create a new {@code FileSystemResource} from a {@link File} handle. *

Note: When building relative resources via {@link #createRelative}, * the relative path will apply at the same directory level: * e.g. new File("C:/dir1"), relative path "dir2" -> "C:/dir2"! @@ -62,7 +62,7 @@ public class FileSystemResource extends AbstractResource implements WritableReso } /** - * Create a new FileSystemResource from a file path. + * Create a new {@code FileSystemResource} from a file path. *

Note: When building relative resources via {@link #createRelative}, * it makes a difference whether the specified resource base path here * ends with a slash or not. In the case of "C:/dir1/", relative paths @@ -77,6 +77,7 @@ public class FileSystemResource extends AbstractResource implements WritableReso this.path = StringUtils.cleanPath(path); } + /** * Return the file path for this resource. */ diff --git a/spring-core/src/main/java/org/springframework/core/type/StandardMethodMetadata.java b/spring-core/src/main/java/org/springframework/core/type/StandardMethodMetadata.java index c6564c643f..8288debed4 100644 --- a/spring-core/src/main/java/org/springframework/core/type/StandardMethodMetadata.java +++ b/spring-core/src/main/java/org/springframework/core/type/StandardMethodMetadata.java @@ -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. @@ -49,9 +49,14 @@ public class StandardMethodMetadata implements MethodMetadata { } /** - * Create a new StandardMethodMetadata wrapper for the given Method. + * Create a new StandardMethodMetadata wrapper for the given Method, + * providing the option to return any nested annotations or annotation arrays in the + * form of {@link org.springframework.core.annotation.AnnotationAttributes} instead + * of actual {@link java.lang.annotation.Annotation} instances. * @param introspectedMethod the Method to introspect - * @param nestedAnnotationsAsMap + * @param nestedAnnotationsAsMap return nested annotations and annotation arrays as + * {@link org.springframework.core.annotation.AnnotationAttributes} for compatibility + * with ASM-based {@link AnnotationMetadata} implementations * @since 3.1.1 */ public StandardMethodMetadata(Method introspectedMethod, boolean nestedAnnotationsAsMap) { diff --git a/spring-core/src/main/java/org/springframework/core/type/classreading/MethodMetadataReadingVisitor.java b/spring-core/src/main/java/org/springframework/core/type/classreading/MethodMetadataReadingVisitor.java index 1155936e3d..dde3790c8e 100644 --- a/spring-core/src/main/java/org/springframework/core/type/classreading/MethodMetadataReadingVisitor.java +++ b/spring-core/src/main/java/org/springframework/core/type/classreading/MethodMetadataReadingVisitor.java @@ -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. @@ -27,7 +27,6 @@ import org.springframework.asm.SpringAsmInfo; import org.springframework.asm.Type; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.MethodMetadata; -import org.springframework.util.MultiValueMap; /** * ASM method visitor which looks for the annotations defined on the method, diff --git a/spring-core/src/main/java/org/springframework/core/type/filter/AbstractTypeHierarchyTraversingFilter.java b/spring-core/src/main/java/org/springframework/core/type/filter/AbstractTypeHierarchyTraversingFilter.java index 82362b5670..6ee0c87528 100644 --- a/spring-core/src/main/java/org/springframework/core/type/filter/AbstractTypeHierarchyTraversingFilter.java +++ b/spring-core/src/main/java/org/springframework/core/type/filter/AbstractTypeHierarchyTraversingFilter.java @@ -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,8 +19,8 @@ package org.springframework.core.type.filter; import java.io.IOException; import org.springframework.core.type.ClassMetadata; -import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.core.type.classreading.MetadataReaderFactory; /** * Type filter that is aware of traversing over hierarchy. @@ -131,7 +131,7 @@ public abstract class AbstractTypeHierarchyTraversingFilter implements TypeFilte /** * Override this to match on interface type name. */ - protected Boolean matchInterface(String interfaceNames) { + protected Boolean matchInterface(String interfaceName) { return null; } diff --git a/spring-oxm/src/main/java/org/springframework/oxm/xmlbeans/XmlBeansMarshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/xmlbeans/XmlBeansMarshaller.java index fc519c7f1e..b75d229b48 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/xmlbeans/XmlBeansMarshaller.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/xmlbeans/XmlBeansMarshaller.java @@ -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. @@ -21,10 +21,10 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; -import java.util.ArrayList; -import java.util.List; import java.lang.ref.WeakReference; import java.nio.CharBuffer; +import java.util.ArrayList; +import java.util.List; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamReader; @@ -113,10 +113,6 @@ public class XmlBeansMarshaller extends AbstractMarshaller { return this.validating; } - @Override - protected String getDefaultEncoding() { - return null; - } /** * This implementation returns true if the given class is an implementation of {@link XmlObject}. @@ -127,7 +123,7 @@ public class XmlBeansMarshaller extends AbstractMarshaller { @Override protected final void marshalDomNode(Object graph, Node node) throws XmlMappingException { - Document document = node.getNodeType() == Node.DOCUMENT_NODE ? (Document) node : node.getOwnerDocument(); + Document document = (node.getNodeType() == Node.DOCUMENT_NODE ? (Document) node : node.getOwnerDocument()); Node xmlBeansNode = ((XmlObject) graph).newDomNode(getXmlOptions()); NodeList xmlBeansChildNodes = xmlBeansNode.getChildNodes(); for (int i = 0; i < xmlBeansChildNodes.getLength(); i++) { @@ -137,29 +133,6 @@ public class XmlBeansMarshaller extends AbstractMarshaller { } } - @Override - protected final void marshalOutputStream(Object graph, OutputStream outputStream) - throws XmlMappingException, IOException { - - ((XmlObject) graph).save(outputStream, getXmlOptions()); - } - - @Override - protected final void marshalSaxHandlers(Object graph, ContentHandler contentHandler, LexicalHandler lexicalHandler) - throws XmlMappingException { - try { - ((XmlObject) graph).save(contentHandler, lexicalHandler, getXmlOptions()); - } - catch (SAXException ex) { - throw convertXmlBeansException(ex, true); - } - } - - @Override - protected final void marshalWriter(Object graph, Writer writer) throws XmlMappingException, IOException { - ((XmlObject) graph).save(writer, getXmlOptions()); - } - @Override protected final void marshalXmlEventWriter(Object graph, XMLEventWriter eventWriter) { ContentHandler contentHandler = StaxUtils.createContentHandler(eventWriter); @@ -172,6 +145,30 @@ public class XmlBeansMarshaller extends AbstractMarshaller { marshalSaxHandlers(graph, contentHandler, null); } + @Override + protected final void marshalSaxHandlers(Object graph, ContentHandler contentHandler, LexicalHandler lexicalHandler) + throws XmlMappingException { + try { + ((XmlObject) graph).save(contentHandler, lexicalHandler, getXmlOptions()); + } + catch (SAXException ex) { + throw convertXmlBeansException(ex, true); + } + } + + @Override + protected final void marshalOutputStream(Object graph, OutputStream outputStream) + throws XmlMappingException, IOException { + + ((XmlObject) graph).save(outputStream, getXmlOptions()); + } + + @Override + protected final void marshalWriter(Object graph, Writer writer) throws XmlMappingException, IOException { + ((XmlObject) graph).save(writer, getXmlOptions()); + } + + @Override protected final Object unmarshalDomNode(Node node) throws XmlMappingException { try { @@ -184,6 +181,58 @@ public class XmlBeansMarshaller extends AbstractMarshaller { } } + @Override + protected final Object unmarshalXmlEventReader(XMLEventReader eventReader) throws XmlMappingException { + XMLReader reader = StaxUtils.createXMLReader(eventReader); + try { + return unmarshalSaxReader(reader, new InputSource()); + } + catch (IOException ex) { + throw convertXmlBeansException(ex, false); + } + } + + @Override + protected final Object unmarshalXmlStreamReader(XMLStreamReader streamReader) throws XmlMappingException { + try { + XmlObject object = XmlObject.Factory.parse(streamReader, getXmlOptions()); + validate(object); + return object; + } + catch (XmlException ex) { + throw convertXmlBeansException(ex, false); + } + } + + @Override + protected final Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource) + throws XmlMappingException, IOException { + + XmlSaxHandler saxHandler = XmlObject.Factory.newXmlSaxHandler(getXmlOptions()); + xmlReader.setContentHandler(saxHandler.getContentHandler()); + try { + xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", saxHandler.getLexicalHandler()); + } + catch (SAXNotRecognizedException ex) { + // ignore + } + catch (SAXNotSupportedException ex) { + // ignore + } + try { + xmlReader.parse(inputSource); + XmlObject object = saxHandler.getObject(); + validate(object); + return object; + } + catch (SAXException ex) { + throw convertXmlBeansException(ex, false); + } + catch (XmlException ex) { + throw convertXmlBeansException(ex, false); + } + } + @Override protected final Object unmarshalInputStream(InputStream inputStream) throws XmlMappingException, IOException { try { @@ -210,57 +259,6 @@ public class XmlBeansMarshaller extends AbstractMarshaller { } } - @Override - protected final Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource) - throws XmlMappingException, IOException { - XmlSaxHandler saxHandler = XmlObject.Factory.newXmlSaxHandler(getXmlOptions()); - xmlReader.setContentHandler(saxHandler.getContentHandler()); - try { - xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", saxHandler.getLexicalHandler()); - } - catch (SAXNotRecognizedException e) { - // ignore - } - catch (SAXNotSupportedException e) { - // ignore - } - try { - xmlReader.parse(inputSource); - XmlObject object = saxHandler.getObject(); - validate(object); - return object; - } - catch (SAXException ex) { - throw convertXmlBeansException(ex, false); - } - catch (XmlException ex) { - throw convertXmlBeansException(ex, false); - } - } - - @Override - protected final Object unmarshalXmlEventReader(XMLEventReader eventReader) throws XmlMappingException { - XMLReader reader = StaxUtils.createXMLReader(eventReader); - try { - return unmarshalSaxReader(reader, new InputSource()); - } - catch (IOException ex) { - throw convertXmlBeansException(ex, false); - } - } - - @Override - protected final Object unmarshalXmlStreamReader(XMLStreamReader streamReader) throws XmlMappingException { - try { - XmlObject object = XmlObject.Factory.parse(streamReader, getXmlOptions()); - validate(object); - return object; - } - catch (XmlException ex) { - throw convertXmlBeansException(ex, false); - } - } - /** * Validate the given {@code XmlObject}. @@ -269,20 +267,27 @@ public class XmlBeansMarshaller extends AbstractMarshaller { */ protected void validate(XmlObject object) throws ValidationFailureException { if (isValidating() && object != null) { - // create a temporary xmlOptions just for validation - XmlOptions validateOptions = getXmlOptions() != null ? getXmlOptions() : new XmlOptions(); - List errorsList = new ArrayList(); + XmlOptions validateOptions = getXmlOptions(); + if (validateOptions == null) { + // Create temporary XmlOptions just for validation + validateOptions = new XmlOptions(); + } + List errorsList = new ArrayList(); validateOptions.setErrorListener(errorsList); if (!object.validate(validateOptions)) { - StringBuilder builder = new StringBuilder("Could not validate XmlObject :"); - for (Object anErrorsList : errorsList) { - XmlError xmlError = (XmlError) anErrorsList; - if (xmlError instanceof XmlValidationError) { - builder.append(xmlError.toString()); + StringBuilder sb = new StringBuilder("Failed to validate XmlObject: "); + boolean first = true; + for (XmlError error : errorsList) { + if (error instanceof XmlValidationError) { + if (!first) { + sb.append("; "); + } + sb.append(error.toString()); + first = false; } } throw new ValidationFailureException("XMLBeans validation failure", - new XmlException(builder.toString(), null, errorsList)); + new XmlException(sb.toString(), null, errorsList)); } } } @@ -299,7 +304,7 @@ public class XmlBeansMarshaller extends AbstractMarshaller { */ protected XmlMappingException convertXmlBeansException(Exception ex, boolean marshalling) { if (ex instanceof XMLStreamValidationException) { - return new ValidationFailureException("XmlBeans validation exception", ex); + return new ValidationFailureException("XMLBeans validation exception", ex); } else if (ex instanceof XmlException || ex instanceof SAXException) { if (marshalling) { @@ -315,14 +320,12 @@ public class XmlBeansMarshaller extends AbstractMarshaller { } } - /** - * See SPR-7034 - */ + private static class NonClosingInputStream extends InputStream { private final WeakReference in; - private NonClosingInputStream(InputStream in) { + public NonClosingInputStream(InputStream in) { this.in = new WeakReference(in); } @@ -333,31 +336,31 @@ public class XmlBeansMarshaller extends AbstractMarshaller { @Override public int read() throws IOException { InputStream in = getInputStream(); - return in != null ? in.read() : -1; + return (in != null ? in.read() : -1); } @Override public int read(byte[] b) throws IOException { InputStream in = getInputStream(); - return in != null ? in.read(b) : -1; + return (in != null ? in.read(b) : -1); } @Override public int read(byte[] b, int off, int len) throws IOException { InputStream in = getInputStream(); - return in != null ? in.read(b, off, len) : -1; + return (in != null ? in.read(b, off, len) : -1); } @Override public long skip(long n) throws IOException { InputStream in = getInputStream(); - return in != null ? in.skip(n) : 0; + return (in != null ? in.skip(n) : 0); } @Override public boolean markSupported() { InputStream in = getInputStream(); - return in != null && in.markSupported(); + return (in != null && in.markSupported()); } @Override @@ -379,23 +382,24 @@ public class XmlBeansMarshaller extends AbstractMarshaller { @Override public int available() throws IOException { InputStream in = getInputStream(); - return in != null ? in.available() : 0; + return (in != null ? in.available() : 0); } @Override public void close() throws IOException { InputStream in = getInputStream(); - if(in != null) { - this.in.clear(); + if (in != null) { + this.in.clear(); } } } + private static class NonClosingReader extends Reader { private final WeakReference reader; - private NonClosingReader(Reader reader) { + public NonClosingReader(Reader reader) { this.reader = new WeakReference(reader); } @@ -406,43 +410,43 @@ public class XmlBeansMarshaller extends AbstractMarshaller { @Override public int read(CharBuffer target) throws IOException { Reader rdr = getReader(); - return rdr != null ? rdr.read(target) : -1; + return (rdr != null ? rdr.read(target) : -1); } @Override public int read() throws IOException { Reader rdr = getReader(); - return rdr != null ? rdr.read() : -1; + return (rdr != null ? rdr.read() : -1); } @Override public int read(char[] cbuf) throws IOException { Reader rdr = getReader(); - return rdr != null ? rdr.read(cbuf) : -1; + return (rdr != null ? rdr.read(cbuf) : -1); } @Override public int read(char[] cbuf, int off, int len) throws IOException { Reader rdr = getReader(); - return rdr != null ? rdr.read(cbuf, off, len) : -1; + return (rdr != null ? rdr.read(cbuf, off, len) : -1); } @Override public long skip(long n) throws IOException { Reader rdr = getReader(); - return rdr != null ? rdr.skip(n) : 0; + return (rdr != null ? rdr.skip(n) : 0); } @Override public boolean ready() throws IOException { Reader rdr = getReader(); - return rdr != null && rdr.ready(); + return (rdr != null && rdr.ready()); } @Override public boolean markSupported() { Reader rdr = getReader(); - return rdr != null && rdr.markSupported(); + return (rdr != null && rdr.markSupported()); } @Override @@ -468,7 +472,6 @@ public class XmlBeansMarshaller extends AbstractMarshaller { this.reader.clear(); } } - } } diff --git a/spring-web/src/main/java/org/springframework/web/filter/OncePerRequestFilter.java b/spring-web/src/main/java/org/springframework/web/filter/OncePerRequestFilter.java index d422184207..39fbea5073 100644 --- a/spring-web/src/main/java/org/springframework/web/filter/OncePerRequestFilter.java +++ b/spring-web/src/main/java/org/springframework/web/filter/OncePerRequestFilter.java @@ -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. @@ -17,7 +17,6 @@ package org.springframework.web.filter; import java.io.IOException; - import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; @@ -35,25 +34,25 @@ import org.springframework.web.util.WebUtils; * method with HttpServletRequest and HttpServletResponse arguments. * *

As of Servlet 3.0, a filter may be invoked as part of a - * {@link javax.servlet.DispatcherType.REQUEST REQUEST} or - * {@link javax.servlet.DispatcherType.ASYNC ASYNC} dispatches that occur in + * {@link javax.servlet.DispatcherType#REQUEST REQUEST} or + * {@link javax.servlet.DispatcherType#ASYNC ASYNC} dispatches that occur in * separate threads. A filter can be configured in {@code web.xml} whether it * should be involved in async dispatches. However, in some cases servlet * containers assume different default configuration. Therefore sub-classes can * override the method {@link #shouldNotFilterAsyncDispatch()} to declare - * statically if they shouuld indeed be invoked, once, during both types + * statically if they should indeed be invoked, once, during both types * of dispatches in order to provide thread initialization, logging, security, * and so on. This mechanism complements and does not replace the need to * configure a filter in {@code web.xml} with dispatcher types. * - *

Sub-classes may use {@link #isAsyncDispatch(HttpServletRequest)} to - * determine when a filter is invoked as part of an async dispatch, and - * use {@link #isAsyncStarted(HttpServletRequest)} to determine when the - * request has been placed in async mode and therefore the current dispatch - * won't be the last one. + *

Subclasses may use {@link #isAsyncDispatch(HttpServletRequest)} to + * determine when a filter is invoked as part of an async dispatch, and use + * {@link #isAsyncStarted(HttpServletRequest)} to determine when the request + * has been placed in async mode and therefore the current dispatch won't be + * the last one for the given request. * *

Yet another dispatch type that also occurs in its own thread is - * {@link javax.servlet.DispatcherType.ERROR ERROR}. Sub-classes can override + * {@link javax.servlet.DispatcherType#ERROR ERROR}. Subclasses can override * {@link #shouldNotFilterErrorDispatch()} if they wish to declare statically * if they should be invoked once during error dispatches. * @@ -128,7 +127,6 @@ public abstract class OncePerRequestFilter extends GenericFilterBean { * in Servlet 3.0 means a filter can be invoked in more than one thread over * the course of a single request. This method returns {@code true} if the * filter is currently executing within an asynchronous dispatch. - * * @param request the current request * @see WebAsyncManager#hasConcurrentResult() */ @@ -139,7 +137,6 @@ public abstract class OncePerRequestFilter extends GenericFilterBean { /** * Whether request processing is in asynchronous mode meaning that the * response will not be committed after the current thread is exited. - * * @param request the current request * @see WebAsyncManager#isConcurrentHandlingStarted() */ @@ -150,7 +147,7 @@ public abstract class OncePerRequestFilter extends GenericFilterBean { /** * Return the name of the request attribute that identifies that a request * is already filtered. - *

Default implementation takes the configured name of the concrete filter + *

The default implementation takes the configured name of the concrete filter * instance and appends ".FILTERED". If the filter is not fully initialized, * it falls back to its class name. * @see #getFilterName @@ -187,7 +184,6 @@ public abstract class OncePerRequestFilter extends GenericFilterBean { * types via {@code web.xml} or in Java through the {@code ServletContext}, * servlet containers may enforce different defaults with regards to * dispatcher types. This flag enforces the design intent of the filter. - * *

The default return value is "true", which means the filter will not be * invoked during subsequent async dispatches. If "false", the filter will * be invoked during async dispatches with the same guarantees of being diff --git a/spring-web/src/main/java/org/springframework/web/filter/ShallowEtagHeaderFilter.java b/spring-web/src/main/java/org/springframework/web/filter/ShallowEtagHeaderFilter.java index f68e7d6c66..4ec3870167 100644 --- a/spring-web/src/main/java/org/springframework/web/filter/ShallowEtagHeaderFilter.java +++ b/spring-web/src/main/java/org/springframework/web/filter/ShallowEtagHeaderFilter.java @@ -67,14 +67,15 @@ public class ShallowEtagHeaderFilter extends OncePerRequestFilter { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + HttpServletResponse responseToUse = response; if (!isAsyncDispatch(request)) { - response = new ShallowEtagResponseWrapper(response); + responseToUse = new ShallowEtagResponseWrapper(response); } - filterChain.doFilter(request, response); + filterChain.doFilter(request, responseToUse); if (!isAsyncStarted(request)) { - updateResponse(request, response); + updateResponse(request, responseToUse); } } @@ -83,34 +84,33 @@ public class ShallowEtagHeaderFilter extends OncePerRequestFilter { WebUtils.getNativeResponse(response, ShallowEtagResponseWrapper.class); Assert.notNull(responseWrapper, "ShallowEtagResponseWrapper not found"); - response = (HttpServletResponse) responseWrapper.getResponse(); - byte[] body = responseWrapper.toByteArray(); + HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse(); int statusCode = responseWrapper.getStatusCode(); + byte[] body = responseWrapper.toByteArray(); if (isEligibleForEtag(request, responseWrapper, statusCode, body)) { String responseETag = generateETagHeaderValue(body); - response.setHeader(HEADER_ETAG, responseETag); - + rawResponse.setHeader(HEADER_ETAG, responseETag); String requestETag = request.getHeader(HEADER_IF_NONE_MATCH); if (responseETag.equals(requestETag)) { if (logger.isTraceEnabled()) { logger.trace("ETag [" + responseETag + "] equal to If-None-Match, sending 304"); } - response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); + rawResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { if (logger.isTraceEnabled()) { logger.trace("ETag [" + responseETag + "] not equal to If-None-Match [" + requestETag + "], sending normal response"); } - copyBodyToResponse(body, response); + copyBodyToResponse(body, rawResponse); } } else { if (logger.isTraceEnabled()) { logger.trace("Response with status code [" + statusCode + "] not eligible for ETag"); } - copyBodyToResponse(body, response); + copyBodyToResponse(body, rawResponse); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java index 48cff20fe5..83c564bc23 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java @@ -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,7 +22,6 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -41,8 +40,8 @@ import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.HandlerMapping; /** - * Extends {@link AbstractMessageConverterMethodArgumentResolver} with the ability to handle method return - * values by writing to the response with {@link HttpMessageConverter}s. + * Extends {@link AbstractMessageConverterMethodArgumentResolver} with the ability to handle + * method return values by writing to the response with {@link HttpMessageConverter}s. * * @author Arjen Poutsma * @author Rossen Stoyanchev @@ -55,6 +54,7 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe private final ContentNegotiationManager contentNegotiationManager; + protected AbstractMessageConverterMethodProcessor(List> messageConverters) { this(messageConverters, null); } @@ -63,12 +63,12 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe ContentNegotiationManager manager) { super(messageConverters); - this.contentNegotiationManager = (manager != null) ? manager : new ContentNegotiationManager(); + this.contentNegotiationManager = (manager != null ? manager : new ContentNegotiationManager()); } + /** * Creates a new {@link HttpOutputMessage} from the given {@link NativeWebRequest}. - * * @param webRequest the web request to create an output message from * @return the output message */ @@ -81,10 +81,9 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe * Writes the given return value to the given web request. Delegates to * {@link #writeWithMessageConverters(Object, MethodParameter, ServletServerHttpRequest, ServletServerHttpResponse)} */ - protected void writeWithMessageConverters(T returnValue, - MethodParameter returnType, - NativeWebRequest webRequest) + protected void writeWithMessageConverters(T returnValue, MethodParameter returnType, NativeWebRequest webRequest) throws IOException, HttpMediaTypeNotAcceptableException { + ServletServerHttpRequest inputMessage = createInputMessage(webRequest); ServletServerHttpResponse outputMessage = createOutputMessage(webRequest); writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage); @@ -92,7 +91,6 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe /** * Writes the given return type to the given output message. - * * @param returnValue the value to write to the output message * @param returnType the type of the value * @param inputMessage the input messages. Used to inspect the {@code Accept} header. @@ -102,23 +100,20 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe * the request cannot be met by the message converters */ @SuppressWarnings("unchecked") - protected void writeWithMessageConverters(T returnValue, - MethodParameter returnType, - ServletServerHttpRequest inputMessage, - ServletServerHttpResponse outputMessage) + protected void writeWithMessageConverters(T returnValue, MethodParameter returnType, + ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) throws IOException, HttpMediaTypeNotAcceptableException { Class returnValueClass = returnValue.getClass(); - HttpServletRequest servletRequest = inputMessage.getServletRequest(); List requestedMediaTypes = getAcceptableMediaTypes(servletRequest); List producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClass); Set compatibleMediaTypes = new LinkedHashSet(); - for (MediaType r : requestedMediaTypes) { - for (MediaType p : producibleMediaTypes) { - if (r.isCompatibleWith(p)) { - compatibleMediaTypes.add(getMostSpecificMediaType(r, p)); + for (MediaType requestedType : requestedMediaTypes) { + for (MediaType producibleType : producibleMediaTypes) { + if (requestedType.isCompatibleWith(producibleType)) { + compatibleMediaTypes.add(getMostSpecificMediaType(requestedType, producibleType)); } } } @@ -143,7 +138,7 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe if (selectedMediaType != null) { selectedMediaType = selectedMediaType.removeQualityValue(); - for (HttpMessageConverter messageConverter : messageConverters) { + for (HttpMessageConverter messageConverter : this.messageConverters) { if (messageConverter.canWrite(returnValueClass, selectedMediaType)) { ((HttpMessageConverter) messageConverter).write(returnValue, selectedMediaType, outputMessage); if (logger.isDebugEnabled()) { @@ -154,15 +149,15 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe } } } - throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes); + throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes); } /** * Returns the media types that can be produced: *

    - *
  • The producible media types specified in the request mappings, or - *
  • Media types of configured converters that can write the specific return value, or - *
  • {@link MediaType#ALL} + *
  • The producible media types specified in the request mappings, or + *
  • Media types of configured converters that can write the specific return value, or + *
  • {@link MediaType#ALL} *
*/ @SuppressWarnings("unchecked") @@ -171,9 +166,9 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe if (!CollectionUtils.isEmpty(mediaTypes)) { return new ArrayList(mediaTypes); } - else if (!allSupportedMediaTypes.isEmpty()) { + else if (!this.allSupportedMediaTypes.isEmpty()) { List result = new ArrayList(); - for (HttpMessageConverter converter : messageConverters) { + for (HttpMessageConverter converter : this.messageConverters) { if (converter.canWrite(returnValueClass, null)) { result.addAll(converter.getSupportedMediaTypes()); } @@ -187,7 +182,7 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe private List getAcceptableMediaTypes(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException { List mediaTypes = this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request)); - return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes; + return (mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes); } /** @@ -195,8 +190,8 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe * with the q-value of the former. */ private MediaType getMostSpecificMediaType(MediaType acceptType, MediaType produceType) { - produceType = produceType.copyQualityValue(acceptType); - return MediaType.SPECIFICITY_COMPARATOR.compare(acceptType, produceType) <= 0 ? acceptType : produceType; + MediaType produceTypeToUse = produceType.copyQualityValue(acceptType); + return (MediaType.SPECIFICITY_COMPARATOR.compare(acceptType, produceTypeToUse) <= 0 ? acceptType : produceTypeToUse); } }