Convert CRLF (dos) to LF (unix)

Prior to this change, roughly 5% (~300 out of 6000+) of files under the
source tree had CRLF line endings as opposed to the majority which have
LF endings.

This change normalizes these files to LF for consistency going forward.

Command used:

$ git ls-files | xargs file | grep CRLF | cut -d":" -f1 | xargs dos2unix

Issue: SPR-5608
This commit is contained in:
Chris Beams
2011-12-21 14:40:03 +01:00
parent 096de373b4
commit ae72cf2f50
292 changed files with 30756 additions and 30756 deletions

View File

@@ -1,96 +1,96 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.springframework.util.Assert;
/**
* Comparator capable of sorting exceptions based on their depth from the thrown exception type.
*
* @author Juergen Hoeller
* @author Arjen Poutsma
* @since 3.0.3
*/
public class ExceptionDepthComparator implements Comparator<Class<? extends Throwable>> {
private final Class<? extends Throwable> targetException;
/**
* Create a new ExceptionDepthComparator for the given exception.
* @param exception the target exception to compare to when sorting by depth
*/
public ExceptionDepthComparator(Throwable exception) {
Assert.notNull(exception, "Target exception must not be null");
this.targetException = exception.getClass();
}
/**
* Create a new ExceptionDepthComparator for the given exception type.
* @param exceptionType the target exception type to compare to when sorting by depth
*/
public ExceptionDepthComparator(Class<? extends Throwable> exceptionType) {
Assert.notNull(exceptionType, "Target exception type must not be null");
this.targetException = exceptionType;
}
public int compare(Class<? extends Throwable> o1, Class<? extends Throwable> o2) {
int depth1 = getDepth(o1, this.targetException, 0);
int depth2 = getDepth(o2, this.targetException, 0);
return (depth1 - depth2);
}
private int getDepth(Class declaredException, Class exceptionToMatch, int depth) {
if (declaredException.equals(exceptionToMatch)) {
// Found it!
return depth;
}
// If we've gone as far as we can go and haven't found it...
if (Throwable.class.equals(exceptionToMatch)) {
return Integer.MAX_VALUE;
}
return getDepth(declaredException, exceptionToMatch.getSuperclass(), depth + 1);
}
/**
* Obtain the closest match from the given exception types for the given target exception.
* @param exceptionTypes the collection of exception types
* @param targetException the target exception to find a match for
* @return the closest matching exception type from the given collection
*/
public static Class<? extends Throwable> findClosestMatch(
Collection<Class<? extends Throwable>> exceptionTypes, Throwable targetException) {
Assert.notEmpty(exceptionTypes, "Exception types must not be empty");
if (exceptionTypes.size() == 1) {
return exceptionTypes.iterator().next();
}
List<Class<? extends Throwable>> handledExceptions =
new ArrayList<Class<? extends Throwable>>(exceptionTypes);
Collections.sort(handledExceptions, new ExceptionDepthComparator(targetException));
return handledExceptions.get(0);
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.springframework.util.Assert;
/**
* Comparator capable of sorting exceptions based on their depth from the thrown exception type.
*
* @author Juergen Hoeller
* @author Arjen Poutsma
* @since 3.0.3
*/
public class ExceptionDepthComparator implements Comparator<Class<? extends Throwable>> {
private final Class<? extends Throwable> targetException;
/**
* Create a new ExceptionDepthComparator for the given exception.
* @param exception the target exception to compare to when sorting by depth
*/
public ExceptionDepthComparator(Throwable exception) {
Assert.notNull(exception, "Target exception must not be null");
this.targetException = exception.getClass();
}
/**
* Create a new ExceptionDepthComparator for the given exception type.
* @param exceptionType the target exception type to compare to when sorting by depth
*/
public ExceptionDepthComparator(Class<? extends Throwable> exceptionType) {
Assert.notNull(exceptionType, "Target exception type must not be null");
this.targetException = exceptionType;
}
public int compare(Class<? extends Throwable> o1, Class<? extends Throwable> o2) {
int depth1 = getDepth(o1, this.targetException, 0);
int depth2 = getDepth(o2, this.targetException, 0);
return (depth1 - depth2);
}
private int getDepth(Class declaredException, Class exceptionToMatch, int depth) {
if (declaredException.equals(exceptionToMatch)) {
// Found it!
return depth;
}
// If we've gone as far as we can go and haven't found it...
if (Throwable.class.equals(exceptionToMatch)) {
return Integer.MAX_VALUE;
}
return getDepth(declaredException, exceptionToMatch.getSuperclass(), depth + 1);
}
/**
* Obtain the closest match from the given exception types for the given target exception.
* @param exceptionTypes the collection of exception types
* @param targetException the target exception to find a match for
* @return the closest matching exception type from the given collection
*/
public static Class<? extends Throwable> findClosestMatch(
Collection<Class<? extends Throwable>> exceptionTypes, Throwable targetException) {
Assert.notEmpty(exceptionTypes, "Exception types must not be empty");
if (exceptionTypes.size() == 1) {
return exceptionTypes.iterator().next();
}
List<Class<? extends Throwable>> handledExceptions =
new ArrayList<Class<? extends Throwable>>(exceptionTypes);
Collections.sort(handledExceptions, new ExceptionDepthComparator(targetException));
return handledExceptions.get(0);
}
}

View File

@@ -1,72 +1,72 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.convert.support;
import java.beans.PropertyEditorSupport;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.util.Assert;
/**
* Adapter that exposes a {@link java.beans.PropertyEditor} for any given
* {@link org.springframework.core.convert.ConversionService} and specific target type.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class ConvertingPropertyEditorAdapter extends PropertyEditorSupport {
private final ConversionService conversionService;
private final TypeDescriptor targetDescriptor;
private final boolean canConvertToString;
/**
* Create a new ConvertingPropertyEditorAdapter for a given
* {@link org.springframework.core.convert.ConversionService}
* and the given target type.
* @param conversionService the ConversionService to delegate to
* @param targetDescriptor the target type to convert to
*/
public ConvertingPropertyEditorAdapter(ConversionService conversionService, TypeDescriptor targetDescriptor) {
Assert.notNull(conversionService, "ConversionService must not be null");
Assert.notNull(targetDescriptor, "TypeDescriptor must not be null");
this.conversionService = conversionService;
this.targetDescriptor = targetDescriptor;
this.canConvertToString = conversionService.canConvert(this.targetDescriptor, TypeDescriptor.valueOf(String.class));
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(this.conversionService.convert(text, TypeDescriptor.valueOf(String.class), this.targetDescriptor));
}
@Override
public String getAsText() {
if (this.canConvertToString) {
return (String) this.conversionService.convert(getValue(), this.targetDescriptor, TypeDescriptor.valueOf(String.class));
}
else {
return null;
}
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.convert.support;
import java.beans.PropertyEditorSupport;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.util.Assert;
/**
* Adapter that exposes a {@link java.beans.PropertyEditor} for any given
* {@link org.springframework.core.convert.ConversionService} and specific target type.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class ConvertingPropertyEditorAdapter extends PropertyEditorSupport {
private final ConversionService conversionService;
private final TypeDescriptor targetDescriptor;
private final boolean canConvertToString;
/**
* Create a new ConvertingPropertyEditorAdapter for a given
* {@link org.springframework.core.convert.ConversionService}
* and the given target type.
* @param conversionService the ConversionService to delegate to
* @param targetDescriptor the target type to convert to
*/
public ConvertingPropertyEditorAdapter(ConversionService conversionService, TypeDescriptor targetDescriptor) {
Assert.notNull(conversionService, "ConversionService must not be null");
Assert.notNull(targetDescriptor, "TypeDescriptor must not be null");
this.conversionService = conversionService;
this.targetDescriptor = targetDescriptor;
this.canConvertToString = conversionService.canConvert(this.targetDescriptor, TypeDescriptor.valueOf(String.class));
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(this.conversionService.convert(text, TypeDescriptor.valueOf(String.class), this.targetDescriptor));
}
@Override
public String getAsText() {
if (this.canConvertToString) {
return (String) this.conversionService.convert(getValue(), this.targetDescriptor, TypeDescriptor.valueOf(String.class));
}
else {
return null;
}
}
}

View File

@@ -1,201 +1,201 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import org.springframework.util.ResourceUtils;
/**
* Abstract base class for resources which resolve URLs into File references,
* such as {@link UrlResource} or {@link ClassPathResource}.
*
* <p>Detects the "file" protocol as well as the JBoss "vfs" protocol in URLs,
* resolving file system references accordingly.
*
* @author Juergen Hoeller
* @since 3.0
*/
public abstract class AbstractFileResolvingResource extends AbstractResource {
/**
* This implementation returns a File reference for the underlying class path
* resource, provided that it refers to a file in the file system.
* @see org.springframework.util.ResourceUtils#getFile(java.net.URL, String)
*/
@Override
public File getFile() throws IOException {
URL url = getURL();
if (url.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(url).getFile();
}
return ResourceUtils.getFile(url, getDescription());
}
/**
* This implementation determines the underlying File
* (or jar file, in case of a resource in a jar/zip).
*/
@Override
protected File getFileForLastModifiedCheck() throws IOException {
URL url = getURL();
if (ResourceUtils.isJarURL(url)) {
URL actualUrl = ResourceUtils.extractJarFileURL(url);
if (actualUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(actualUrl).getFile();
}
return ResourceUtils.getFile(actualUrl, "Jar URL");
}
else {
return getFile();
}
}
/**
* This implementation returns a File reference for the underlying class path
* resource, provided that it refers to a file in the file system.
* @see org.springframework.util.ResourceUtils#getFile(java.net.URI, String)
*/
protected File getFile(URI uri) throws IOException {
if (uri.getScheme().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(uri).getFile();
}
return ResourceUtils.getFile(uri, getDescription());
}
@Override
public boolean exists() {
try {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
return getFile().exists();
}
else {
// Try a URL connection content-length header...
URLConnection con = url.openConnection();
con.setUseCaches(false);
HttpURLConnection httpCon =
(con instanceof HttpURLConnection ? (HttpURLConnection) con : null);
if (httpCon != null) {
httpCon.setRequestMethod("HEAD");
int code = httpCon.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
return true;
}
else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
}
if (con.getContentLength() >= 0) {
return true;
}
if (httpCon != null) {
// no HTTP OK status, and no content-length header: give up
httpCon.disconnect();
return false;
}
else {
// Fall back to stream existence: can we open the stream?
InputStream is = getInputStream();
is.close();
return true;
}
}
}
catch (IOException ex) {
return false;
}
}
@Override
public boolean isReadable() {
try {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
File file = getFile();
return (file.canRead() && !file.isDirectory());
}
else {
return true;
}
}
catch (IOException ex) {
return false;
}
}
@Override
public long contentLength() throws IOException {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
return super.contentLength();
}
else {
// Try a URL connection content-length header...
URLConnection con = url.openConnection();
con.setUseCaches(false);
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).setRequestMethod("HEAD");
}
return con.getContentLength();
}
}
@Override
public long lastModified() throws IOException {
URL url = getURL();
if (ResourceUtils.isFileURL(url) || ResourceUtils.isJarURL(url)) {
// Proceed with file system resolution...
return super.lastModified();
}
else {
// Try a URL connection last-modified header...
URLConnection con = url.openConnection();
con.setUseCaches(false);
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).setRequestMethod("HEAD");
}
return con.getLastModified();
}
}
/**
* Inner delegate class, avoiding a hard JBoss VFS API dependency at runtime.
*/
private static class VfsResourceDelegate {
public static Resource getResource(URL url) throws IOException {
return new VfsResource(VfsUtils.getRoot(url));
}
public static Resource getResource(URI uri) throws IOException {
return new VfsResource(VfsUtils.getRoot(uri));
}
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import org.springframework.util.ResourceUtils;
/**
* Abstract base class for resources which resolve URLs into File references,
* such as {@link UrlResource} or {@link ClassPathResource}.
*
* <p>Detects the "file" protocol as well as the JBoss "vfs" protocol in URLs,
* resolving file system references accordingly.
*
* @author Juergen Hoeller
* @since 3.0
*/
public abstract class AbstractFileResolvingResource extends AbstractResource {
/**
* This implementation returns a File reference for the underlying class path
* resource, provided that it refers to a file in the file system.
* @see org.springframework.util.ResourceUtils#getFile(java.net.URL, String)
*/
@Override
public File getFile() throws IOException {
URL url = getURL();
if (url.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(url).getFile();
}
return ResourceUtils.getFile(url, getDescription());
}
/**
* This implementation determines the underlying File
* (or jar file, in case of a resource in a jar/zip).
*/
@Override
protected File getFileForLastModifiedCheck() throws IOException {
URL url = getURL();
if (ResourceUtils.isJarURL(url)) {
URL actualUrl = ResourceUtils.extractJarFileURL(url);
if (actualUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(actualUrl).getFile();
}
return ResourceUtils.getFile(actualUrl, "Jar URL");
}
else {
return getFile();
}
}
/**
* This implementation returns a File reference for the underlying class path
* resource, provided that it refers to a file in the file system.
* @see org.springframework.util.ResourceUtils#getFile(java.net.URI, String)
*/
protected File getFile(URI uri) throws IOException {
if (uri.getScheme().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(uri).getFile();
}
return ResourceUtils.getFile(uri, getDescription());
}
@Override
public boolean exists() {
try {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
return getFile().exists();
}
else {
// Try a URL connection content-length header...
URLConnection con = url.openConnection();
con.setUseCaches(false);
HttpURLConnection httpCon =
(con instanceof HttpURLConnection ? (HttpURLConnection) con : null);
if (httpCon != null) {
httpCon.setRequestMethod("HEAD");
int code = httpCon.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
return true;
}
else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
}
if (con.getContentLength() >= 0) {
return true;
}
if (httpCon != null) {
// no HTTP OK status, and no content-length header: give up
httpCon.disconnect();
return false;
}
else {
// Fall back to stream existence: can we open the stream?
InputStream is = getInputStream();
is.close();
return true;
}
}
}
catch (IOException ex) {
return false;
}
}
@Override
public boolean isReadable() {
try {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
File file = getFile();
return (file.canRead() && !file.isDirectory());
}
else {
return true;
}
}
catch (IOException ex) {
return false;
}
}
@Override
public long contentLength() throws IOException {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
return super.contentLength();
}
else {
// Try a URL connection content-length header...
URLConnection con = url.openConnection();
con.setUseCaches(false);
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).setRequestMethod("HEAD");
}
return con.getContentLength();
}
}
@Override
public long lastModified() throws IOException {
URL url = getURL();
if (ResourceUtils.isFileURL(url) || ResourceUtils.isJarURL(url)) {
// Proceed with file system resolution...
return super.lastModified();
}
else {
// Try a URL connection last-modified header...
URLConnection con = url.openConnection();
con.setUseCaches(false);
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).setRequestMethod("HEAD");
}
return con.getLastModified();
}
}
/**
* Inner delegate class, avoiding a hard JBoss VFS API dependency at runtime.
*/
private static class VfsResourceDelegate {
public static Resource getResource(URL url) throws IOException {
return new VfsResource(VfsUtils.getRoot(url));
}
public static Resource getResource(URI uri) throws IOException {
return new VfsResource(VfsUtils.getRoot(uri));
}
}
}

View File

@@ -1,75 +1,75 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* {@link ResourceLoader} implementation that interprets plain resource paths
* as relative to a given <code>java.lang.Class</code>.
*
* @author Juergen Hoeller
* @since 3.0
* @see java.lang.Class#getResource(String)
* @see ClassPathResource#ClassPathResource(String, Class)
*/
public class ClassRelativeResourceLoader extends DefaultResourceLoader {
private final Class clazz;
/**
* Create a new ClassRelativeResourceLoader for the given class.
* @param clazz the class to load resources through
*/
public ClassRelativeResourceLoader(Class clazz) {
Assert.notNull(clazz, "Class must not be null");
this.clazz = clazz;
setClassLoader(clazz.getClassLoader());
}
protected Resource getResourceByPath(String path) {
return new ClassRelativeContextResource(path, this.clazz);
}
/**
* ClassPathResource that explicitly expresses a context-relative path
* through implementing the ContextResource interface.
*/
private static class ClassRelativeContextResource extends ClassPathResource implements ContextResource {
private final Class clazz;
public ClassRelativeContextResource(String path, Class clazz) {
super(path, clazz);
this.clazz = clazz;
}
public String getPathWithinContext() {
return getPath();
}
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
return new ClassRelativeContextResource(pathToUse, this.clazz);
}
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* {@link ResourceLoader} implementation that interprets plain resource paths
* as relative to a given <code>java.lang.Class</code>.
*
* @author Juergen Hoeller
* @since 3.0
* @see java.lang.Class#getResource(String)
* @see ClassPathResource#ClassPathResource(String, Class)
*/
public class ClassRelativeResourceLoader extends DefaultResourceLoader {
private final Class clazz;
/**
* Create a new ClassRelativeResourceLoader for the given class.
* @param clazz the class to load resources through
*/
public ClassRelativeResourceLoader(Class clazz) {
Assert.notNull(clazz, "Class must not be null");
this.clazz = clazz;
setClassLoader(clazz.getClassLoader());
}
protected Resource getResourceByPath(String path) {
return new ClassRelativeContextResource(path, this.clazz);
}
/**
* ClassPathResource that explicitly expresses a context-relative path
* through implementing the ContextResource interface.
*/
private static class ClassRelativeContextResource extends ClassPathResource implements ContextResource {
private final Class clazz;
public ClassRelativeContextResource(String path, Class clazz) {
super(path, clazz);
this.clazz = clazz;
}
public String getPathWithinContext() {
return getPath();
}
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
return new ClassRelativeContextResource(pathToUse, this.clazz);
}
}
}

View File

@@ -1,253 +1,253 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.NestedIOException;
import org.springframework.util.ReflectionUtils;
/**
* Utility for detecting the JBoss VFS version available in the classpath.
* JBoss AS 5+ uses VFS 2.x (package <code>org.jboss.virtual</code>) while
* JBoss AS 6+ uses VFS 3.x (package <code>org.jboss.vfs</code>).
*
* <p>Thanks go to Marius Bogoevici for the initial patch.
*
* <b>Note:</b> This is an internal class and should not be used outside the framework.
*
* @author Costin Leau
* @since 3.0.3
*/
public abstract class VfsUtils {
private static final Log logger = LogFactory.getLog(VfsUtils.class);
private static final String VFS2_PKG = "org.jboss.virtual.";
private static final String VFS3_PKG = "org.jboss.vfs.";
private static final String VFS_NAME = "VFS";
private static enum VFS_VER { V2, V3 }
private static VFS_VER version;
private static Method VFS_METHOD_GET_ROOT_URL = null;
private static Method VFS_METHOD_GET_ROOT_URI = null;
private static Method VIRTUAL_FILE_METHOD_EXISTS = null;
private static Method VIRTUAL_FILE_METHOD_GET_SIZE;
private static Method VIRTUAL_FILE_METHOD_GET_LAST_MODIFIED;
private static Method VIRTUAL_FILE_METHOD_GET_CHILD;
private static Method VIRTUAL_FILE_METHOD_GET_INPUT_STREAM;
private static Method VIRTUAL_FILE_METHOD_TO_URL;
private static Method VIRTUAL_FILE_METHOD_TO_URI;
private static Method VIRTUAL_FILE_METHOD_GET_NAME;
private static Method VIRTUAL_FILE_METHOD_GET_PATH_NAME;
protected static Class<?> VIRTUAL_FILE_VISITOR_INTERFACE;
protected static Method VIRTUAL_FILE_METHOD_VISIT;
private static Method VFS_UTILS_METHOD_IS_NESTED_FILE = null;
private static Method VFS_UTILS_METHOD_GET_COMPATIBLE_URI = null;
private static Field VISITOR_ATTRIBUTES_FIELD_RECURSE = null;
private static Method GET_PHYSICAL_FILE = null;
static {
ClassLoader loader = VfsUtils.class.getClassLoader();
String pkg;
Class<?> vfsClass;
// check for JBoss 6
try {
vfsClass = loader.loadClass(VFS3_PKG + VFS_NAME);
version = VFS_VER.V3;
pkg = VFS3_PKG;
if (logger.isDebugEnabled()) {
logger.debug("JBoss VFS packages for JBoss AS 6 found");
}
}
catch (ClassNotFoundException ex) {
// fallback to JBoss 5
if (logger.isDebugEnabled())
logger.debug("JBoss VFS packages for JBoss AS 6 not found; falling back to JBoss AS 5 packages");
try {
vfsClass = loader.loadClass(VFS2_PKG + VFS_NAME);
version = VFS_VER.V2;
pkg = VFS2_PKG;
if (logger.isDebugEnabled())
logger.debug("JBoss VFS packages for JBoss AS 5 found");
} catch (ClassNotFoundException ex1) {
logger.error("JBoss VFS packages (for both JBoss AS 5 and 6) were not found - JBoss VFS support disabled");
throw new IllegalStateException("Cannot detect JBoss VFS packages", ex1);
}
}
// cache reflective information
try {
String methodName = (VFS_VER.V3.equals(version) ? "getChild" : "getRoot");
VFS_METHOD_GET_ROOT_URL = ReflectionUtils.findMethod(vfsClass, methodName, URL.class);
VFS_METHOD_GET_ROOT_URI = ReflectionUtils.findMethod(vfsClass, methodName, URI.class);
Class<?> virtualFile = loader.loadClass(pkg + "VirtualFile");
VIRTUAL_FILE_METHOD_EXISTS = ReflectionUtils.findMethod(virtualFile, "exists");
VIRTUAL_FILE_METHOD_GET_SIZE = ReflectionUtils.findMethod(virtualFile, "getSize");
VIRTUAL_FILE_METHOD_GET_INPUT_STREAM = ReflectionUtils.findMethod(virtualFile, "openStream");
VIRTUAL_FILE_METHOD_GET_LAST_MODIFIED = ReflectionUtils.findMethod(virtualFile, "getLastModified");
VIRTUAL_FILE_METHOD_TO_URI = ReflectionUtils.findMethod(virtualFile, "toURI");
VIRTUAL_FILE_METHOD_TO_URL = ReflectionUtils.findMethod(virtualFile, "toURL");
VIRTUAL_FILE_METHOD_GET_NAME = ReflectionUtils.findMethod(virtualFile, "getName");
VIRTUAL_FILE_METHOD_GET_PATH_NAME = ReflectionUtils.findMethod(virtualFile, "getPathName");
GET_PHYSICAL_FILE = ReflectionUtils.findMethod(virtualFile, "getPhysicalFile");
methodName = (VFS_VER.V3.equals(version) ? "getChild" : "findChild");
VIRTUAL_FILE_METHOD_GET_CHILD = ReflectionUtils.findMethod(virtualFile, methodName, String.class);
Class<?> utilsClass = loader.loadClass(pkg + "VFSUtils");
VFS_UTILS_METHOD_GET_COMPATIBLE_URI = ReflectionUtils.findMethod(utilsClass, "getCompatibleURI",
virtualFile);
VFS_UTILS_METHOD_IS_NESTED_FILE = ReflectionUtils.findMethod(utilsClass, "isNestedFile", virtualFile);
VIRTUAL_FILE_VISITOR_INTERFACE = loader.loadClass(pkg + "VirtualFileVisitor");
VIRTUAL_FILE_METHOD_VISIT = ReflectionUtils.findMethod(virtualFile, "visit", VIRTUAL_FILE_VISITOR_INTERFACE);
Class<?> visitorAttributesClass = loader.loadClass(pkg + "VisitorAttributes");
VISITOR_ATTRIBUTES_FIELD_RECURSE = ReflectionUtils.findField(visitorAttributesClass, "RECURSE");
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Could not detect the JBoss VFS infrastructure", ex);
}
}
protected static Object invokeVfsMethod(Method method, Object target, Object... args) throws IOException {
try {
return method.invoke(target, args);
}
catch (InvocationTargetException ex) {
Throwable targetEx = ex.getTargetException();
if (targetEx instanceof IOException) {
throw (IOException) targetEx;
}
ReflectionUtils.handleInvocationTargetException(ex);
}
catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
}
throw new IllegalStateException("Invalid code path reached");
}
static boolean exists(Object vfsResource) {
try {
return (Boolean) invokeVfsMethod(VIRTUAL_FILE_METHOD_EXISTS, vfsResource);
}
catch (IOException ex) {
return false;
}
}
static boolean isReadable(Object vfsResource) {
try {
return ((Long) invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_SIZE, vfsResource) > 0);
}
catch (IOException ex) {
return false;
}
}
static long getLastModified(Object vfsResource) throws IOException {
return (Long) invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_LAST_MODIFIED, vfsResource);
}
static InputStream getInputStream(Object vfsResource) throws IOException {
return (InputStream) invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_INPUT_STREAM, vfsResource);
}
static URL getURL(Object vfsResource) throws IOException {
return (URL) invokeVfsMethod(VIRTUAL_FILE_METHOD_TO_URL, vfsResource);
}
static URI getURI(Object vfsResource) throws IOException {
return (URI) invokeVfsMethod(VIRTUAL_FILE_METHOD_TO_URI, vfsResource);
}
static String getName(Object vfsResource) {
try {
return (String) invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_NAME, vfsResource);
}
catch (IOException ex) {
throw new IllegalStateException("Cannot get resource name", ex);
}
}
static Object getRelative(URL url) throws IOException {
return invokeVfsMethod(VFS_METHOD_GET_ROOT_URL, null, url);
}
static Object getChild(Object vfsResource, String path) throws IOException {
return invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_CHILD, vfsResource, path);
}
static File getFile(Object vfsResource) throws IOException {
if (VFS_VER.V2.equals(version)) {
if ((Boolean) invokeVfsMethod(VFS_UTILS_METHOD_IS_NESTED_FILE, null, vfsResource)) {
throw new IOException("File resolution not supported for nested resource: " + vfsResource);
}
try {
return new File((URI) invokeVfsMethod(VFS_UTILS_METHOD_GET_COMPATIBLE_URI, null, vfsResource));
}
catch (Exception ex) {
throw new NestedIOException("Failed to obtain File reference for " + vfsResource, ex);
}
}
else {
return (File) invokeVfsMethod(GET_PHYSICAL_FILE, vfsResource);
}
}
static Object getRoot(URI url) throws IOException {
return invokeVfsMethod(VFS_METHOD_GET_ROOT_URI, null, url);
}
// protected methods used by the support sub-package
protected static Object getRoot(URL url) throws IOException {
return invokeVfsMethod(VFS_METHOD_GET_ROOT_URL, null, url);
}
protected static Object doGetVisitorAttribute() {
return ReflectionUtils.getField(VISITOR_ATTRIBUTES_FIELD_RECURSE, null);
}
protected static String doGetPath(Object resource) {
return (String) ReflectionUtils.invokeMethod(VIRTUAL_FILE_METHOD_GET_PATH_NAME, resource);
}
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.NestedIOException;
import org.springframework.util.ReflectionUtils;
/**
* Utility for detecting the JBoss VFS version available in the classpath.
* JBoss AS 5+ uses VFS 2.x (package <code>org.jboss.virtual</code>) while
* JBoss AS 6+ uses VFS 3.x (package <code>org.jboss.vfs</code>).
*
* <p>Thanks go to Marius Bogoevici for the initial patch.
*
* <b>Note:</b> This is an internal class and should not be used outside the framework.
*
* @author Costin Leau
* @since 3.0.3
*/
public abstract class VfsUtils {
private static final Log logger = LogFactory.getLog(VfsUtils.class);
private static final String VFS2_PKG = "org.jboss.virtual.";
private static final String VFS3_PKG = "org.jboss.vfs.";
private static final String VFS_NAME = "VFS";
private static enum VFS_VER { V2, V3 }
private static VFS_VER version;
private static Method VFS_METHOD_GET_ROOT_URL = null;
private static Method VFS_METHOD_GET_ROOT_URI = null;
private static Method VIRTUAL_FILE_METHOD_EXISTS = null;
private static Method VIRTUAL_FILE_METHOD_GET_SIZE;
private static Method VIRTUAL_FILE_METHOD_GET_LAST_MODIFIED;
private static Method VIRTUAL_FILE_METHOD_GET_CHILD;
private static Method VIRTUAL_FILE_METHOD_GET_INPUT_STREAM;
private static Method VIRTUAL_FILE_METHOD_TO_URL;
private static Method VIRTUAL_FILE_METHOD_TO_URI;
private static Method VIRTUAL_FILE_METHOD_GET_NAME;
private static Method VIRTUAL_FILE_METHOD_GET_PATH_NAME;
protected static Class<?> VIRTUAL_FILE_VISITOR_INTERFACE;
protected static Method VIRTUAL_FILE_METHOD_VISIT;
private static Method VFS_UTILS_METHOD_IS_NESTED_FILE = null;
private static Method VFS_UTILS_METHOD_GET_COMPATIBLE_URI = null;
private static Field VISITOR_ATTRIBUTES_FIELD_RECURSE = null;
private static Method GET_PHYSICAL_FILE = null;
static {
ClassLoader loader = VfsUtils.class.getClassLoader();
String pkg;
Class<?> vfsClass;
// check for JBoss 6
try {
vfsClass = loader.loadClass(VFS3_PKG + VFS_NAME);
version = VFS_VER.V3;
pkg = VFS3_PKG;
if (logger.isDebugEnabled()) {
logger.debug("JBoss VFS packages for JBoss AS 6 found");
}
}
catch (ClassNotFoundException ex) {
// fallback to JBoss 5
if (logger.isDebugEnabled())
logger.debug("JBoss VFS packages for JBoss AS 6 not found; falling back to JBoss AS 5 packages");
try {
vfsClass = loader.loadClass(VFS2_PKG + VFS_NAME);
version = VFS_VER.V2;
pkg = VFS2_PKG;
if (logger.isDebugEnabled())
logger.debug("JBoss VFS packages for JBoss AS 5 found");
} catch (ClassNotFoundException ex1) {
logger.error("JBoss VFS packages (for both JBoss AS 5 and 6) were not found - JBoss VFS support disabled");
throw new IllegalStateException("Cannot detect JBoss VFS packages", ex1);
}
}
// cache reflective information
try {
String methodName = (VFS_VER.V3.equals(version) ? "getChild" : "getRoot");
VFS_METHOD_GET_ROOT_URL = ReflectionUtils.findMethod(vfsClass, methodName, URL.class);
VFS_METHOD_GET_ROOT_URI = ReflectionUtils.findMethod(vfsClass, methodName, URI.class);
Class<?> virtualFile = loader.loadClass(pkg + "VirtualFile");
VIRTUAL_FILE_METHOD_EXISTS = ReflectionUtils.findMethod(virtualFile, "exists");
VIRTUAL_FILE_METHOD_GET_SIZE = ReflectionUtils.findMethod(virtualFile, "getSize");
VIRTUAL_FILE_METHOD_GET_INPUT_STREAM = ReflectionUtils.findMethod(virtualFile, "openStream");
VIRTUAL_FILE_METHOD_GET_LAST_MODIFIED = ReflectionUtils.findMethod(virtualFile, "getLastModified");
VIRTUAL_FILE_METHOD_TO_URI = ReflectionUtils.findMethod(virtualFile, "toURI");
VIRTUAL_FILE_METHOD_TO_URL = ReflectionUtils.findMethod(virtualFile, "toURL");
VIRTUAL_FILE_METHOD_GET_NAME = ReflectionUtils.findMethod(virtualFile, "getName");
VIRTUAL_FILE_METHOD_GET_PATH_NAME = ReflectionUtils.findMethod(virtualFile, "getPathName");
GET_PHYSICAL_FILE = ReflectionUtils.findMethod(virtualFile, "getPhysicalFile");
methodName = (VFS_VER.V3.equals(version) ? "getChild" : "findChild");
VIRTUAL_FILE_METHOD_GET_CHILD = ReflectionUtils.findMethod(virtualFile, methodName, String.class);
Class<?> utilsClass = loader.loadClass(pkg + "VFSUtils");
VFS_UTILS_METHOD_GET_COMPATIBLE_URI = ReflectionUtils.findMethod(utilsClass, "getCompatibleURI",
virtualFile);
VFS_UTILS_METHOD_IS_NESTED_FILE = ReflectionUtils.findMethod(utilsClass, "isNestedFile", virtualFile);
VIRTUAL_FILE_VISITOR_INTERFACE = loader.loadClass(pkg + "VirtualFileVisitor");
VIRTUAL_FILE_METHOD_VISIT = ReflectionUtils.findMethod(virtualFile, "visit", VIRTUAL_FILE_VISITOR_INTERFACE);
Class<?> visitorAttributesClass = loader.loadClass(pkg + "VisitorAttributes");
VISITOR_ATTRIBUTES_FIELD_RECURSE = ReflectionUtils.findField(visitorAttributesClass, "RECURSE");
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Could not detect the JBoss VFS infrastructure", ex);
}
}
protected static Object invokeVfsMethod(Method method, Object target, Object... args) throws IOException {
try {
return method.invoke(target, args);
}
catch (InvocationTargetException ex) {
Throwable targetEx = ex.getTargetException();
if (targetEx instanceof IOException) {
throw (IOException) targetEx;
}
ReflectionUtils.handleInvocationTargetException(ex);
}
catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
}
throw new IllegalStateException("Invalid code path reached");
}
static boolean exists(Object vfsResource) {
try {
return (Boolean) invokeVfsMethod(VIRTUAL_FILE_METHOD_EXISTS, vfsResource);
}
catch (IOException ex) {
return false;
}
}
static boolean isReadable(Object vfsResource) {
try {
return ((Long) invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_SIZE, vfsResource) > 0);
}
catch (IOException ex) {
return false;
}
}
static long getLastModified(Object vfsResource) throws IOException {
return (Long) invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_LAST_MODIFIED, vfsResource);
}
static InputStream getInputStream(Object vfsResource) throws IOException {
return (InputStream) invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_INPUT_STREAM, vfsResource);
}
static URL getURL(Object vfsResource) throws IOException {
return (URL) invokeVfsMethod(VIRTUAL_FILE_METHOD_TO_URL, vfsResource);
}
static URI getURI(Object vfsResource) throws IOException {
return (URI) invokeVfsMethod(VIRTUAL_FILE_METHOD_TO_URI, vfsResource);
}
static String getName(Object vfsResource) {
try {
return (String) invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_NAME, vfsResource);
}
catch (IOException ex) {
throw new IllegalStateException("Cannot get resource name", ex);
}
}
static Object getRelative(URL url) throws IOException {
return invokeVfsMethod(VFS_METHOD_GET_ROOT_URL, null, url);
}
static Object getChild(Object vfsResource, String path) throws IOException {
return invokeVfsMethod(VIRTUAL_FILE_METHOD_GET_CHILD, vfsResource, path);
}
static File getFile(Object vfsResource) throws IOException {
if (VFS_VER.V2.equals(version)) {
if ((Boolean) invokeVfsMethod(VFS_UTILS_METHOD_IS_NESTED_FILE, null, vfsResource)) {
throw new IOException("File resolution not supported for nested resource: " + vfsResource);
}
try {
return new File((URI) invokeVfsMethod(VFS_UTILS_METHOD_GET_COMPATIBLE_URI, null, vfsResource));
}
catch (Exception ex) {
throw new NestedIOException("Failed to obtain File reference for " + vfsResource, ex);
}
}
else {
return (File) invokeVfsMethod(GET_PHYSICAL_FILE, vfsResource);
}
}
static Object getRoot(URI url) throws IOException {
return invokeVfsMethod(VFS_METHOD_GET_ROOT_URI, null, url);
}
// protected methods used by the support sub-package
protected static Object getRoot(URL url) throws IOException {
return invokeVfsMethod(VFS_METHOD_GET_ROOT_URL, null, url);
}
protected static Object doGetVisitorAttribute() {
return ReflectionUtils.getField(VISITOR_ATTRIBUTES_FIELD_RECURSE, null);
}
protected static String doGetPath(Object resource) {
return (String) ReflectionUtils.invokeMethod(VIRTUAL_FILE_METHOD_GET_PATH_NAME, resource);
}
}

View File

@@ -1,52 +1,52 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io;
import java.io.IOException;
import java.io.OutputStream;
/**
* Extended interface for a resource that supports writing to it.
* Provides an {@link #getOutputStream() OutputStream accessor}.
*
* @author Juergen Hoeller
* @since 3.1
* @see java.io.OutputStream
*/
public interface WritableResource extends Resource {
/**
* Return whether the contents of this resource can be modified,
* e.g. via {@link #getOutputStream()} or {@link #getFile()}.
* <p>Will be <code>true</code> for typical resource descriptors;
* note that actual content writing may still fail when attempted.
* However, a value of <code>false</code> is a definitive indication
* that the resource content cannot be modified.
* @see #getOutputStream()
* @see #isReadable()
*/
boolean isWritable();
/**
* Return an {@link OutputStream} for the underlying resource,
* allowing to (over-)write its content.
* @throws IOException if the stream could not be opened
* @see #getInputStream()
*/
OutputStream getOutputStream() throws IOException;
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io;
import java.io.IOException;
import java.io.OutputStream;
/**
* Extended interface for a resource that supports writing to it.
* Provides an {@link #getOutputStream() OutputStream accessor}.
*
* @author Juergen Hoeller
* @since 3.1
* @see java.io.OutputStream
*/
public interface WritableResource extends Resource {
/**
* Return whether the contents of this resource can be modified,
* e.g. via {@link #getOutputStream()} or {@link #getFile()}.
* <p>Will be <code>true</code> for typical resource descriptors;
* note that actual content writing may still fail when attempted.
* However, a value of <code>false</code> is a definitive indication
* that the resource content cannot be modified.
* @see #getOutputStream()
* @see #isReadable()
*/
boolean isWritable();
/**
* Return an {@link OutputStream} for the underlying resource,
* allowing to (over-)write its content.
* @throws IOException if the stream could not be opened
* @see #getInputStream()
*/
OutputStream getOutputStream() throws IOException;
}

View File

@@ -1,53 +1,53 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io.support;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.net.URL;
import org.springframework.core.io.VfsUtils;
/**
* Artificial class used for accessing the {@link VfsUtils} methods
* without exposing them to the entire world.
*
* @author Costin Leau
* @since 3.0.3
*/
abstract class VfsPatternUtils extends VfsUtils {
static Object getVisitorAttribute() {
return doGetVisitorAttribute();
}
static String getPath(Object resource) {
return doGetPath(resource);
}
static Object findRoot(URL url) throws IOException {
return getRoot(url);
}
static void visit(Object resource, InvocationHandler visitor) throws IOException {
Object visitorProxy = Proxy.newProxyInstance(VIRTUAL_FILE_VISITOR_INTERFACE.getClassLoader(),
new Class<?>[] { VIRTUAL_FILE_VISITOR_INTERFACE }, visitor);
invokeVfsMethod(VIRTUAL_FILE_METHOD_VISIT, resource, visitorProxy);
}
}
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io.support;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.net.URL;
import org.springframework.core.io.VfsUtils;
/**
* Artificial class used for accessing the {@link VfsUtils} methods
* without exposing them to the entire world.
*
* @author Costin Leau
* @since 3.0.3
*/
abstract class VfsPatternUtils extends VfsUtils {
static Object getVisitorAttribute() {
return doGetVisitorAttribute();
}
static String getPath(Object resource) {
return doGetPath(resource);
}
static Object findRoot(URL url) throws IOException {
return getRoot(url);
}
static void visit(Object resource, InvocationHandler visitor) throws IOException {
Object visitorProxy = Proxy.newProxyInstance(VIRTUAL_FILE_VISITOR_INTERFACE.getClassLoader(),
new Class<?>[] { VIRTUAL_FILE_VISITOR_INTERFACE }, visitor);
invokeVfsMethod(VIRTUAL_FILE_METHOD_VISIT, resource, visitorProxy);
}
}

View File

@@ -1,9 +1,9 @@
/**
*
* Support classes for Spring's serializer abstraction.
* Includes adapters to the Converter SPI.
*
*/
package org.springframework.core.serializer.support;
/**
*
* Support classes for Spring's serializer abstraction.
* Includes adapters to the Converter SPI.
*
*/
package org.springframework.core.serializer.support;

View File

@@ -1,87 +1,87 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.task.support;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;
import org.springframework.core.task.TaskExecutor;
import org.springframework.util.Assert;
/**
* Adapter that takes a Spring {@link org.springframework.core.task.TaskExecutor})
* and exposes a full <code>java.util.concurrent.ExecutorService</code> for it.
*
* <p>This is primarily for adapting to client components that communicate via the
* <code>java.util.concurrent.ExecutorService</code> API. It can also be used as
* common ground between a local Spring <code>TaskExecutor</code> backend and a
* JNDI-located <code>ManagedExecutorService</code> in a Java EE 6 environment.
*
* <p><b>NOTE:</b> This ExecutorService adapter does <em>not</em> support the
* lifecycle methods in the <code>java.util.concurrent.ExecutorService</code> API
* ("shutdown()" etc), similar to a server-wide <code>ManagedExecutorService</code>
* in a Java EE 6 environment. The lifecycle is always up to the backend pool,
* with this adapter acting as an access-only proxy for that target pool.
*
* @author Juergen Hoeller
* @since 3.0
* @see java.util.concurrent.ExecutorService
*/
public class ExecutorServiceAdapter extends AbstractExecutorService {
private final TaskExecutor taskExecutor;
/**
* Create a new ExecutorServiceAdapter, using the given target executor.
* @param concurrentExecutor the target executor to delegate to
*/
public ExecutorServiceAdapter(TaskExecutor taskExecutor) {
Assert.notNull(taskExecutor, "TaskExecutor must not be null");
this.taskExecutor = taskExecutor;
}
public void execute(Runnable task) {
this.taskExecutor.execute(task);
}
public void shutdown() {
throw new IllegalStateException(
"Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
}
public List<Runnable> shutdownNow() {
throw new IllegalStateException(
"Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
}
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
throw new IllegalStateException(
"Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
}
public boolean isShutdown() {
return false;
}
public boolean isTerminated() {
return false;
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.task.support;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;
import org.springframework.core.task.TaskExecutor;
import org.springframework.util.Assert;
/**
* Adapter that takes a Spring {@link org.springframework.core.task.TaskExecutor})
* and exposes a full <code>java.util.concurrent.ExecutorService</code> for it.
*
* <p>This is primarily for adapting to client components that communicate via the
* <code>java.util.concurrent.ExecutorService</code> API. It can also be used as
* common ground between a local Spring <code>TaskExecutor</code> backend and a
* JNDI-located <code>ManagedExecutorService</code> in a Java EE 6 environment.
*
* <p><b>NOTE:</b> This ExecutorService adapter does <em>not</em> support the
* lifecycle methods in the <code>java.util.concurrent.ExecutorService</code> API
* ("shutdown()" etc), similar to a server-wide <code>ManagedExecutorService</code>
* in a Java EE 6 environment. The lifecycle is always up to the backend pool,
* with this adapter acting as an access-only proxy for that target pool.
*
* @author Juergen Hoeller
* @since 3.0
* @see java.util.concurrent.ExecutorService
*/
public class ExecutorServiceAdapter extends AbstractExecutorService {
private final TaskExecutor taskExecutor;
/**
* Create a new ExecutorServiceAdapter, using the given target executor.
* @param concurrentExecutor the target executor to delegate to
*/
public ExecutorServiceAdapter(TaskExecutor taskExecutor) {
Assert.notNull(taskExecutor, "TaskExecutor must not be null");
this.taskExecutor = taskExecutor;
}
public void execute(Runnable task) {
this.taskExecutor.execute(task);
}
public void shutdown() {
throw new IllegalStateException(
"Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
}
public List<Runnable> shutdownNow() {
throw new IllegalStateException(
"Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
}
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
throw new IllegalStateException(
"Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
}
public boolean isShutdown() {
return false;
}
public boolean isTerminated() {
return false;
}
}

View File

@@ -1,79 +1,79 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type;
import java.util.Map;
/**
* Interface that defines abstract access to the annotations of a specific
* class, in a form that does not require that class to be loaded yet.
*
* @author Juergen Hoeller
* @author Mark Pollack
* @author Chris Beams
* @since 3.0
* @see StandardMethodMetadata
* @see AnnotationMetadata#getAnnotatedMethods
*/
public interface MethodMetadata {
/**
* Return the name of the method.
*/
String getMethodName();
/**
* Return the fully-qualified name of the class that declares this method.
*/
public String getDeclaringClassName();
/**
* Return whether the underlying method is declared as 'static'.
*/
boolean isStatic();
/**
* Return whether the underlying method is marked as 'final'.
*/
boolean isFinal();
/**
* Return whether the underlying method is overridable,
* i.e. not marked as static, final or private.
*/
boolean isOverridable();
/**
* Determine whether the underlying method has an annotation or
* meta-annotation of the given type defined.
* @param annotationType the annotation type to look for
* @return whether a matching annotation is defined
*/
boolean isAnnotated(String annotationType);
/**
* Retrieve the attributes of the annotation of the given type,
* if any (i.e. if defined on the underlying method, as direct
* annotation or as meta-annotation).
* @param annotationType the annotation type to look for
* @return a Map of attributes, with the attribute name as key (e.g. "value")
* and the defined attribute value as Map value. This return value will be
* <code>null</code> if no matching annotation is defined.
*/
Map<String, Object> getAnnotationAttributes(String annotationType);
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type;
import java.util.Map;
/**
* Interface that defines abstract access to the annotations of a specific
* class, in a form that does not require that class to be loaded yet.
*
* @author Juergen Hoeller
* @author Mark Pollack
* @author Chris Beams
* @since 3.0
* @see StandardMethodMetadata
* @see AnnotationMetadata#getAnnotatedMethods
*/
public interface MethodMetadata {
/**
* Return the name of the method.
*/
String getMethodName();
/**
* Return the fully-qualified name of the class that declares this method.
*/
public String getDeclaringClassName();
/**
* Return whether the underlying method is declared as 'static'.
*/
boolean isStatic();
/**
* Return whether the underlying method is marked as 'final'.
*/
boolean isFinal();
/**
* Return whether the underlying method is overridable,
* i.e. not marked as static, final or private.
*/
boolean isOverridable();
/**
* Determine whether the underlying method has an annotation or
* meta-annotation of the given type defined.
* @param annotationType the annotation type to look for
* @return whether a matching annotation is defined
*/
boolean isAnnotated(String annotationType);
/**
* Retrieve the attributes of the annotation of the given type,
* if any (i.e. if defined on the underlying method, as direct
* annotation or as meta-annotation).
* @param annotationType the annotation type to look for
* @return a Map of attributes, with the attribute name as key (e.g. "value")
* and the defined attribute value as Map value. This return value will be
* <code>null</code> if no matching annotation is defined.
*/
Map<String, Object> getAnnotationAttributes(String annotationType);
}

View File

@@ -1,108 +1,108 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
/**
* {@link MethodMetadata} implementation that uses standard reflection
* to introspect a given <code>Method</code>.
*
* @author Juergen Hoeller
* @author Mark Pollack
* @author Chris Beams
* @since 3.0
*/
public class StandardMethodMetadata implements MethodMetadata {
private final Method introspectedMethod;
/**
* Create a new StandardMethodMetadata wrapper for the given Method.
* @param introspectedMethod the Method to introspect
*/
public StandardMethodMetadata(Method introspectedMethod) {
Assert.notNull(introspectedMethod, "Method must not be null");
this.introspectedMethod = introspectedMethod;
}
/**
* Return the underlying Method.
*/
public final Method getIntrospectedMethod() {
return this.introspectedMethod;
}
public String getMethodName() {
return this.introspectedMethod.getName();
}
public String getDeclaringClassName() {
return this.introspectedMethod.getDeclaringClass().getName();
}
public boolean isStatic() {
return Modifier.isStatic(this.introspectedMethod.getModifiers());
}
public boolean isFinal() {
return Modifier.isFinal(this.introspectedMethod.getModifiers());
}
public boolean isOverridable() {
return (!isStatic() && !isFinal() && !Modifier.isPrivate(this.introspectedMethod.getModifiers()));
}
public boolean isAnnotated(String annotationType) {
Annotation[] anns = this.introspectedMethod.getAnnotations();
for (Annotation ann : anns) {
if (ann.annotationType().getName().equals(annotationType)) {
return true;
}
for (Annotation metaAnn : ann.annotationType().getAnnotations()) {
if (metaAnn.annotationType().getName().equals(annotationType)) {
return true;
}
}
}
return false;
}
public Map<String, Object> getAnnotationAttributes(String annotationType) {
Annotation[] anns = this.introspectedMethod.getAnnotations();
for (Annotation ann : anns) {
if (ann.annotationType().getName().equals(annotationType)) {
return AnnotationUtils.getAnnotationAttributes(ann, true);
}
for (Annotation metaAnn : ann.annotationType().getAnnotations()) {
if (metaAnn.annotationType().getName().equals(annotationType)) {
return AnnotationUtils.getAnnotationAttributes(metaAnn, true);
}
}
}
return null;
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
/**
* {@link MethodMetadata} implementation that uses standard reflection
* to introspect a given <code>Method</code>.
*
* @author Juergen Hoeller
* @author Mark Pollack
* @author Chris Beams
* @since 3.0
*/
public class StandardMethodMetadata implements MethodMetadata {
private final Method introspectedMethod;
/**
* Create a new StandardMethodMetadata wrapper for the given Method.
* @param introspectedMethod the Method to introspect
*/
public StandardMethodMetadata(Method introspectedMethod) {
Assert.notNull(introspectedMethod, "Method must not be null");
this.introspectedMethod = introspectedMethod;
}
/**
* Return the underlying Method.
*/
public final Method getIntrospectedMethod() {
return this.introspectedMethod;
}
public String getMethodName() {
return this.introspectedMethod.getName();
}
public String getDeclaringClassName() {
return this.introspectedMethod.getDeclaringClass().getName();
}
public boolean isStatic() {
return Modifier.isStatic(this.introspectedMethod.getModifiers());
}
public boolean isFinal() {
return Modifier.isFinal(this.introspectedMethod.getModifiers());
}
public boolean isOverridable() {
return (!isStatic() && !isFinal() && !Modifier.isPrivate(this.introspectedMethod.getModifiers()));
}
public boolean isAnnotated(String annotationType) {
Annotation[] anns = this.introspectedMethod.getAnnotations();
for (Annotation ann : anns) {
if (ann.annotationType().getName().equals(annotationType)) {
return true;
}
for (Annotation metaAnn : ann.annotationType().getAnnotations()) {
if (metaAnn.annotationType().getName().equals(annotationType)) {
return true;
}
}
}
return false;
}
public Map<String, Object> getAnnotationAttributes(String annotationType) {
Annotation[] anns = this.introspectedMethod.getAnnotations();
for (Annotation ann : anns) {
if (ann.annotationType().getName().equals(annotationType)) {
return AnnotationUtils.getAnnotationAttributes(ann, true);
}
for (Annotation metaAnn : ann.annotationType().getAnnotations()) {
if (metaAnn.annotationType().getName().equals(annotationType)) {
return AnnotationUtils.getAnnotationAttributes(metaAnn, true);
}
}
}
return null;
}
}

View File

@@ -1,150 +1,150 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type.classreading;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.asm.AnnotationVisitor;
import org.springframework.asm.Type;
import org.springframework.asm.commons.EmptyVisitor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
/**
* ASM visitor which looks for the annotations defined on a class or method.
*
* @author Juergen Hoeller
* @since 3.0
*/
final class AnnotationAttributesReadingVisitor implements AnnotationVisitor {
private final String annotationType;
private final Map<String, Map<String, Object>> attributesMap;
private final Map<String, Set<String>> metaAnnotationMap;
private final ClassLoader classLoader;
private final Map<String, Object> localAttributes = new LinkedHashMap<String, Object>();
public AnnotationAttributesReadingVisitor(
String annotationType, Map<String, Map<String, Object>> attributesMap,
Map<String, Set<String>> metaAnnotationMap, ClassLoader classLoader) {
this.annotationType = annotationType;
this.attributesMap = attributesMap;
this.metaAnnotationMap = metaAnnotationMap;
this.classLoader = classLoader;
}
public void visit(String name, Object value) {
this.localAttributes.put(name, value);
}
public void visitEnum(String name, String desc, String value) {
Object valueToUse = value;
try {
Class<?> enumType = this.classLoader.loadClass(Type.getType(desc).getClassName());
Field enumConstant = ReflectionUtils.findField(enumType, value);
if (enumConstant != null) {
valueToUse = enumConstant.get(null);
}
}
catch (Exception ex) {
// Class not found - can't resolve class reference in annotation attribute.
}
this.localAttributes.put(name, valueToUse);
}
public AnnotationVisitor visitAnnotation(String name, String desc) {
return new EmptyVisitor();
}
public AnnotationVisitor visitArray(final String attrName) {
return new AnnotationVisitor() {
public void visit(String name, Object value) {
Object newValue = value;
Object existingValue = localAttributes.get(attrName);
if (existingValue != null) {
newValue = ObjectUtils.addObjectToArray((Object[]) existingValue, newValue);
}
else {
Object[] newArray = (Object[]) Array.newInstance(newValue.getClass(), 1);
newArray[0] = newValue;
newValue = newArray;
}
localAttributes.put(attrName, newValue);
}
public void visitEnum(String name, String desc, String value) {
}
public AnnotationVisitor visitAnnotation(String name, String desc) {
return new EmptyVisitor();
}
public AnnotationVisitor visitArray(String name) {
return new EmptyVisitor();
}
public void visitEnd() {
}
};
}
public void visitEnd() {
this.attributesMap.put(this.annotationType, this.localAttributes);
try {
Class<?> annotationClass = this.classLoader.loadClass(this.annotationType);
// Check declared default values of attributes in the annotation type.
Method[] annotationAttributes = annotationClass.getMethods();
for (Method annotationAttribute : annotationAttributes) {
String attributeName = annotationAttribute.getName();
Object defaultValue = annotationAttribute.getDefaultValue();
if (defaultValue != null && !this.localAttributes.containsKey(attributeName)) {
this.localAttributes.put(attributeName, defaultValue);
}
}
// Register annotations that the annotation type is annotated with.
Set<String> metaAnnotationTypeNames = new LinkedHashSet<String>();
for (Annotation metaAnnotation : annotationClass.getAnnotations()) {
metaAnnotationTypeNames.add(metaAnnotation.annotationType().getName());
if (!this.attributesMap.containsKey(metaAnnotation.annotationType().getName())) {
this.attributesMap.put(metaAnnotation.annotationType().getName(),
AnnotationUtils.getAnnotationAttributes(metaAnnotation, true));
}
for (Annotation metaMetaAnnotation : metaAnnotation.annotationType().getAnnotations()) {
metaAnnotationTypeNames.add(metaMetaAnnotation.annotationType().getName());
}
}
if (this.metaAnnotationMap != null) {
this.metaAnnotationMap.put(this.annotationType, metaAnnotationTypeNames);
}
}
catch (ClassNotFoundException ex) {
// Class not found - can't determine meta-annotations.
}
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type.classreading;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.asm.AnnotationVisitor;
import org.springframework.asm.Type;
import org.springframework.asm.commons.EmptyVisitor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
/**
* ASM visitor which looks for the annotations defined on a class or method.
*
* @author Juergen Hoeller
* @since 3.0
*/
final class AnnotationAttributesReadingVisitor implements AnnotationVisitor {
private final String annotationType;
private final Map<String, Map<String, Object>> attributesMap;
private final Map<String, Set<String>> metaAnnotationMap;
private final ClassLoader classLoader;
private final Map<String, Object> localAttributes = new LinkedHashMap<String, Object>();
public AnnotationAttributesReadingVisitor(
String annotationType, Map<String, Map<String, Object>> attributesMap,
Map<String, Set<String>> metaAnnotationMap, ClassLoader classLoader) {
this.annotationType = annotationType;
this.attributesMap = attributesMap;
this.metaAnnotationMap = metaAnnotationMap;
this.classLoader = classLoader;
}
public void visit(String name, Object value) {
this.localAttributes.put(name, value);
}
public void visitEnum(String name, String desc, String value) {
Object valueToUse = value;
try {
Class<?> enumType = this.classLoader.loadClass(Type.getType(desc).getClassName());
Field enumConstant = ReflectionUtils.findField(enumType, value);
if (enumConstant != null) {
valueToUse = enumConstant.get(null);
}
}
catch (Exception ex) {
// Class not found - can't resolve class reference in annotation attribute.
}
this.localAttributes.put(name, valueToUse);
}
public AnnotationVisitor visitAnnotation(String name, String desc) {
return new EmptyVisitor();
}
public AnnotationVisitor visitArray(final String attrName) {
return new AnnotationVisitor() {
public void visit(String name, Object value) {
Object newValue = value;
Object existingValue = localAttributes.get(attrName);
if (existingValue != null) {
newValue = ObjectUtils.addObjectToArray((Object[]) existingValue, newValue);
}
else {
Object[] newArray = (Object[]) Array.newInstance(newValue.getClass(), 1);
newArray[0] = newValue;
newValue = newArray;
}
localAttributes.put(attrName, newValue);
}
public void visitEnum(String name, String desc, String value) {
}
public AnnotationVisitor visitAnnotation(String name, String desc) {
return new EmptyVisitor();
}
public AnnotationVisitor visitArray(String name) {
return new EmptyVisitor();
}
public void visitEnd() {
}
};
}
public void visitEnd() {
this.attributesMap.put(this.annotationType, this.localAttributes);
try {
Class<?> annotationClass = this.classLoader.loadClass(this.annotationType);
// Check declared default values of attributes in the annotation type.
Method[] annotationAttributes = annotationClass.getMethods();
for (Method annotationAttribute : annotationAttributes) {
String attributeName = annotationAttribute.getName();
Object defaultValue = annotationAttribute.getDefaultValue();
if (defaultValue != null && !this.localAttributes.containsKey(attributeName)) {
this.localAttributes.put(attributeName, defaultValue);
}
}
// Register annotations that the annotation type is annotated with.
Set<String> metaAnnotationTypeNames = new LinkedHashSet<String>();
for (Annotation metaAnnotation : annotationClass.getAnnotations()) {
metaAnnotationTypeNames.add(metaAnnotation.annotationType().getName());
if (!this.attributesMap.containsKey(metaAnnotation.annotationType().getName())) {
this.attributesMap.put(metaAnnotation.annotationType().getName(),
AnnotationUtils.getAnnotationAttributes(metaAnnotation, true));
}
for (Annotation metaMetaAnnotation : metaAnnotation.annotationType().getAnnotations()) {
metaAnnotationTypeNames.add(metaMetaAnnotation.annotationType().getName());
}
}
if (this.metaAnnotationMap != null) {
this.metaAnnotationMap.put(this.annotationType, metaAnnotationTypeNames);
}
}
catch (ClassNotFoundException ex) {
// Class not found - can't determine meta-annotations.
}
}
}

View File

@@ -1,75 +1,75 @@
/*
* Copyright 2004-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Iterator that combines multiple other iterators.
* This implementation maintains a list of iterators which are invoked in sequence until all iterators are exhausted.
* @author Erwin Vervaet
*/
public class CompositeIterator<E> implements Iterator<E> {
private List<Iterator<E>> iterators = new LinkedList<Iterator<E>>();
private boolean inUse = false;
/**
* Create a new composite iterator. Add iterators using the {@link #add(Iterator)} method.
*/
public CompositeIterator() {
}
/**
* Add given iterator to this composite.
*/
public void add(Iterator<E> iterator) {
Assert.state(!inUse, "You can no longer add iterator to a composite iterator that's already in use");
if (iterators.contains(iterator)) {
throw new IllegalArgumentException("You cannot add the same iterator twice");
}
iterators.add(iterator);
}
public boolean hasNext() {
inUse = true;
for (Iterator<Iterator<E>> it = iterators.iterator(); it.hasNext();) {
if (it.next().hasNext()) {
return true;
}
}
return false;
}
public E next() {
inUse = true;
for (Iterator<Iterator<E>> it = iterators.iterator(); it.hasNext();) {
Iterator<E> iterator = it.next();
if (iterator.hasNext()) {
return iterator.next();
}
}
throw new NoSuchElementException("Exhaused all iterators");
}
public void remove() {
throw new UnsupportedOperationException("Remove is not supported");
}
/*
* Copyright 2004-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Iterator that combines multiple other iterators.
* This implementation maintains a list of iterators which are invoked in sequence until all iterators are exhausted.
* @author Erwin Vervaet
*/
public class CompositeIterator<E> implements Iterator<E> {
private List<Iterator<E>> iterators = new LinkedList<Iterator<E>>();
private boolean inUse = false;
/**
* Create a new composite iterator. Add iterators using the {@link #add(Iterator)} method.
*/
public CompositeIterator() {
}
/**
* Add given iterator to this composite.
*/
public void add(Iterator<E> iterator) {
Assert.state(!inUse, "You can no longer add iterator to a composite iterator that's already in use");
if (iterators.contains(iterator)) {
throw new IllegalArgumentException("You cannot add the same iterator twice");
}
iterators.add(iterator);
}
public boolean hasNext() {
inUse = true;
for (Iterator<Iterator<E>> it = iterators.iterator(); it.hasNext();) {
if (it.next().hasNext()) {
return true;
}
}
return false;
}
public E next() {
inUse = true;
for (Iterator<Iterator<E>> it = iterators.iterator(); it.hasNext();) {
Iterator<E> iterator = it.next();
if (iterator.hasNext()) {
return iterator.next();
}
}
throw new NoSuchElementException("Exhaused all iterators");
}
public void remove() {
throw new UnsupportedOperationException("Remove is not supported");
}
}

View File

@@ -1,149 +1,149 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
/**
* {@link LinkedHashMap} variant that stores String keys in a case-insensitive
* manner, for example for key-based access in a results table.
*
* <p>Preserves the original order as well as the original casing of keys,
* while allowing for contains, get and remove calls with any case of key.
*
* <p>Does <i>not</i> support <code>null</code> keys.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class LinkedCaseInsensitiveMap<V> extends LinkedHashMap<String, V> {
private final Map<String, String> caseInsensitiveKeys;
private final Locale locale;
/**
* Create a new LinkedCaseInsensitiveMap for the default Locale.
* @see java.lang.String#toLowerCase()
*/
public LinkedCaseInsensitiveMap() {
this(null);
}
/**
* Create a new LinkedCaseInsensitiveMap that stores lower-case keys
* according to the given Locale.
* @param locale the Locale to use for lower-case conversion
* @see java.lang.String#toLowerCase(java.util.Locale)
*/
public LinkedCaseInsensitiveMap(Locale locale) {
super();
this.caseInsensitiveKeys = new HashMap<String, String>();
this.locale = (locale != null ? locale : Locale.getDefault());
}
/**
* Create a new LinkedCaseInsensitiveMap that wraps a {@link LinkedHashMap}
* with the given initial capacity and stores lower-case keys according
* to the default Locale.
* @param initialCapacity the initial capacity
* @see java.lang.String#toLowerCase()
*/
public LinkedCaseInsensitiveMap(int initialCapacity) {
this(initialCapacity, null);
}
/**
* Create a new LinkedCaseInsensitiveMap that wraps a {@link LinkedHashMap}
* with the given initial capacity and stores lower-case keys according
* to the given Locale.
* @param initialCapacity the initial capacity
* @param locale the Locale to use for lower-case conversion
* @see java.lang.String#toLowerCase(java.util.Locale)
*/
public LinkedCaseInsensitiveMap(int initialCapacity, Locale locale) {
super(initialCapacity);
this.caseInsensitiveKeys = new HashMap<String, String>(initialCapacity);
this.locale = (locale != null ? locale : Locale.getDefault());
}
@Override
public V put(String key, V value) {
this.caseInsensitiveKeys.put(convertKey(key), key);
return super.put(key, value);
}
@Override
public void putAll(Map<? extends String, ? extends V> map) {
if (map.isEmpty()) {
return;
}
for (Map.Entry<? extends String, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public boolean containsKey(Object key) {
return (key instanceof String && this.caseInsensitiveKeys.containsKey(convertKey((String) key)));
}
@Override
public V get(Object key) {
if (key instanceof String) {
return super.get(this.caseInsensitiveKeys.get(convertKey((String) key)));
}
else {
return null;
}
}
@Override
public V remove(Object key) {
if (key instanceof String ) {
return super.remove(this.caseInsensitiveKeys.remove(convertKey((String) key)));
}
else {
return null;
}
}
@Override
public void clear() {
this.caseInsensitiveKeys.clear();
super.clear();
}
/**
* Convert the given key to a case-insensitive key.
* <p>The default implementation converts the key
* to lower-case according to this Map's Locale.
* @param key the user-specified key
* @return the key to use for storing
* @see java.lang.String#toLowerCase(java.util.Locale)
*/
protected String convertKey(String key) {
return key.toLowerCase(this.locale);
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
/**
* {@link LinkedHashMap} variant that stores String keys in a case-insensitive
* manner, for example for key-based access in a results table.
*
* <p>Preserves the original order as well as the original casing of keys,
* while allowing for contains, get and remove calls with any case of key.
*
* <p>Does <i>not</i> support <code>null</code> keys.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class LinkedCaseInsensitiveMap<V> extends LinkedHashMap<String, V> {
private final Map<String, String> caseInsensitiveKeys;
private final Locale locale;
/**
* Create a new LinkedCaseInsensitiveMap for the default Locale.
* @see java.lang.String#toLowerCase()
*/
public LinkedCaseInsensitiveMap() {
this(null);
}
/**
* Create a new LinkedCaseInsensitiveMap that stores lower-case keys
* according to the given Locale.
* @param locale the Locale to use for lower-case conversion
* @see java.lang.String#toLowerCase(java.util.Locale)
*/
public LinkedCaseInsensitiveMap(Locale locale) {
super();
this.caseInsensitiveKeys = new HashMap<String, String>();
this.locale = (locale != null ? locale : Locale.getDefault());
}
/**
* Create a new LinkedCaseInsensitiveMap that wraps a {@link LinkedHashMap}
* with the given initial capacity and stores lower-case keys according
* to the default Locale.
* @param initialCapacity the initial capacity
* @see java.lang.String#toLowerCase()
*/
public LinkedCaseInsensitiveMap(int initialCapacity) {
this(initialCapacity, null);
}
/**
* Create a new LinkedCaseInsensitiveMap that wraps a {@link LinkedHashMap}
* with the given initial capacity and stores lower-case keys according
* to the given Locale.
* @param initialCapacity the initial capacity
* @param locale the Locale to use for lower-case conversion
* @see java.lang.String#toLowerCase(java.util.Locale)
*/
public LinkedCaseInsensitiveMap(int initialCapacity, Locale locale) {
super(initialCapacity);
this.caseInsensitiveKeys = new HashMap<String, String>(initialCapacity);
this.locale = (locale != null ? locale : Locale.getDefault());
}
@Override
public V put(String key, V value) {
this.caseInsensitiveKeys.put(convertKey(key), key);
return super.put(key, value);
}
@Override
public void putAll(Map<? extends String, ? extends V> map) {
if (map.isEmpty()) {
return;
}
for (Map.Entry<? extends String, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public boolean containsKey(Object key) {
return (key instanceof String && this.caseInsensitiveKeys.containsKey(convertKey((String) key)));
}
@Override
public V get(Object key) {
if (key instanceof String) {
return super.get(this.caseInsensitiveKeys.get(convertKey((String) key)));
}
else {
return null;
}
}
@Override
public V remove(Object key) {
if (key instanceof String ) {
return super.remove(this.caseInsensitiveKeys.remove(convertKey((String) key)));
}
else {
return null;
}
}
@Override
public void clear() {
this.caseInsensitiveKeys.clear();
super.clear();
}
/**
* Convert the given key to a case-insensitive key.
* <p>The default implementation converts the key
* to lower-case according to this Map's Locale.
* @param key the user-specified key
* @return the key to use for storing
* @see java.lang.String#toLowerCase(java.util.Locale)
*/
protected String convertKey(String key) {
return key.toLowerCase(this.locale);
}
}

View File

@@ -1,105 +1,105 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @author Chris Shepperd
*/
public class ExceptionDepthComparatorTests {
@Test
public void targetBeforeSameDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(TargetException.class, SameDepthException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void sameDepthBeforeTarget() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(SameDepthException.class, TargetException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void lowestDepthBeforeTarget() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(LowestDepthException.class, TargetException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void targetBeforeLowestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(TargetException.class, LowestDepthException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void noDepthBeforeTarget() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(NoDepthException.class, TargetException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void noDepthBeforeHighestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(NoDepthException.class, HighestDepthException.class);
assertEquals(HighestDepthException.class, foundClass);
}
@Test
public void highestDepthBeforeNoDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(HighestDepthException.class, NoDepthException.class);
assertEquals(HighestDepthException.class, foundClass);
}
@Test
public void highestDepthBeforeLowestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(HighestDepthException.class, LowestDepthException.class);
assertEquals(LowestDepthException.class, foundClass);
}
@Test
public void lowestDepthBeforeHighestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(LowestDepthException.class, HighestDepthException.class);
assertEquals(LowestDepthException.class, foundClass);
}
private Class<? extends Throwable> findClosestMatch(Class<? extends Throwable>... classes) {
return ExceptionDepthComparator.findClosestMatch(Arrays.asList(classes), new TargetException());
}
public class HighestDepthException extends Throwable {
}
public class LowestDepthException extends HighestDepthException {
}
public class TargetException extends LowestDepthException {
}
public class SameDepthException extends LowestDepthException {
}
public class NoDepthException extends TargetException {
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @author Chris Shepperd
*/
public class ExceptionDepthComparatorTests {
@Test
public void targetBeforeSameDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(TargetException.class, SameDepthException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void sameDepthBeforeTarget() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(SameDepthException.class, TargetException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void lowestDepthBeforeTarget() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(LowestDepthException.class, TargetException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void targetBeforeLowestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(TargetException.class, LowestDepthException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void noDepthBeforeTarget() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(NoDepthException.class, TargetException.class);
assertEquals(TargetException.class, foundClass);
}
@Test
public void noDepthBeforeHighestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(NoDepthException.class, HighestDepthException.class);
assertEquals(HighestDepthException.class, foundClass);
}
@Test
public void highestDepthBeforeNoDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(HighestDepthException.class, NoDepthException.class);
assertEquals(HighestDepthException.class, foundClass);
}
@Test
public void highestDepthBeforeLowestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(HighestDepthException.class, LowestDepthException.class);
assertEquals(LowestDepthException.class, foundClass);
}
@Test
public void lowestDepthBeforeHighestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(LowestDepthException.class, HighestDepthException.class);
assertEquals(LowestDepthException.class, foundClass);
}
private Class<? extends Throwable> findClosestMatch(Class<? extends Throwable>... classes) {
return ExceptionDepthComparator.findClosestMatch(Arrays.asList(classes), new TargetException());
}
public class HighestDepthException extends Throwable {
}
public class LowestDepthException extends HighestDepthException {
}
public class TargetException extends LowestDepthException {
}
public class SameDepthException extends LowestDepthException {
}
public class NoDepthException extends TargetException {
}
}

View File

@@ -1,97 +1,97 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.util.Collection;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class GenericTypeResolverTests {
@Test
public void testSimpleInterfaceType() {
assertEquals(String.class, GenericTypeResolver.resolveTypeArgument(MySimpleInterfaceType.class, MyInterfaceType.class));
}
@Test
public void testSimpleCollectionInterfaceType() {
assertEquals(Collection.class, GenericTypeResolver.resolveTypeArgument(MyCollectionInterfaceType.class, MyInterfaceType.class));
}
@Test
public void testSimpleSuperclassType() {
assertEquals(String.class, GenericTypeResolver.resolveTypeArgument(MySimpleSuperclassType.class, MySuperclassType.class));
}
@Test
public void testSimpleCollectionSuperclassType() {
assertEquals(Collection.class, GenericTypeResolver.resolveTypeArgument(MyCollectionSuperclassType.class, MySuperclassType.class));
}
@Test
public void testMethodReturnType() {
assertEquals(Integer.class, GenericTypeResolver.resolveReturnTypeArgument(ReflectionUtils.findMethod(MyTypeWithMethods.class, "integer"), MyInterfaceType.class));
assertEquals(String.class, GenericTypeResolver.resolveReturnTypeArgument(ReflectionUtils.findMethod(MyTypeWithMethods.class, "string"), MyInterfaceType.class));
assertEquals(null, GenericTypeResolver.resolveReturnTypeArgument(ReflectionUtils.findMethod(MyTypeWithMethods.class, "raw"), MyInterfaceType.class));
assertEquals(null, GenericTypeResolver.resolveReturnTypeArgument(ReflectionUtils.findMethod(MyTypeWithMethods.class, "object"), MyInterfaceType.class));
}
@Test
public void testNullIfNotResolvable() {
GenericClass<String> obj = new GenericClass<String>();
assertNull(GenericTypeResolver.resolveTypeArgument(obj.getClass(), GenericClass.class));
}
public interface MyInterfaceType<T> {
}
public class MySimpleInterfaceType implements MyInterfaceType<String> {
}
public class MyCollectionInterfaceType implements MyInterfaceType<Collection<String>> {
}
public abstract class MySuperclassType<T> {
}
public class MySimpleSuperclassType extends MySuperclassType<String> {
}
public class MyCollectionSuperclassType extends MySuperclassType<Collection<String>> {
}
public class MyTypeWithMethods {
public MyInterfaceType<Integer> integer() { return null; }
public MySimpleInterfaceType string() { return null; }
public Object object() { return null; }
@SuppressWarnings("rawtypes")
public MyInterfaceType raw() { return null; }
}
static class GenericClass<T> {
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.util.Collection;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class GenericTypeResolverTests {
@Test
public void testSimpleInterfaceType() {
assertEquals(String.class, GenericTypeResolver.resolveTypeArgument(MySimpleInterfaceType.class, MyInterfaceType.class));
}
@Test
public void testSimpleCollectionInterfaceType() {
assertEquals(Collection.class, GenericTypeResolver.resolveTypeArgument(MyCollectionInterfaceType.class, MyInterfaceType.class));
}
@Test
public void testSimpleSuperclassType() {
assertEquals(String.class, GenericTypeResolver.resolveTypeArgument(MySimpleSuperclassType.class, MySuperclassType.class));
}
@Test
public void testSimpleCollectionSuperclassType() {
assertEquals(Collection.class, GenericTypeResolver.resolveTypeArgument(MyCollectionSuperclassType.class, MySuperclassType.class));
}
@Test
public void testMethodReturnType() {
assertEquals(Integer.class, GenericTypeResolver.resolveReturnTypeArgument(ReflectionUtils.findMethod(MyTypeWithMethods.class, "integer"), MyInterfaceType.class));
assertEquals(String.class, GenericTypeResolver.resolveReturnTypeArgument(ReflectionUtils.findMethod(MyTypeWithMethods.class, "string"), MyInterfaceType.class));
assertEquals(null, GenericTypeResolver.resolveReturnTypeArgument(ReflectionUtils.findMethod(MyTypeWithMethods.class, "raw"), MyInterfaceType.class));
assertEquals(null, GenericTypeResolver.resolveReturnTypeArgument(ReflectionUtils.findMethod(MyTypeWithMethods.class, "object"), MyInterfaceType.class));
}
@Test
public void testNullIfNotResolvable() {
GenericClass<String> obj = new GenericClass<String>();
assertNull(GenericTypeResolver.resolveTypeArgument(obj.getClass(), GenericClass.class));
}
public interface MyInterfaceType<T> {
}
public class MySimpleInterfaceType implements MyInterfaceType<String> {
}
public class MyCollectionInterfaceType implements MyInterfaceType<Collection<String>> {
}
public abstract class MySuperclassType<T> {
}
public class MySimpleSuperclassType extends MySuperclassType<String> {
}
public class MyCollectionSuperclassType extends MySuperclassType<Collection<String>> {
}
public class MyTypeWithMethods {
public MyInterfaceType<Integer> integer() { return null; }
public MySimpleInterfaceType string() { return null; }
public Object object() { return null; }
@SuppressWarnings("rawtypes")
public MyInterfaceType raw() { return null; }
}
static class GenericClass<T> {
}
}

View File

@@ -1,79 +1,79 @@
/*
* Copyright 2006-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
/**
* Unit test checking the behaviour of {@link CachingMetadataReaderFactory under load.
* If the cache is not controller, this test should fail with an out of memory exception around entry
* 5k.
*
* @author Costin Leau
*/
public class CachingMetadataReaderLeakTest {
private static int ITEMS_LOAD = 9999;
private MetadataReaderFactory mrf;
@Before
public void before() {
mrf = new CachingMetadataReaderFactory();
}
@Test
public void testSignificantLoad() throws Exception {
// the biggest public class in the JDK (>60k)
URL url = getClass().getResource("/java/awt/Component.class");
assertThat(url, notNullValue());
// look at a LOT of items
for (int i = 0; i < ITEMS_LOAD; i++) {
Resource resource = new UrlResource(url) {
private int counter = 0;
@Override
public boolean equals(Object obj) {
return (obj == this);
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
};
MetadataReader reader = mrf.getMetadataReader(resource);
assertThat(reader, notNullValue());
}
// useful for profiling to take snapshots
//System.in.read();
}
}
/*
* Copyright 2006-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
/**
* Unit test checking the behaviour of {@link CachingMetadataReaderFactory under load.
* If the cache is not controller, this test should fail with an out of memory exception around entry
* 5k.
*
* @author Costin Leau
*/
public class CachingMetadataReaderLeakTest {
private static int ITEMS_LOAD = 9999;
private MetadataReaderFactory mrf;
@Before
public void before() {
mrf = new CachingMetadataReaderFactory();
}
@Test
public void testSignificantLoad() throws Exception {
// the biggest public class in the JDK (>60k)
URL url = getClass().getResource("/java/awt/Component.class");
assertThat(url, notNullValue());
// look at a LOT of items
for (int i = 0; i < ITEMS_LOAD; i++) {
Resource resource = new UrlResource(url) {
private int counter = 0;
@Override
public boolean equals(Object obj) {
return (obj == this);
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
};
MetadataReader reader = mrf.getMetadataReader(resource);
assertThat(reader, notNullValue());
}
// useful for profiling to take snapshots
//System.in.read();
}
}

View File

@@ -1,98 +1,98 @@
package org.springframework.util;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import junit.framework.TestCase;
/**
* Test case for {@link CompositeIterator}.
*
* @author Erwin Vervaet
*/
public class CompositeIteratorTests extends TestCase {
public void testNoIterators() {
CompositeIterator it = new CompositeIterator();
assertFalse(it.hasNext());
try {
it.next();
fail();
} catch (NoSuchElementException e) {
// expected
}
}
public void testSingleIterator() {
CompositeIterator it = new CompositeIterator();
it.add(Arrays.asList(new String[] { "0", "1" }).iterator());
for (int i = 0; i < 2; i++) {
assertTrue(it.hasNext());
assertEquals(String.valueOf(i), it.next());
}
assertFalse(it.hasNext());
try {
it.next();
fail();
} catch (NoSuchElementException e) {
// expected
}
}
public void testMultipleIterators() {
CompositeIterator it = new CompositeIterator();
it.add(Arrays.asList(new String[] { "0", "1" }).iterator());
it.add(Arrays.asList(new String[] { "2" }).iterator());
it.add(Arrays.asList(new String[] { "3", "4" }).iterator());
for (int i = 0; i < 5; i++) {
assertTrue(it.hasNext());
assertEquals(String.valueOf(i), it.next());
}
assertFalse(it.hasNext());
try {
it.next();
fail();
} catch (NoSuchElementException e) {
// expected
}
}
public void testInUse() {
List list = Arrays.asList(new String[] { "0", "1" });
CompositeIterator it = new CompositeIterator();
it.add(list.iterator());
it.hasNext();
try {
it.add(list.iterator());
fail();
} catch (IllegalStateException e) {
// expected
}
it = new CompositeIterator();
it.add(list.iterator());
it.next();
try {
it.add(list.iterator());
fail();
} catch (IllegalStateException e) {
// expected
}
}
public void testDuplicateIterators() {
List list = Arrays.asList(new String[] { "0", "1" });
Iterator iterator = list.iterator();
CompositeIterator it = new CompositeIterator();
it.add(iterator);
it.add(list.iterator());
try {
it.add(iterator);
fail();
} catch (IllegalArgumentException e) {
// expected
}
}
}
package org.springframework.util;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import junit.framework.TestCase;
/**
* Test case for {@link CompositeIterator}.
*
* @author Erwin Vervaet
*/
public class CompositeIteratorTests extends TestCase {
public void testNoIterators() {
CompositeIterator it = new CompositeIterator();
assertFalse(it.hasNext());
try {
it.next();
fail();
} catch (NoSuchElementException e) {
// expected
}
}
public void testSingleIterator() {
CompositeIterator it = new CompositeIterator();
it.add(Arrays.asList(new String[] { "0", "1" }).iterator());
for (int i = 0; i < 2; i++) {
assertTrue(it.hasNext());
assertEquals(String.valueOf(i), it.next());
}
assertFalse(it.hasNext());
try {
it.next();
fail();
} catch (NoSuchElementException e) {
// expected
}
}
public void testMultipleIterators() {
CompositeIterator it = new CompositeIterator();
it.add(Arrays.asList(new String[] { "0", "1" }).iterator());
it.add(Arrays.asList(new String[] { "2" }).iterator());
it.add(Arrays.asList(new String[] { "3", "4" }).iterator());
for (int i = 0; i < 5; i++) {
assertTrue(it.hasNext());
assertEquals(String.valueOf(i), it.next());
}
assertFalse(it.hasNext());
try {
it.next();
fail();
} catch (NoSuchElementException e) {
// expected
}
}
public void testInUse() {
List list = Arrays.asList(new String[] { "0", "1" });
CompositeIterator it = new CompositeIterator();
it.add(list.iterator());
it.hasNext();
try {
it.add(list.iterator());
fail();
} catch (IllegalStateException e) {
// expected
}
it = new CompositeIterator();
it.add(list.iterator());
it.next();
try {
it.add(list.iterator());
fail();
} catch (IllegalStateException e) {
// expected
}
}
public void testDuplicateIterators() {
List list = Arrays.asList(new String[] { "0", "1" });
Iterator iterator = list.iterator();
CompositeIterator it = new CompositeIterator();
it.add(iterator);
it.add(list.iterator());
try {
it.add(iterator);
fail();
} catch (IllegalArgumentException e) {
// expected
}
}
}