http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/95885781/core/src/main/java/org/apache/tamaya/core/internal/resource/InputStreamResource.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/tamaya/core/internal/resource/InputStreamResource.java b/core/src/main/java/org/apache/tamaya/core/internal/resource/InputStreamResource.java index e956670..11dc8ee 100644 --- a/core/src/main/java/org/apache/tamaya/core/internal/resource/InputStreamResource.java +++ b/core/src/main/java/org/apache/tamaya/core/internal/resource/InputStreamResource.java @@ -27,7 +27,7 @@ import java.util.Objects; * be used if no specific Resource implementation is applicable. * In particular, prefer {@code ByteArrayResource} or any current the * file-based Resource implementations where possible. - * + * <p> * <p>In contrast to other Resource implementations, this is a descriptor * for an <i>already opened</i> resource - therefore returning "true" from * {@code isOpen()}. Do not use it if you need to keep the resource @@ -38,85 +38,87 @@ import java.util.Objects; */ public class InputStreamResource implements Resource { - private final InputStream inputStream; - - private final String description; - - private boolean read = false; - - - /** - * Create a new InputStreamResource. - * @param inputStream the InputStream to use - */ - public InputStreamResource(InputStream inputStream) { - this(inputStream, "resource loaded through InputStream"); - } - - /** - * Create a new InputStreamResource. - * @param inputStream the InputStream to use - * @param description where the InputStream comes from - */ - public InputStreamResource(InputStream inputStream, String description) { - this.inputStream = Objects.requireNonNull(inputStream); - this.description = (description != null ? description : ""); - } - - - /** - * This implementation always returns {@code true}. - */ - @Override - public boolean exists() { - return true; - } - - /** - * This implementation always returns {@code true}. - */ - @Override - public boolean isOpen() { - return true; - } - - /** - * This implementation throws IllegalStateException if attempting to - * read the underlying stream multiple times. - */ - @Override - public InputStream getInputStream() throws IOException { - if (this.read) { - throw new IllegalStateException("InputStream has already been read - " + - "do not use InputStreamResource if a stream needs to be read multiple times"); - } - this.read = true; - return this.inputStream; - } - - /** - * This implementation returns the passed-in description, if any. - */ - public String toString() { - return this.description!=null?this.description:super.toString(); - } - - - /** - * This implementation compares the underlying InputStream. - */ - @Override - public boolean equals(Object obj) { - return (obj == this || - (obj instanceof InputStreamResource && ((InputStreamResource) obj).inputStream.equals(this.inputStream))); - } - - /** - * This implementation returns the hash code current the underlying InputStream. - */ - @Override - public int hashCode() { - return this.inputStream.hashCode(); - } + private final InputStream inputStream; + + private final String description; + + private boolean read = false; + + + /** + * Create a new InputStreamResource. + * + * @param inputStream the InputStream to use + */ + public InputStreamResource(InputStream inputStream) { + this(inputStream, "resource loaded through InputStream"); + } + + /** + * Create a new InputStreamResource. + * + * @param inputStream the InputStream to use + * @param description where the InputStream comes from + */ + public InputStreamResource(InputStream inputStream, String description) { + this.inputStream = Objects.requireNonNull(inputStream); + this.description = (description != null ? description : ""); + } + + + /** + * This implementation always returns {@code true}. + */ + @Override + public boolean exists() { + return true; + } + + /** + * This implementation always returns {@code true}. + */ + @Override + public boolean isOpen() { + return true; + } + + /** + * This implementation throws IllegalStateException if attempting to + * read the underlying stream multiple times. + */ + @Override + public InputStream getInputStream() throws IOException { + if (this.read) { + throw new IllegalStateException("InputStream has already been read - " + + "do not use InputStreamResource if a stream needs to be read multiple times"); + } + this.read = true; + return this.inputStream; + } + + /** + * This implementation returns the passed-in description, if any. + */ + public String toString() { + return this.description != null ? this.description : super.toString(); + } + + + /** + * This implementation compares the underlying InputStream. + */ + @Override + public boolean equals(Object obj) { + return (obj == this || + (obj instanceof InputStreamResource && ((InputStreamResource) obj).inputStream.equals(this.inputStream))); + } + + /** + * This implementation returns the hash code current the underlying InputStream. + */ + @Override + public int hashCode() { + return this.inputStream.hashCode(); + } }
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/95885781/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingDefaultResourceLoader.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingDefaultResourceLoader.java b/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingDefaultResourceLoader.java index c70f04b..cf16762 100644 --- a/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingDefaultResourceLoader.java +++ b/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingDefaultResourceLoader.java @@ -33,107 +33,110 @@ import java.util.Objects; */ class PathMatchingDefaultResourceLoader { - /** Pseudo URL prefix for loading from the class path: "classpath:" */ + /** + * Pseudo URL prefix for loading from the class path: "classpath:" + */ public static final String CLASSPATH_URL_PREFIX = "classpath:"; - private ClassLoader classLoader; - - - /** - * Create a new DefaultResourceLoader. - * <p>ClassLoader access will happen using the thread context class loader - * at the time current this ResourceLoader's initialization. - * @see java.lang.Thread#getContextClassLoader() - */ - public PathMatchingDefaultResourceLoader() { - this.classLoader = ClassUtils.getDefaultClassLoader(); - } - - /** - * Create a new DefaultResourceLoader. - * @param classLoader the ClassLoader to load class path resources with, or {@code null} - * for using the thread context class loader at the time current actual resource access - */ - public PathMatchingDefaultResourceLoader(ClassLoader classLoader) { - this.classLoader = classLoader; - } - - - /** - * Specify the ClassLoader to load class path resources with, or {@code null} - * for using the thread context class loader at the time current actual resource access. - * <p>The default is that ClassLoader access will happen using the thread context - * class loader at the time current this ResourceLoader's initialization. - */ - void setClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader; - } - - /** - * Return the ClassLoader to load class path resources with. - * <p>Will get passed to ClassPathResource's constructor for all - * ClassPathResource objects created by this resource loader. - * @see ClassPathResource - */ - public ClassLoader getClassLoader() { - return (this.classLoader != null ? this.classLoader : ClassUtils.getDefaultClassLoader()); - } - - - public Resource getResource(String location) { - Objects.requireNonNull(location, "Location must not be null"); - if (location.startsWith("/")) { - return getResourceByPath(location); - } - else if (location.startsWith(CLASSPATH_URL_PREFIX)) { - return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader()); - } - else { - try { - // Try to parse the location as a URL... - URL url = new URL(location); - return new UrlResource(url); - } - catch (MalformedURLException ex) { - // No URL -> resolve as resource path. - return getResourceByPath(location); - } - } - } - - /** - * Return a Resource handle for the resource at the given path. - * <p>The default implementation supports class path locations. This should - * be appropriate for standalone implementations but can be overridden, - * e.g. for implementations targeted at a Servlet container. - * @param path the path to the resource - * @return the corresponding Resource handle - * @see ClassPathResource - */ - protected Resource getResourceByPath(String path) { - return new ClassPathContextResource(path, getClassLoader()); - } - - - /** - * ClassPathResource that explicitly expresses a context-relative path - * through implementing the ContextResource interface. - */ - protected static class ClassPathContextResource extends ClassPathResource { - - public ClassPathContextResource(String path, ClassLoader classLoader) { - super(path, classLoader); - } - - public String getPathWithinContext() { - return getPath(); - } - - @Override - public Resource createRelative(String relativePath) { - String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath); - return new ClassPathContextResource(pathToUse, getClassLoader()); - } - } + private ClassLoader classLoader; + + + /** + * Create a new DefaultResourceLoader. + * <p>ClassLoader access will happen using the thread context class loader + * at the time current this ResourceLoader's initialization. + * + * @see java.lang.Thread#getContextClassLoader() + */ + public PathMatchingDefaultResourceLoader() { + this.classLoader = ClassUtils.getDefaultClassLoader(); + } + + /** + * Create a new DefaultResourceLoader. + * + * @param classLoader the ClassLoader to load class path resources with, or {@code null} + * for using the thread context class loader at the time current actual resource access + */ + public PathMatchingDefaultResourceLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + } + + + /** + * Specify the ClassLoader to load class path resources with, or {@code null} + * for using the thread context class loader at the time current actual resource access. + * <p>The default is that ClassLoader access will happen using the thread context + * class loader at the time current this ResourceLoader's initialization. + */ + void setClassLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + } + + /** + * Return the ClassLoader to load class path resources with. + * <p>Will get passed to ClassPathResource's constructor for all + * ClassPathResource objects created by this resource loader. + * + * @see ClassPathResource + */ + public ClassLoader getClassLoader() { + return (this.classLoader != null ? this.classLoader : ClassUtils.getDefaultClassLoader()); + } + + + public Resource getResource(String location) { + Objects.requireNonNull(location, "Location must not be null"); + if (location.startsWith("/")) { + return getResourceByPath(location); + } else if (location.startsWith(CLASSPATH_URL_PREFIX)) { + return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader()); + } else { + try { + // Try to parse the location as a URL... + URL url = new URL(location); + return new UrlResource(url); + } catch (MalformedURLException ex) { + // No URL -> resolve as resource path. + return getResourceByPath(location); + } + } + } + + /** + * Return a Resource handle for the resource at the given path. + * <p>The default implementation supports class path locations. This should + * be appropriate for standalone implementations but can be overridden, + * e.g. for implementations targeted at a Servlet container. + * + * @param path the path to the resource + * @return the corresponding Resource handle + * @see ClassPathResource + */ + protected Resource getResourceByPath(String path) { + return new ClassPathContextResource(path, getClassLoader()); + } + + + /** + * ClassPathResource that explicitly expresses a context-relative path + * through implementing the ContextResource interface. + */ + protected static class ClassPathContextResource extends ClassPathResource { + + public ClassPathContextResource(String path, ClassLoader classLoader) { + super(path, classLoader); + } + + public String getPathWithinContext() { + return getPath(); + } + + @Override + public Resource createRelative(String relativePath) { + String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath); + return new ClassPathContextResource(pathToUse, getClassLoader()); + } + } } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/95885781/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingResourcePatternResolver.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingResourcePatternResolver.java b/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingResourcePatternResolver.java index 005617b..b4cee0d 100644 --- a/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingResourcePatternResolver.java +++ b/core/src/main/java/org/apache/tamaya/core/internal/resource/PathMatchingResourcePatternResolver.java @@ -48,9 +48,9 @@ import java.util.stream.Collectors; * internal Ant-style regular expressions (matched using Spring's * {@code org.springframework.util.AntPathMatcher} utility). * Both current the latter are effectively wildcards. - * + * <p> * <p><b>No Wildcards:</b> - * + * <p> * <p>In the simple case, if the specified location path does not start with the * {@code "classpath*:}" prefix, and does not contain a PathMatcher pattern, * this resolver will simply return a single resource via a @@ -60,9 +60,9 @@ import java.util.stream.Collectors; * such as "{@code /WEB-INF/context.xml}". The latter will resolve in a * fashion specific to the underlying {@code ResourceLoader} (e.g. * {@code ServletContextResource} for a {@code WebApplicationContext}). - * + * <p> * <p><b>Ant-style Patterns:</b> - * + * <p> * <p>When the path location contains an Ant-style pattern, e.g.: * <pre class="code"> * /WEB-INF/*-context.xml @@ -79,13 +79,13 @@ import java.util.stream.Collectors; * either gets a {@code java.net.JarURLConnection} from it, or manually parses * the jar URL, and then traverses the contents current the jar file, to resolve the * wildcards. - * + * <p> * <p><b>Implications on portability:</b> - * + * <p> * <p>If the specified path is already a file URL (either explicitly, or * implicitly because the base {@code ResourceLoader} is a filesystem one, * then wildcarding is guaranteed to work in a completely portable fashion. - * + * <p> * <p>If the specified path is a classpath location, then the resolver must * obtain the last non-wildcard path segment URL via a * {@code Classloader.getResource()} call. Since this is just a @@ -95,7 +95,7 @@ import java.util.stream.Collectors; * the directory, where the classpath resource resolves to a filesystem * location, or a jar URL current some sort, where the classpath resource resolves * to a jar location. Still, there is a portability concern on this operation. - * + * <p> * <p>If a jar URL is obtained for the last non-wildcard segment, the resolver * must be able to get a {@code java.net.JarURLConnection} from it, or * manually parse the jar URL, to be able to walk the contents current the jar, @@ -103,9 +103,9 @@ import java.util.stream.Collectors; * fail in others, and it is strongly recommended that the wildcard * resolution current resources coming from jars be thoroughly tested in your * specific environment before you rely on it. - * + * <p> * <p><b>{@code classpath*:} Prefix:</b> - * + * <p> * <p>There is special support for retrieving multiple class path resources with * the same name, via the "{@code classpath*:}" prefix. For example, * "{@code classpath*:META-INF/beans.xml}" will find all "beans.xml" @@ -113,7 +113,7 @@ import java.util.stream.Collectors; * This is particularly useful for autodetecting config files current the same name * at the same location within each jar file. Internally, this happens via a * {@code ClassLoader.getResources()} call, and is completely portable. - * + * <p> * <p>The "classpath*:" prefix can also be combined with a PathMatcher pattern in * the rest current the location path, for example "classpath*:META-INF/*-beans.xml". * In this case, the resolution strategy is fairly simple: a @@ -121,9 +121,9 @@ import java.util.stream.Collectors; * path segment to get all the matching resources in the class loader hierarchy, * and then off each resource the same PathMatcher resolution strategy described * above is used for the wildcard subpath. - * + * <p> * <p><b>Other notes:</b> - * + * <p> * <p><b>WARNING:</b> Note that "{@code classpath*:}" when combined with * Ant-style patterns will only work reliably with at least one root directory * before the pattern starts, unless the actual target files reside in the file @@ -132,16 +132,16 @@ import java.util.stream.Collectors; * root current expanded directories. This originates from a limitation in the JDK's * {@code ClassLoader.getResources()} method which only returns file system * locations for a passed-in empty String (indicating potential roots to search). - * + * <p> * <p><b>WARNING:</b> Ant-style patterns with "classpath:" resources are not * guaranteed to find matching resources if the root package to search is available * in multiple class path locations. This is because a resource such as * <pre class="code"> - * com/mycompany/package1/service-context.xml + * com/mycompany/package1/service-context.xml * </pre> * may be in only one location, but when a path such as * <pre class="code"> - * classpath:com/mycompany/**/service-context.xml + * classpath:com/mycompany/**/service-context.xml * </pre> * is used to try to resolve it, the resolver will work off the (first) URL * returned by {@code getResource("com/mycompany");}. If this base package @@ -154,10 +154,10 @@ import java.util.stream.Collectors; * @author Colin Sampaleanu * @author Marius Bogoevici * @author Costin Leau - * @since 1.0.2 * @see ClassLoader#getResources(String) + * @since 1.0.2 */ -public final class PathMatchingResourcePatternResolver{ +public final class PathMatchingResourcePatternResolver { private static final Logger logger = Logger.getLogger(PathMatchingResourcePatternResolver.class.getName()); private static final java.lang.String CLASSPATH_ALL_URL_PREFIX = "classpath:"; @@ -171,8 +171,7 @@ public final class PathMatchingResourcePatternResolver{ PathMatchingResourcePatternResolver.class.getClassLoader()); equinoxResolveMethod = fileLocatorClass.getMethod("resolve", URL.class); logger.finest("Found Equinox FileLocator for OSGi bundle URL resolution"); - } - catch (Throwable ex) { + } catch (Throwable ex) { equinoxResolveMethod = null; } } @@ -184,7 +183,7 @@ public final class PathMatchingResourcePatternResolver{ private static Map<ClassLoader, PathMatchingResourcePatternResolver> resolvers = new ConcurrentHashMap<>(); - public static PathMatchingResourcePatternResolver of(ClassLoader loader){ + public static PathMatchingResourcePatternResolver of(ClassLoader loader) { return resolvers.computeIfAbsent(loader, PathMatchingResourcePatternResolver::new); } @@ -198,9 +197,10 @@ public final class PathMatchingResourcePatternResolver{ /** * Create a new PathMatchingResourcePatternResolver with a DefaultResourceLoader. + * * @param classLoader the ClassLoader to load classpath resources with, - * or {@code null} for using the thread context class loader - * at the time current actual resource access + * or {@code null} for using the thread context class loader + * at the time current actual resource access * @see PathMatchingDefaultResourceLoader */ public PathMatchingResourcePatternResolver(ClassLoader classLoader) { @@ -229,23 +229,20 @@ public final class PathMatchingResourcePatternResolver{ if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) { // a class path resource pattern return findPathMatchingResources(locationPattern); - } - else { + } else { // all class path resources with the given name return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length())); } - } - else { + } else { // Only look for a pattern after a prefix here // (to not get fooled by a pattern symbol in a strange prefix). int prefixEnd = locationPattern.indexOf(':') + 1; if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) { // a file pattern return findPathMatchingResources(locationPattern); - } - else { + } else { // a single resource with the given name - return new Resource[] {this.resourceLoader.getResource(locationPattern)}; + return new Resource[]{this.resourceLoader.getResource(locationPattern)}; } } } @@ -253,6 +250,7 @@ public final class PathMatchingResourcePatternResolver{ /** * Find all class location resources with the given location via the ClassLoader. * Delegates to {@link #doFindAllClassPathResources(String)}. + * * @param location the absolute path within the classpath * @return the result as Resource array * @throws IOException in case current I/O errors @@ -271,6 +269,7 @@ public final class PathMatchingResourcePatternResolver{ /** * Find all class location resources with the given path via the ClassLoader. * Called by {@link #findAllClassPathResources(String)}. + * * @param path the absolute path within the classpath (never a leading slash) * @return a mutable Set current matching Resource instances */ @@ -293,6 +292,7 @@ public final class PathMatchingResourcePatternResolver{ /** * Convert the given URL as returned from the ClassLoader into a {@link Resource}. * <p>The default implementation simply creates a {@link UrlResource} instance. + * * @param url a URL as returned from the ClassLoader * @return the corresponding Resource object * @see java.lang.ClassLoader#getResources @@ -305,8 +305,9 @@ public final class PathMatchingResourcePatternResolver{ /** * Search all {@link URLClassLoader} URLs for jar file references and add them to the * given set current resources in the form current pointers to the root current the jar file content. + * * @param classLoader the ClassLoader to search (including its ancestors) - * @param result the set current resources to add jar roots to + * @param result the set current resources to add jar roots to */ protected void addAllClassLoaderJarRoots(ClassLoader classLoader, Set<Resource> result) { if (classLoader instanceof URLClassLoader) { @@ -319,15 +320,13 @@ public final class PathMatchingResourcePatternResolver{ if (jarResource.exists()) { result.add(jarResource); } - } - catch (MalformedURLException ex) { + } catch (MalformedURLException ex) { logger.finest(() -> "Cannot search for matching files underneath [" + url + "] because it cannot be converted to a valid 'jar:' URL: " + ex.getMessage()); } } } - } - catch (Exception ex) { + } catch (Exception ex) { logger.finest(() -> "Cannot introspect jar files since ClassLoader [" + classLoader + "] does not support 'getURLs()': " + ex); } @@ -335,8 +334,7 @@ public final class PathMatchingResourcePatternResolver{ if (classLoader != null) { try { addAllClassLoaderJarRoots(classLoader.getParent(), result); - } - catch (Exception ex) { + } catch (Exception ex) { logger.finest(() -> "Cannot introspect jar files in parent ClassLoader since [" + classLoader + "] does not support 'getParent()': " + ex); } @@ -347,6 +345,7 @@ public final class PathMatchingResourcePatternResolver{ * Find all resources that match the given location pattern via the * Ant-style PathMatcher. Supports resources in jar files and zip files * and in the file system. + * * @param locationPattern the location pattern to match * @return the result as Resource array * @throws IOException in case current I/O errors @@ -362,11 +361,9 @@ public final class PathMatchingResourcePatternResolver{ rootDirResource = resolveRootDirResource(rootDirResource); if (rootDirResource.toURL().getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirResource, subPattern, getPathMatcher())); - } - else if (isJarResource(rootDirResource)) { + } else if (isJarResource(rootDirResource)) { result.addAll(doFindPathMatchingJarResources(rootDirResource, subPattern)); - } - else { + } else { result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern)); } } @@ -382,6 +379,7 @@ public final class PathMatchingResourcePatternResolver{ * remainder current the location as pattern. * <p>Will return "/WEB-INF/" for the pattern "/WEB-INF/*.xml", * for example. + * * @param location the location to check * @return the part current the location that denotes the root directory * @see #retrieveMatchingFiles @@ -403,6 +401,7 @@ public final class PathMatchingResourcePatternResolver{ * <p>The default implementation detects an Equinox OSGi "bundleresource:" * / "bundleentry:" URL and resolves it into a standard jar file URL that * can be traversed using Spring's standard jar file traversal algorithm. + * * @param original the resource to resolve * @return the resolved resource (may be identical to the passed-in resource) * @throws IOException in case current resolution failure @@ -427,8 +426,9 @@ public final class PathMatchingResourcePatternResolver{ * <p>The default implementation checks against the URL protocols * "jar", "zip" and "wsjar" (the latter are used by BEA WebLogic Server * and IBM WebSphere, respectively, but can be treated like jar files). + * * @param resource the resource handle to check - * (usually the root directory to start path matching from) + * (usually the root directory to start path matching from) * @see #doFindPathMatchingJarResources * @see ResourceUtils#isJarURL */ @@ -439,8 +439,9 @@ public final class PathMatchingResourcePatternResolver{ /** * Find all resources in jar files that match the given location pattern * via the Ant-style PathMatcher. + * * @param rootDirResource the root directory as Resource - * @param subPattern the sub pattern to match (below the root directory) + * @param subPattern the sub pattern to match (below the root directory) * @return a mutable Set current matching Resource instances * @throws IOException in case current I/O errors * @see java.net.JarURLConnection @@ -462,8 +463,7 @@ public final class PathMatchingResourcePatternResolver{ jarFileUrl = jarCon.getJarFileURL().toExternalForm(); JarEntry jarEntry = jarCon.getJarEntry(); rootEntryPath = (jarEntry != null ? jarEntry.getName() : ""); - } - else { + } else { // No JarURLConnection -> need to resort to URL file parsing. // We'll assume URLs current the format "jar:path!/entry", with the protocol // being arbitrary as long as following the entry format. @@ -474,8 +474,7 @@ public final class PathMatchingResourcePatternResolver{ jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length()); jarFile = getJarFile(jarFileUrl); - } - else { + } else { jarFile = new JarFile(urlFile); jarFileUrl = urlFile; rootEntryPath = ""; @@ -491,7 +490,7 @@ public final class PathMatchingResourcePatternResolver{ rootEntryPath = rootEntryPath + "/"; } Set<Resource> result = new LinkedHashSet<>(8); - for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { + for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); if (entryPath.startsWith(rootEntryPath)) { @@ -502,8 +501,7 @@ public final class PathMatchingResourcePatternResolver{ } } return result; - } - finally { + } finally { // Close jar file, but only if freshly obtained - // not from JarURLConnection, which might cache the file reference. if (newJarFile) { @@ -519,13 +517,11 @@ public final class PathMatchingResourcePatternResolver{ if (jarFileUrl.startsWith(ResourceUtils.FILE_URL_PREFIX)) { try { return new JarFile(ResourceUtils.toURI(jarFileUrl).getSchemeSpecificPart()); - } - catch (URISyntaxException ex) { + } catch (URISyntaxException ex) { // Fallback for URLs that are not valid URIs (should hardly ever happen). return new JarFile(jarFileUrl.substring(ResourceUtils.FILE_URL_PREFIX.length())); } - } - else { + } else { return new JarFile(jarFileUrl); } } @@ -533,8 +529,9 @@ public final class PathMatchingResourcePatternResolver{ /** * Find all resources in the file system that match the given location pattern * via the Ant-style PathMatcher. + * * @param rootDirResource the root directory as Resource - * @param subPattern the sub pattern to match (below the root directory) + * @param subPattern the sub pattern to match (below the root directory) * @return a mutable Set current matching Resource instances * @throws IOException in case current I/O errors * @see #retrieveMatchingFiles @@ -545,10 +542,9 @@ public final class PathMatchingResourcePatternResolver{ File rootDir; try { rootDir = rootDirResource.toFile().getAbsoluteFile(); - } - catch (IOException ex) { + } catch (IOException ex) { logger.log(Level.WARNING, ex, () -> "Cannot search for matching files underneath " + rootDirResource + - " because it does not correspond to a directory in the file system"); + " because it does not correspond to a directory in the file system"); return Collections.emptySet(); } return doFindMatchingFileSystemResources(rootDir, subPattern); @@ -557,7 +553,8 @@ public final class PathMatchingResourcePatternResolver{ /** * Find all resources in the file system that match the given location pattern * via the Ant-style PathMatcher. - * @param rootDir the root directory in the file system + * + * @param rootDir the root directory in the file system * @param subPattern the sub pattern to match (below the root directory) * @return a mutable Set current matching Resource instances * @throws IOException in case current I/O errors @@ -574,9 +571,10 @@ public final class PathMatchingResourcePatternResolver{ /** * Retrieve files that match the given path pattern, * checking the given directory and its subdirectories. + * * @param rootDir the directory to start from * @param pattern the pattern to match against, - * relative to the root directory + * relative to the root directory * @return a mutable Set current matching Resource instances * @throws IOException if directory contents could not be retrieved */ @@ -609,10 +607,11 @@ public final class PathMatchingResourcePatternResolver{ /** * Recursively retrieve files that match the given pattern, * adding them to the given result list. + * * @param fullPattern the pattern to match against, - * with prepended root directory path - * @param dir the current directory - * @param result the Set current matching File instances to add to + * with prepended root directory path + * @param dir the current directory + * @param result the Set current matching File instances to add to * @throws IOException if directory contents could not be retrieved */ protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException { @@ -627,10 +626,9 @@ public final class PathMatchingResourcePatternResolver{ String currPath = StringUtils.replace(content.getAbsolutePath(), File.separator, "/"); if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) { if (!content.canRead()) { - logger.finest(() -> "Skipping subdirectory [" + dir.getAbsolutePath() + - "] because the application is not allowed to read the directory"); - } - else { + logger.finest(() -> "Skipping subdirectory [" + dir.getAbsolutePath() + + "] because the application is not allowed to read the directory"); + } else { doRetrieveMatchingFiles(fullPattern, content, result); } } @@ -684,19 +682,15 @@ public final class PathMatchingResourcePatternResolver{ if (methodName.equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); - } - else if (methodName.equals("hashCode")) { + } else if (methodName.equals("hashCode")) { return System.identityHashCode(proxy); } - } - else if ("getAttributes".equals(methodName)) { + } else if ("getAttributes".equals(methodName)) { return getAttributes(); - } - else if ("visit".equals(methodName)) { + } else if ("visit".equals(methodName)) { visit(args[0]); return null; - } - else if ("toString".equals(methodName)) { + } else if ("toString".equals(methodName)) { return toString(); } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/95885781/core/src/main/java/org/apache/tamaya/core/internal/resource/ReflectionUtils.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/tamaya/core/internal/resource/ReflectionUtils.java b/core/src/main/java/org/apache/tamaya/core/internal/resource/ReflectionUtils.java index 391f7e8..a638238 100644 --- a/core/src/main/java/org/apache/tamaya/core/internal/resource/ReflectionUtils.java +++ b/core/src/main/java/org/apache/tamaya/core/internal/resource/ReflectionUtils.java @@ -25,168 +25,177 @@ import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; /** -* Simple utility class for working with the reflection API and handling -* reflection exceptions. -* -* <p>Only intended for internal use. -* -* @author Juergen Hoeller -* @author Rob Harrop -* @author Rod Johnson -* @author Costin Leau -* @author Sam Brannen -* @author Chris Beams -* @since 1.2.2 -*/ + * Simple utility class for working with the reflection API and handling + * reflection exceptions. + * <p> + * <p>Only intended for internal use. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @author Rod Johnson + * @author Costin Leau + * @author Sam Brannen + * @author Chris Beams + * @since 1.2.2 + */ public abstract class ReflectionUtils { - /** - * Cache for {@link Class#getDeclaredMethods()}, allowing for fast resolution. - */ - private static final Map<Class<?>, Method[]> declaredMethodsCache = - new ConcurrentHashMap<>(256); + /** + * Cache for {@link Class#getDeclaredMethods()}, allowing for fast resolution. + */ + private static final Map<Class<?>, Method[]> DECLARED_METHODS_CACHE = + new ConcurrentHashMap<>(256); - /** - * Attempt to find a {@link Field field} on the supplied {@link Class} with the - * supplied {@code name}. Searches all superclasses up to {@link Object}. - * @param clazz the class to introspect - * @param name the name current the field - * @return the corresponding Field object, or {@code null} if not found - */ - public static Field findField(Class<?> clazz, String name) { - return findField(clazz, name, null); - } + /** + * Attempt to find a {@link Field field} on the supplied {@link Class} with the + * supplied {@code name}. Searches all superclasses up to {@link Object}. + * + * @param clazz the class to introspect + * @param name the name current the field + * @return the corresponding Field object, or {@code null} if not found + */ + public static Field findField(Class<?> clazz, String name) { + return findField(clazz, name, null); + } - /** - * Attempt to find a {@link Field field} on the supplied {@link Class} with the - * supplied {@code name} and/or {@link Class type}. Searches all superclasses - * up to {@link Object}. - * @param clazz the class to introspect - * @param name the name current the field (may be {@code null} if type is specified) - * @param type the type current the field (may be {@code null} if name is specified) - * @return the corresponding Field object, or {@code null} if not found - */ - public static Field findField(Class<?> clazz, String name, Class<?> type) { - Objects.requireNonNull(clazz, "Class must not be null"); - if(name == null && type == null) throw new IllegalArgumentException("Either name or type current the field must be specified"); - Class<?> searchType = clazz; - while (!Object.class.equals(searchType) && searchType != null) { - Field[] fields = searchType.getDeclaredFields(); - for (Field field : fields) { - if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) { - return field; - } - } - searchType = searchType.getSuperclass(); - } - return null; - } + /** + * Attempt to find a {@link Field field} on the supplied {@link Class} with the + * supplied {@code name} and/or {@link Class type}. Searches all superclasses + * up to {@link Object}. + * + * @param clazz the class to introspect + * @param name the name current the field (may be {@code null} if type is specified) + * @param type the type current the field (may be {@code null} if name is specified) + * @return the corresponding Field object, or {@code null} if not found + */ + public static Field findField(Class<?> clazz, String name, Class<?> type) { + Objects.requireNonNull(clazz, "Class must not be null"); + if (name == null && type == null) { + throw new IllegalArgumentException("Either name or type current the field must be specified"); + } + Class<?> searchType = clazz; + while (!Object.class.equals(searchType) && searchType != null) { + Field[] fields = searchType.getDeclaredFields(); + for (Field field : fields) { + if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) { + return field; + } + } + searchType = searchType.getSuperclass(); + } + return null; + } - /** - * Attempt to find a {@link Method} on the supplied class with the supplied name - * and no parameters. Searches all superclasses up to {@code Object}. - * <p>Returns {@code null} if no {@link Method} can be found. - * @param clazz the class to introspect - * @param name the name current the method - * @return the Method object, or {@code null} if none found - */ - public static Method findMethod(Class<?> clazz, String name) { - return findMethod(clazz, name, new Class<?>[0]); - } + /** + * Attempt to find a {@link Method} on the supplied class with the supplied name + * and no parameters. Searches all superclasses up to {@code Object}. + * <p>Returns {@code null} if no {@link Method} can be found. + * + * @param clazz the class to introspect + * @param name the name current the method + * @return the Method object, or {@code null} if none found + */ + public static Method findMethod(Class<?> clazz, String name) { + return findMethod(clazz, name, new Class<?>[0]); + } - /** - * Attempt to find a {@link Method} on the supplied class with the supplied name - * and parameter types. Searches all superclasses up to {@code Object}. - * <p>Returns {@code null} if no {@link Method} can be found. - * @param clazz the class to introspect - * @param name the name current the method - * @param paramTypes the parameter types current the method - * (may be {@code null} to indicate any signature) - * @return the Method object, or {@code null} if none found - */ - public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) { - Objects.requireNonNull(clazz, "Class must not be null"); - Objects.requireNonNull(name, "Method name must not be null"); - Class<?> searchType = clazz; - while (searchType != null) { - Method[] methods = (searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType)); - for (Method method : methods) { - if (name.equals(method.getName()) && - (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) { - return method; - } - } - searchType = searchType.getSuperclass(); - } - return null; - } + /** + * Attempt to find a {@link Method} on the supplied class with the supplied name + * and parameter types. Searches all superclasses up to {@code Object}. + * <p>Returns {@code null} if no {@link Method} can be found. + * + * @param clazz the class to introspect + * @param name the name current the method + * @param paramTypes the parameter types current the method + * (may be {@code null} to indicate any signature) + * @return the Method object, or {@code null} if none found + */ + public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) { + Objects.requireNonNull(clazz, "Class must not be null"); + Objects.requireNonNull(name, "Method name must not be null"); + Class<?> searchType = clazz; + while (searchType != null) { + Method[] methods = (searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType)); + for (Method method : methods) { + if (name.equals(method.getName()) && + (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) { + return method; + } + } + searchType = searchType.getSuperclass(); + } + return null; + } - /** - * Handle the given reflection exception. Should only be called if no - * checked exception is expected to be thrown by the target method. - * <p>Throws the underlying RuntimeException or Error in case current an - * InvocationTargetException with such a root cause. Throws an - * IllegalStateException with an appropriate message else. - * @param ex the reflection exception to handle - */ - public static void handleReflectionException(Exception ex) { - if (ex instanceof NoSuchMethodException) { - throw new IllegalStateException("Method not found: " + ex.getMessage()); - } - if (ex instanceof IllegalAccessException) { - throw new IllegalStateException("Could not access method: " + ex.getMessage()); - } - if (ex instanceof InvocationTargetException) { - handleInvocationTargetException((InvocationTargetException) ex); - } - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; - } - throw new UndeclaredThrowableException(ex); - } + /** + * Handle the given reflection exception. Should only be called if no + * checked exception is expected to be thrown by the target method. + * <p>Throws the underlying RuntimeException or Error in case current an + * InvocationTargetException with such a root cause. Throws an + * IllegalStateException with an appropriate message else. + * + * @param ex the reflection exception to handle + */ + public static void handleReflectionException(Exception ex) { + if (ex instanceof NoSuchMethodException) { + throw new IllegalStateException("Method not found: " + ex.getMessage()); + } + if (ex instanceof IllegalAccessException) { + throw new IllegalStateException("Could not access method: " + ex.getMessage()); + } + if (ex instanceof InvocationTargetException) { + handleInvocationTargetException((InvocationTargetException) ex); + } + if (ex instanceof RuntimeException) { + throw (RuntimeException) ex; + } + throw new UndeclaredThrowableException(ex); + } - /** - * Handle the given invocation target exception. Should only be called if no - * checked exception is expected to be thrown by the target method. - * <p>Throws the underlying RuntimeException or Error in case current such a root - * cause. Throws an IllegalStateException else. - * @param ex the invocation target exception to handle - */ - public static void handleInvocationTargetException(InvocationTargetException ex) { - rethrowRuntimeException(ex.getTargetException()); - } + /** + * Handle the given invocation target exception. Should only be called if no + * checked exception is expected to be thrown by the target method. + * <p>Throws the underlying RuntimeException or Error in case current such a root + * cause. Throws an IllegalStateException else. + * + * @param ex the invocation target exception to handle + */ + public static void handleInvocationTargetException(InvocationTargetException ex) { + rethrowRuntimeException(ex.getTargetException()); + } - /** - * Rethrow the given {@link Throwable exception}, which is presumably the - * <em>target exception</em> current an {@link InvocationTargetException}. Should - * only be called if no checked exception is expected to be thrown by the - * target method. - * <p>Rethrows the underlying exception cast to an {@link RuntimeException} or - * {@link Error} if appropriate; otherwise, throws an - * {@link IllegalStateException}. - * @param ex the exception to rethrow - * @throws RuntimeException the rethrown exception - */ - public static void rethrowRuntimeException(Throwable ex) { - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; - } - if (ex instanceof Error) { - throw (Error) ex; - } - throw new UndeclaredThrowableException(ex); - } + /** + * Rethrow the given {@link Throwable exception}, which is presumably the + * <em>target exception</em> current an {@link InvocationTargetException}. Should + * only be called if no checked exception is expected to be thrown by the + * target method. + * <p>Rethrows the underlying exception cast to an {@link RuntimeException} or + * {@link Error} if appropriate; otherwise, throws an + * {@link IllegalStateException}. + * + * @param ex the exception to rethrow + * @throws RuntimeException the rethrown exception + */ + public static void rethrowRuntimeException(Throwable ex) { + if (ex instanceof RuntimeException) { + throw (RuntimeException) ex; + } + if (ex instanceof Error) { + throw (Error) ex; + } + throw new UndeclaredThrowableException(ex); + } - /** - * This method retrieves {@link Class#getDeclaredMethods()} from a local cache - * in order to avoid the JVM's SecurityManager check and defensive array copying. - */ - private static Method[] getDeclaredMethods(Class<?> clazz) { - Method[] result = declaredMethodsCache.get(clazz); - if (result == null) { - result = clazz.getDeclaredMethods(); - declaredMethodsCache.put(clazz, result); - } - return result; - } + /** + * This method retrieves {@link Class#getDeclaredMethods()} from a local cache + * in order to avoid the JVM's SecurityManager check and defensive array copying. + */ + private static Method[] getDeclaredMethods(Class<?> clazz) { + Method[] result = DECLARED_METHODS_CACHE.get(clazz); + if (result == null) { + result = clazz.getDeclaredMethods(); + DECLARED_METHODS_CACHE.put(clazz, result); + } + return result; + } } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/95885781/core/src/main/java/org/apache/tamaya/core/internal/resource/ResourceUtils.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/tamaya/core/internal/resource/ResourceUtils.java b/core/src/main/java/org/apache/tamaya/core/internal/resource/ResourceUtils.java index a9979f1..b79da71 100644 --- a/core/src/main/java/org/apache/tamaya/core/internal/resource/ResourceUtils.java +++ b/core/src/main/java/org/apache/tamaya/core/internal/resource/ResourceUtils.java @@ -25,233 +25,264 @@ import java.net.URLConnection; import java.util.Objects; /** -* Utility methods for resolving resource locations to files in the -* file system. Mainly for internal use within the framework. -* -* <p>Consider using Spring's Resource abstraction in the core package -* for handling all kinds current file resources in a uniform manner. -* {@code org.springframework.core.io.ResourceLoader}'s {@code getResource()} -* method can resolve any location to a {@code org.springframework.core.io.Resource} -* object, which in turn allows one to obtain a {@code java.io.File} in the -* file system through its {@code getFile()} method. -* -* <p>The main reason for these utility methods for resource location handling -* is to support {@code Log4jConfigurer}, which must be able to resolve -* resource locations <i>before the logging system has been initialized</i>. -* Spring's {@code Resource} abstraction in the core package, on the other hand, -* already expects the logging system to be available. -* -* @author Juergen Hoeller -* @since 1.1.5 -*/ + * Utility methods for resolving resource locations to files in the + * file system. Mainly for internal use within the framework. + * <p> + * <p>Consider using Spring's Resource abstraction in the core package + * for handling all kinds current file resources in a uniform manner. + * {@code org.springframework.core.io.ResourceLoader}'s {@code getResource()} + * method can resolve any location to a {@code org.springframework.core.io.Resource} + * object, which in turn allows one to obtain a {@code java.io.File} in the + * file system through its {@code getFile()} method. + * <p> + * <p>The main reason for these utility methods for resource location handling + * is to support {@code Log4jConfigurer}, which must be able to resolve + * resource locations <i>before the logging system has been initialized</i>. + * Spring's {@code Resource} abstraction in the core package, on the other hand, + * already expects the logging system to be available. + * + * @author Juergen Hoeller + * @since 1.1.5 + */ final class ResourceUtils { - /** URL prefix for loading from the file system: "file:" */ - public static final String FILE_URL_PREFIX = "file:"; + /** + * URL prefix for loading from the file system: "file:" + */ + public static final String FILE_URL_PREFIX = "file:"; - /** URL prefix for loading from the file system: "jar:" */ - public static final String JAR_URL_PREFIX = "jar:"; + /** + * URL prefix for loading from the file system: "jar:" + */ + public static final String JAR_URL_PREFIX = "jar:"; - /** URL protocol for a file in the file system: "file" */ - public static final String URL_PROTOCOL_FILE = "file"; + /** + * URL protocol for a file in the file system: "file" + */ + public static final String URL_PROTOCOL_FILE = "file"; - /** URL protocol for an entry from a jar file: "jar" */ - public static final String URL_PROTOCOL_JAR = "jar"; + /** + * URL protocol for an entry from a jar file: "jar" + */ + public static final String URL_PROTOCOL_JAR = "jar"; - /** URL protocol for an entry from a zip file: "zip" */ - public static final String URL_PROTOCOL_ZIP = "zip"; + /** + * URL protocol for an entry from a zip file: "zip" + */ + public static final String URL_PROTOCOL_ZIP = "zip"; - /** URL protocol for an entry from a WebSphere jar file: "wsjar" */ - public static final String URL_PROTOCOL_WSJAR = "wsjar"; + /** + * URL protocol for an entry from a WebSphere jar file: "wsjar" + */ + public static final String URL_PROTOCOL_WSJAR = "wsjar"; - /** URL protocol for an entry from a JBoss jar file: "vfszip" */ - public static final String URL_PROTOCOL_VFSZIP = "vfszip"; + /** + * URL protocol for an entry from a JBoss jar file: "vfszip" + */ + public static final String URL_PROTOCOL_VFSZIP = "vfszip"; - /** URL protocol for a JBoss file system resource: "vfsfile" */ - public static final String URL_PROTOCOL_VFSFILE = "vfsfile"; + /** + * URL protocol for a JBoss file system resource: "vfsfile" + */ + public static final String URL_PROTOCOL_VFSFILE = "vfsfile"; - /** URL protocol for a general JBoss VFS resource: "vfs" */ - public static final String URL_PROTOCOL_VFS = "vfs"; + /** + * URL protocol for a general JBoss VFS resource: "vfs" + */ + public static final String URL_PROTOCOL_VFS = "vfs"; - /** File extension for a regular jar file: ".jar" */ - public static final String JAR_FILE_EXTENSION = ".jar"; + /** + * File extension for a regular jar file: ".jar" + */ + public static final String JAR_FILE_EXTENSION = ".jar"; - /** Separator between JAR URL and file path within the JAR: "!/" */ - public static final String JAR_URL_SEPARATOR = "!/"; + /** + * Separator between JAR URL and file path within the JAR: "!/" + */ + public static final String JAR_URL_SEPARATOR = "!/"; /** * Singleton constructor. */ - private ResourceUtils(){} + private ResourceUtils() { + } - /** - * Resolve the given resource URL to a {@code java.io.File}, - * i.e. to a file in the file system. - * @param resourceUrl the resource URL to resolve - * @return a corresponding File object - * @throws FileNotFoundException if the URL cannot be resolved to - * a file in the file system - */ - public static File getFile(URL resourceUrl) throws FileNotFoundException { - return getFile(resourceUrl, "URL"); - } + /** + * Resolve the given resource URL to a {@code java.io.File}, + * i.e. to a file in the file system. + * + * @param resourceUrl the resource URL to resolve + * @return a corresponding File object + * @throws FileNotFoundException if the URL cannot be resolved to + * a file in the file system + */ + public static File getFile(URL resourceUrl) throws FileNotFoundException { + return getFile(resourceUrl, "URL"); + } - /** - * Resolve the given resource URL to a {@code java.io.File}, - * i.e. to a file in the file system. - * @param resourceUrl the resource URL to resolve - * @param description a description current the original resource that - * the URL was created for (for example, a class path location) - * @return a corresponding File object - * @throws FileNotFoundException if the URL cannot be resolved to - * a file in the file system - */ - public static File getFile(URL resourceUrl, String description) throws FileNotFoundException { - Objects.requireNonNull(resourceUrl, "Resource URL must not be null"); - if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) { - throw new FileNotFoundException( - description + " cannot be resolved to absolute file path " + - "because it does not reside in the file system: " + resourceUrl); - } - try { - return new File(toURI(resourceUrl).getSchemeSpecificPart()); - } - catch (URISyntaxException ex) { - // Fallback for URLs that are not valid URIs (should hardly ever happen). - return new File(resourceUrl.getFile()); - } - } + /** + * Resolve the given resource URL to a {@code java.io.File}, + * i.e. to a file in the file system. + * + * @param resourceUrl the resource URL to resolve + * @param description a description current the original resource that + * the URL was created for (for example, a class path location) + * @return a corresponding File object + * @throws FileNotFoundException if the URL cannot be resolved to + * a file in the file system + */ + public static File getFile(URL resourceUrl, String description) throws FileNotFoundException { + Objects.requireNonNull(resourceUrl, "Resource URL must not be null"); + if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) { + throw new FileNotFoundException( + description + " cannot be resolved to absolute file path " + + "because it does not reside in the file system: " + resourceUrl); + } + try { + return new File(toURI(resourceUrl).getSchemeSpecificPart()); + } catch (URISyntaxException ex) { + // Fallback for URLs that are not valid URIs (should hardly ever happen). + return new File(resourceUrl.getFile()); + } + } - /** - * Resolve the given resource URI to a {@code java.io.File}, - * i.e. to a file in the file system. - * @param resourceUri the resource URI to resolve - * @return a corresponding File object - * @throws FileNotFoundException if the URL cannot be resolved to - * a file in the file system - */ - public static File getFile(URI resourceUri) throws FileNotFoundException { - return getFile(resourceUri, "URI"); - } + /** + * Resolve the given resource URI to a {@code java.io.File}, + * i.e. to a file in the file system. + * + * @param resourceUri the resource URI to resolve + * @return a corresponding File object + * @throws FileNotFoundException if the URL cannot be resolved to + * a file in the file system + */ + public static File getFile(URI resourceUri) throws FileNotFoundException { + return getFile(resourceUri, "URI"); + } - /** - * Resolve the given resource URI to a {@code java.io.File}, - * i.e. to a file in the file system. - * @param resourceUri the resource URI to resolve - * @param description a description current the original resource that - * the URI was created for (for example, a class path location) - * @return a corresponding File object - * @throws FileNotFoundException if the URL cannot be resolved to - * a file in the file system - */ - public static File getFile(URI resourceUri, String description) throws FileNotFoundException { - Objects.requireNonNull(resourceUri, "Resource URI must not be null"); - if (!URL_PROTOCOL_FILE.equals(resourceUri.getScheme())) { - throw new FileNotFoundException( - description + " cannot be resolved to absolute file path " + - "because it does not reside in the file system: " + resourceUri); - } - return new File(resourceUri.getSchemeSpecificPart()); - } + /** + * Resolve the given resource URI to a {@code java.io.File}, + * i.e. to a file in the file system. + * + * @param resourceUri the resource URI to resolve + * @param description a description current the original resource that + * the URI was created for (for example, a class path location) + * @return a corresponding File object + * @throws FileNotFoundException if the URL cannot be resolved to + * a file in the file system + */ + public static File getFile(URI resourceUri, String description) throws FileNotFoundException { + Objects.requireNonNull(resourceUri, "Resource URI must not be null"); + if (!URL_PROTOCOL_FILE.equals(resourceUri.getScheme())) { + throw new FileNotFoundException( + description + " cannot be resolved to absolute file path " + + "because it does not reside in the file system: " + resourceUri); + } + return new File(resourceUri.getSchemeSpecificPart()); + } - /** - * Determine whether the given URL points to a resource in the file system, - * that is, has protocol "file", "vfsfile" or "vfs". - * @param url the URL to check - * @return whether the URL has been identified as a file system URL - */ - public static boolean isFileURL(URL url) { - String protocol = url.getProtocol(); - return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) || - URL_PROTOCOL_VFS.equals(protocol)); - } + /** + * Determine whether the given URL points to a resource in the file system, + * that is, has protocol "file", "vfsfile" or "vfs". + * + * @param url the URL to check + * @return whether the URL has been identified as a file system URL + */ + public static boolean isFileURL(URL url) { + String protocol = url.getProtocol(); + return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) || + URL_PROTOCOL_VFS.equals(protocol)); + } - /** - * Determine whether the given URL points to a resource in a jar file, - * that is, has protocol "jar", "zip", "vfszip" or "wsjar". - * @param url the URL to check - * @return whether the URL has been identified as a JAR URL - */ - public static boolean isJarURL(URL url) { - String protocol = url.getProtocol(); - return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_ZIP.equals(protocol) || - URL_PROTOCOL_VFSZIP.equals(protocol) || URL_PROTOCOL_WSJAR.equals(protocol)); - } + /** + * Determine whether the given URL points to a resource in a jar file, + * that is, has protocol "jar", "zip", "vfszip" or "wsjar". + * + * @param url the URL to check + * @return whether the URL has been identified as a JAR URL + */ + public static boolean isJarURL(URL url) { + String protocol = url.getProtocol(); + return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_ZIP.equals(protocol) || + URL_PROTOCOL_VFSZIP.equals(protocol) || URL_PROTOCOL_WSJAR.equals(protocol)); + } - /** - * Determine whether the given URL points to a jar file itself, - * that is, has protocol "file" and ends with the ".jar" extension. - * @param url the URL to check - * @return whether the URL has been identified as a JAR file URL - * @since 4.1 - */ - public static boolean isJarFileURL(URL url) { - return (URL_PROTOCOL_FILE.equals(url.getProtocol()) && - url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION)); - } + /** + * Determine whether the given URL points to a jar file itself, + * that is, has protocol "file" and ends with the ".jar" extension. + * + * @param url the URL to check + * @return whether the URL has been identified as a JAR file URL + * @since 4.1 + */ + public static boolean isJarFileURL(URL url) { + return (URL_PROTOCOL_FILE.equals(url.getProtocol()) && + url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION)); + } - /** - * Extract the URL for the actual jar file from the given URL - * (which may point to a resource in a jar file or to a jar file itself). - * @param jarUrl the original URL - * @return the URL for the actual jar file - * @throws MalformedURLException if no valid jar file URL could be extracted - */ - public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException { - String urlFile = jarUrl.getFile(); - int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR); - if (separatorIndex != -1) { - String jarFile = urlFile.substring(0, separatorIndex); - try { - return new URL(jarFile); - } - catch (MalformedURLException ex) { - // Probably no protocol in original jar URL, like "jar:C:/mypath/myjar.jar". - // This usually indicates that the jar file resides in the file system. - if (!jarFile.startsWith("/")) { - jarFile = "/" + jarFile; - } - return new URL(FILE_URL_PREFIX + jarFile); - } - } - else { - return jarUrl; - } - } + /** + * Extract the URL for the actual jar file from the given URL + * (which may point to a resource in a jar file or to a jar file itself). + * + * @param jarUrl the original URL + * @return the URL for the actual jar file + * @throws MalformedURLException if no valid jar file URL could be extracted + */ + public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException { + String urlFile = jarUrl.getFile(); + int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR); + if (separatorIndex != -1) { + String jarFile = urlFile.substring(0, separatorIndex); + try { + return new URL(jarFile); + } catch (MalformedURLException ex) { + // Probably no protocol in original jar URL, like "jar:C:/mypath/myjar.jar". + // This usually indicates that the jar file resides in the file system. + if (!jarFile.startsWith("/")) { + jarFile = "/" + jarFile; + } + return new URL(FILE_URL_PREFIX + jarFile); + } + } else { + return jarUrl; + } + } - /** - * Create a URI instance for the given URL, - * replacing spaces with "%20" URI encoding first. - * <p>Furthermore, this method works on JDK 1.4 as well, - * in contrast to the {@code URL.toURI()} method. - * @param url the URL to convert into a URI instance - * @return the URI instance - * @throws URISyntaxException if the URL wasn't a valid URI - * @see java.net.URL#toURI() - */ - public static URI toURI(URL url) throws URISyntaxException { - return toURI(url.toString()); - } + /** + * Create a URI instance for the given URL, + * replacing spaces with "%20" URI encoding first. + * <p>Furthermore, this method works on JDK 1.4 as well, + * in contrast to the {@code URL.toURI()} method. + * + * @param url the URL to convert into a URI instance + * @return the URI instance + * @throws URISyntaxException if the URL wasn't a valid URI + * @see java.net.URL#toURI() + */ + public static URI toURI(URL url) throws URISyntaxException { + return toURI(url.toString()); + } - /** - * Create a URI instance for the given location String, - * replacing spaces with "%20" URI encoding first. - * @param location the location String to convert into a URI instance - * @return the URI instance - * @throws URISyntaxException if the location wasn't a valid URI - */ - public static URI toURI(String location) throws URISyntaxException { - return new URI(location.replaceAll(" ", "%20")); - } + /** + * Create a URI instance for the given location String, + * replacing spaces with "%20" URI encoding first. + * + * @param location the location String to convert into a URI instance + * @return the URI instance + * @throws URISyntaxException if the location wasn't a valid URI + */ + public static URI toURI(String location) throws URISyntaxException { + return new URI(location.replaceAll(" ", "%20")); + } - /** - * Set the {@link URLConnection#setUseCaches "useCaches"} flag on the - * given connection, preferring {@code false} but leaving the - * flag at {@code true} for JNLP based resources. - * @param con the URLConnection to set the flag on - */ - public static void useCachesIfNecessary(URLConnection con) { - con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP")); - } + /** + * Set the {@link URLConnection#setUseCaches "useCaches"} flag on the + * given connection, preferring {@code false} but leaving the + * flag at {@code true} for JNLP based resources. + * + * @param con the URLConnection to set the flag on + */ + public static void useCachesIfNecessary(URLConnection con) { + con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP")); + } } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/95885781/core/src/main/java/org/apache/tamaya/core/internal/resource/UrlResource.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/tamaya/core/internal/resource/UrlResource.java b/core/src/main/java/org/apache/tamaya/core/internal/resource/UrlResource.java index 6011109..4576aac 100644 --- a/core/src/main/java/org/apache/tamaya/core/internal/resource/UrlResource.java +++ b/core/src/main/java/org/apache/tamaya/core/internal/resource/UrlResource.java @@ -35,8 +35,8 @@ import java.util.Objects; * the "file:" protocol. * * @author Juergen Hoeller - * @since 28.12.2003 * @see java.net.URL + * @since 28.12.2003 */ public class UrlResource extends AbstractFileResolvingResource { @@ -58,6 +58,7 @@ public class UrlResource extends AbstractFileResolvingResource { /** * Create a new UrlResource based on the given URI object. + * * @param uri a URI * @throws MalformedURLException if the given URL path is not valid */ @@ -70,6 +71,7 @@ public class UrlResource extends AbstractFileResolvingResource { /** * Create a new UrlResource based on the given URL object. + * * @param url a URL */ public UrlResource(URL url) { @@ -82,6 +84,7 @@ public class UrlResource extends AbstractFileResolvingResource { /** * Create a new UrlResource based on a URL path. * <p>Note: The given path needs to be pre-encoded if necessary. + * * @param path a URL path * @throws MalformedURLException if the given URL path is not valid * @see java.net.URL#URL(String) @@ -96,36 +99,37 @@ public class UrlResource extends AbstractFileResolvingResource { /** * Create a new UrlResource based on a URI specification. * <p>The given parts will automatically get encoded if necessary. + * * @param protocol the URL protocol to use (e.g. "jar" or "file" - without colon); - * also known as "scheme" + * also known as "scheme" * @param location the location (e.g. the file path within that protocol); - * also known as "scheme-specific part" + * also known as "scheme-specific part" * @throws MalformedURLException if the given URL specification is not valid * @see java.net.URI#URI(String, String, String) */ - public UrlResource(String protocol, String location) throws MalformedURLException { + public UrlResource(String protocol, String location) throws MalformedURLException { this(protocol, location, null); } /** * Create a new UrlResource based on a URI specification. * <p>The given parts will automatically get encoded if necessary. + * * @param protocol the URL protocol to use (e.g. "jar" or "file" - without colon); - * also known as "scheme" + * also known as "scheme" * @param location the location (e.g. the file path within that protocol); - * also known as "scheme-specific part" + * also known as "scheme-specific part" * @param fragment the fragment within that location (e.g. anchor on an HTML page, - * as following after a "#" separator) + * as following after a "#" separator) * @throws MalformedURLException if the given URL specification is not valid * @see java.net.URI#URI(String, String, String) */ - public UrlResource(String protocol, String location, String fragment) throws MalformedURLException { + public UrlResource(String protocol, String location, String fragment) throws MalformedURLException { try { this.uri = new URI(protocol, location, fragment); this.url = this.uri.toURL(); this.cleanedUrl = getCleanedUrl(this.url, this.uri.toString()); - } - catch (URISyntaxException ex) { + } catch (URISyntaxException ex) { MalformedURLException exToThrow = new MalformedURLException(ex.getMessage()); exToThrow.initCause(ex); throw exToThrow; @@ -134,15 +138,15 @@ public class UrlResource extends AbstractFileResolvingResource { /** * Determine a cleaned URL for the given original URL. - * @param originalUrl the original URL + * + * @param originalUrl the original URL * @param originalPath the original URL path * @return the cleaned URL */ private URL getCleanedUrl(URL originalUrl, String originalPath) { try { return new URL(StringUtils.cleanPath(originalPath)); - } - catch (MalformedURLException ex) { + } catch (MalformedURLException ex) { // Cleaned URL path cannot be converted to URL // -> take original URL. return originalUrl; @@ -154,19 +158,19 @@ public class UrlResource extends AbstractFileResolvingResource { * This implementation opens an InputStream for the given URL. * It sets the "UseCaches" flag to {@code false}, * mainly to avoid jar file locking on Windows. + * * @see java.net.URL#openConnection() * @see java.net.URLConnection#setUseCaches(boolean) * @see java.net.URLConnection#getInputStream() */ @Override - public InputStream getInputStream()throws IOException { + public InputStream getInputStream() throws IOException { URLConnection con = null; try { con = this.url.openConnection(); useCachesIfNecessary(con); return con.getInputStream(); - } - catch (IOException ex) { + } catch (IOException ex) { // Close the HTTP connection (if applicable). if (con instanceof HttpURLConnection) { ((HttpURLConnection) con).disconnect(); @@ -191,8 +195,7 @@ public class UrlResource extends AbstractFileResolvingResource { public URI getURI() throws IOException { if (this.uri != null) { return this.uri; - } - else { + } else { return super.getURI(); } } @@ -205,8 +208,7 @@ public class UrlResource extends AbstractFileResolvingResource { public File toFile() throws IOException { if (this.uri != null) { return super.getFile(this.uri); - } - else { + } else { return super.toFile(); } } @@ -214,6 +216,7 @@ public class UrlResource extends AbstractFileResolvingResource { /** * This implementation creates a UrlResource, applying the given path * relative to the path current the underlying URL current this resource descriptor. + * * @see java.net.URL#URL(java.net.URL, String) */ @Override @@ -226,6 +229,7 @@ public class UrlResource extends AbstractFileResolvingResource { /** * This implementation returns the name current the file that this URL refers to. + * * @see java.net.URL#getFile() * @see java.io.File#getName() */ @@ -260,15 +264,16 @@ public class UrlResource extends AbstractFileResolvingResource { return this.cleanedUrl.hashCode(); } - /** - * Set the {@link URLConnection#setUseCaches "useCaches"} flag on the - * given connection, preferring {@code false} but leaving the - * flag at {@code true} for JNLP based resources. - * @param con the URLConnection to set the flag on - */ - private void useCachesIfNecessary(URLConnection con) { - con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP")); - } + /** + * Set the {@link URLConnection#setUseCaches "useCaches"} flag on the + * given connection, preferring {@code false} but leaving the + * flag at {@code true} for JNLP based resources. + * + * @param con the URLConnection to set the flag on + */ + private void useCachesIfNecessary(URLConnection con) { + con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP")); + } } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/95885781/core/src/main/java/org/apache/tamaya/core/internal/resource/VfsResource.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/tamaya/core/internal/resource/VfsResource.java b/core/src/main/java/org/apache/tamaya/core/internal/resource/VfsResource.java index b39a907..7688a6f 100644 --- a/core/src/main/java/org/apache/tamaya/core/internal/resource/VfsResource.java +++ b/core/src/main/java/org/apache/tamaya/core/internal/resource/VfsResource.java @@ -26,7 +26,7 @@ import java.util.Objects; /** * JBoss VFS based {@link Resource} implementation. - * + * <p> * <p>As current Spring 4.0, this class supports VFS 3.x on JBoss AS 6+ (package * {@code org.jboss.vfs}) and is in particular compatible with JBoss AS 7 and * WildFly 8. @@ -38,97 +38,94 @@ import java.util.Objects; */ public class VfsResource implements Resource { - private final Object resource; + private final Object resource; - public VfsResource(Object resource) { - Objects.requireNonNull(resource, "VirtualFile must not be null"); - this.resource = resource; - } + public VfsResource(Object resource) { + Objects.requireNonNull(resource, "VirtualFile must not be null"); + this.resource = resource; + } - @Override - public InputStream getInputStream()throws IOException { + @Override + public InputStream getInputStream() throws IOException { return VfsUtils.getInputStream(this.resource); } - @Override - public boolean exists() { - return VfsUtils.exists(this.resource); - } - - @Override - public boolean isReadable() { - return VfsUtils.isReadable(this.resource); - } - - @Override - public URL toURL() throws IOException { - try { - return VfsUtils.getURL(this.resource); - } - catch (Exception ex) { - throw new IllegalStateException("Failed to obtain URL for file " + this.resource, ex); - } - } - - @Override - public URI getURI() throws IOException { - try { - return VfsUtils.getURI(this.resource); - } - catch (Exception ex) { - throw new IllegalStateException("Failed to obtain URI for " + this.resource, ex); - } - } - - @Override - public File toFile() throws IOException { - return VfsUtils.getFile(this.resource); - } - - @Override - public long contentLength() throws IOException { - return VfsUtils.getSize(this.resource); - } - - @Override - public long lastModified() throws IOException { - return VfsUtils.getLastModified(this.resource); - } - - @Override - public Resource createRelative(String relativePath) throws IOException { - if (!relativePath.startsWith(".") && relativePath.contains("/")) { - try { - return new VfsResource(VfsUtils.getChild(this.resource, relativePath)); - } - catch (IOException ex) { - // fall back to getRelative - } - } - - return new VfsResource(VfsUtils.getRelative(new URL(toURL(), relativePath))); - } - - @Override - public String getDisplayName() { - return VfsUtils.getName(this.resource); - } - - @Override - public String toString() { - return this.resource.toString(); - } - - @Override - public boolean equals(Object obj) { - return (obj == this || (obj instanceof VfsResource && this.resource.equals(((VfsResource) obj).resource))); - } - - @Override - public int hashCode() { - return this.resource.hashCode(); - } + @Override + public boolean exists() { + return VfsUtils.exists(this.resource); + } + + @Override + public boolean isReadable() { + return VfsUtils.isReadable(this.resource); + } + + @Override + public URL toURL() throws IOException { + try { + return VfsUtils.getURL(this.resource); + } catch (Exception ex) { + throw new IllegalStateException("Failed to obtain URL for file " + this.resource, ex); + } + } + + @Override + public URI getURI() throws IOException { + try { + return VfsUtils.getURI(this.resource); + } catch (Exception ex) { + throw new IllegalStateException("Failed to obtain URI for " + this.resource, ex); + } + } + + @Override + public File toFile() throws IOException { + return VfsUtils.getFile(this.resource); + } + + @Override + public long contentLength() throws IOException { + return VfsUtils.getSize(this.resource); + } + + @Override + public long lastModified() throws IOException { + return VfsUtils.getLastModified(this.resource); + } + + @Override + public Resource createRelative(String relativePath) throws IOException { + if (!relativePath.startsWith(".") && relativePath.contains("/")) { + try { + return new VfsResource(VfsUtils.getChild(this.resource, relativePath)); + } catch (IOException ex) { + // fall back to getRelative + } + } + + return new VfsResource(VfsUtils.getRelative(new URL(toURL(), relativePath))); + } + + @Override + public String getDisplayName() { + return VfsUtils.getName(this.resource); + } + + @Override + public String toString() { + return this.resource.toString(); + } + + @Override + public boolean equals(Object obj) { + return (obj == this || (obj instanceof VfsResource && this.resource.equals(((VfsResource) obj).resource))); + } + + @Override + public int hashCode() { + return this.resource.hashCode(); + } }