Example usage for org.springframework.core.io UrlResource UrlResource

List of usage examples for org.springframework.core.io UrlResource UrlResource

Introduction

In this page you can find the example usage for org.springframework.core.io UrlResource UrlResource.

Prototype

public UrlResource(String path) throws MalformedURLException 

Source Link

Document

Create a new UrlResource based on a URL path.

Usage

From source file:org.springframework.cloud.config.server.support.AbstractScmAccessor.java

protected File getWorkingDirectory() {
    if (this.uri.startsWith("file:")) {
        try {// w  w w  .j  a va 2  s.  c  o  m
            return new UrlResource(StringUtils.cleanPath(this.uri)).getFile();
        } catch (Exception e) {
            throw new IllegalStateException("Cannot convert uri to file: " + this.uri);
        }
    }
    return this.basedir;
}

From source file:org.springframework.cloud.stream.config.BinderFactoryConfiguration.java

@Bean
public BinderTypeRegistry binderTypeRegistry(ConfigurableApplicationContext configurableApplicationContext) {
    Map<String, BinderType> binderTypes = new HashMap<>();
    ClassLoader classLoader = configurableApplicationContext.getClassLoader();
    // the above can never be null since it will default to ClassUtils.getDefaultClassLoader(..)
    try {/*  w w w  .  j  a v a  2 s .c om*/
        Enumeration<URL> resources = classLoader.getResources("META-INF/spring.binders");
        if (!Boolean.valueOf(this.selfContained) && (resources == null || !resources.hasMoreElements())) {
            this.logger.debug("Failed to locate 'META-INF/spring.binders' resources on the classpath."
                    + " Assuming standard boot 'META-INF/spring.factories' configuration is used");
        } else {
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                UrlResource resource = new UrlResource(url);
                for (BinderType binderType : parseBinderConfigurations(classLoader, resource)) {
                    binderTypes.put(binderType.getDefaultName(), binderType);
                }
            }
        }

    } catch (IOException | ClassNotFoundException e) {
        throw new BeanCreationException("Cannot create binder factory:", e);
    }
    return new DefaultBinderTypeRegistry(binderTypes);
}

From source file:org.springframework.context.index.CandidateComponentsIndexLoader.java

@Nullable
private static CandidateComponentsIndex doLoadIndex(ClassLoader classLoader) {
    if (shouldIgnoreIndex) {
        return null;
    }/*w ww.j av  a  2 s  .c  o m*/

    try {
        Enumeration<URL> urls = classLoader.getResources(COMPONENTS_RESOURCE_LOCATION);
        if (!urls.hasMoreElements()) {
            return null;
        }
        List<Properties> result = new ArrayList<>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
            result.add(properties);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded " + result.size() + "] index(es)");
        }
        int totalCount = result.stream().mapToInt(Properties::size).sum();
        return (totalCount > 0 ? new CandidateComponentsIndex(result) : null);
    } catch (IOException ex) {
        throw new IllegalStateException(
                "Unable to load indexes from location [" + COMPONENTS_RESOURCE_LOCATION + "]", ex);
    }
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * 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
 * @see org.springframework.core.io.Resource
 *///from   ww  w  . j ava  2s. c om
protected Resource convertClassLoaderURL(URL url) {
    return new UrlResource(url);
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Search all {@link URLClassLoader} URLs for jar file references and add them to the
 * given set of resources in the form of pointers to the root of the jar file content.
 * @param classLoader the ClassLoader to search (including its ancestors)
 * @param result the set of resources to add jar roots to
 * @since 4.1.1//www . j  a va 2  s  .co  m
 */
protected void addAllClassLoaderJarRoots(@Nullable ClassLoader classLoader, Set<Resource> result) {
    if (classLoader instanceof URLClassLoader) {
        try {
            for (URL url : ((URLClassLoader) classLoader).getURLs()) {
                try {
                    UrlResource jarResource = new UrlResource(
                            ResourceUtils.JAR_URL_PREFIX + url + ResourceUtils.JAR_URL_SEPARATOR);
                    if (jarResource.exists()) {
                        result.add(jarResource);
                    }
                } catch (MalformedURLException ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Cannot search for matching files underneath [" + url
                                + "] because it cannot be converted to a valid 'jar:' URL: " + ex.getMessage());
                    }
                }
            }
        } catch (Exception ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Cannot introspect jar files since ClassLoader [" + classLoader
                        + "] does not support 'getURLs()': " + ex);
            }
        }
    }

    if (classLoader == ClassLoader.getSystemClassLoader()) {
        // "java.class.path" manifest evaluation...
        addClassPathManifestEntries(result);
    }

    if (classLoader != null) {
        try {
            // Hierarchy traversal...
            addAllClassLoaderJarRoots(classLoader.getParent(), result);
        } catch (Exception ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Cannot introspect jar files in parent ClassLoader since [" + classLoader
                        + "] does not support 'getParent()': " + ex);
            }
        }
    }
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Determine jar file references from the "java.class.path." manifest property and add them
 * to the given set of resources in the form of pointers to the root of the jar file content.
 * @param result the set of resources to add jar roots to
 * @since 4.3//from  ww  w.  ja  va 2  s . c  o m
 */
protected void addClassPathManifestEntries(Set<Resource> result) {
    try {
        String javaClassPathProperty = System.getProperty("java.class.path");
        for (String path : StringUtils.delimitedListToStringArray(javaClassPathProperty,
                System.getProperty("path.separator"))) {
            try {
                String filePath = new File(path).getAbsolutePath();
                int prefixIndex = filePath.indexOf(':');
                if (prefixIndex == 1) {
                    // Possibly "c:" drive prefix on Windows, to be upper-cased for proper duplicate detection
                    filePath = StringUtils.capitalize(filePath);
                }
                UrlResource jarResource = new UrlResource(ResourceUtils.JAR_URL_PREFIX
                        + ResourceUtils.FILE_URL_PREFIX + filePath + ResourceUtils.JAR_URL_SEPARATOR);
                // Potentially overlapping with URLClassLoader.getURLs() result above!
                if (!result.contains(jarResource) && !hasDuplicate(filePath, result) && jarResource.exists()) {
                    result.add(jarResource);
                }
            } catch (MalformedURLException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Cannot search for matching files underneath [" + path
                            + "] because it cannot be converted to a valid 'jar:' URL: " + ex.getMessage());
                }
            }
        }
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to evaluate 'java.class.path' manifest entries: " + ex);
        }
    }
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Check whether the given file path has a duplicate but differently structured entry
 * in the existing result, i.e. with or without a leading slash.
 * @param filePath the file path (with or without a leading slash)
 * @param result the current result// w  w  w . j  a  va 2  s .  c  om
 * @return {@code true} if there is a duplicate (i.e. to ignore the given file path),
 * {@code false} to proceed with adding a corresponding resource to the current result
 */
private boolean hasDuplicate(String filePath, Set<Resource> result) {
    if (result.isEmpty()) {
        return false;
    }
    String duplicatePath = (filePath.startsWith("/") ? filePath.substring(1) : "/" + filePath);
    try {
        return result.contains(new UrlResource(ResourceUtils.JAR_URL_PREFIX + ResourceUtils.FILE_URL_PREFIX
                + duplicatePath + ResourceUtils.JAR_URL_SEPARATOR));
    } catch (MalformedURLException ex) {
        // Ignore: just for testing against duplicate.
        return false;
    }
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * 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.// ww  w .jav  a 2s.c  o m
 * @param locationPattern the location pattern to match
 * @return the result as Resource array
 * @throws IOException in case of I/O errors
 * @see #doFindPathMatchingJarResources
 * @see #doFindPathMatchingFileResources
 * @see org.springframework.util.PathMatcher
 */
protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
    String rootDirPath = determineRootDir(locationPattern);
    String subPattern = locationPattern.substring(rootDirPath.length());
    Resource[] rootDirResources = getResources(rootDirPath);
    Set<Resource> result = new LinkedHashSet<>(16);
    for (Resource rootDirResource : rootDirResources) {
        rootDirResource = resolveRootDirResource(rootDirResource);
        URL rootDirUrl = rootDirResource.getURL();
        if (equinoxResolveMethod != null) {
            if (rootDirUrl.getProtocol().startsWith("bundle")) {
                URL resolvedUrl = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirUrl);
                if (resolvedUrl != null) {
                    rootDirUrl = resolvedUrl;
                }
                rootDirResource = new UrlResource(rootDirUrl);
            }
        }
        if (rootDirUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
            result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirUrl, subPattern,
                    getPathMatcher()));
        } else if (ResourceUtils.isJarURL(rootDirUrl) || isJarResource(rootDirResource)) {
            result.addAll(doFindPathMatchingJarResources(rootDirResource, rootDirUrl, subPattern));
        } else {
            result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
    }
    return result.toArray(new Resource[result.size()]);
}

From source file:org.springframework.core.io.support.SpringFactoriesLoader.java

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    MultiValueMap<String, String> result = cache.get(classLoader);
    if (result != null)
        return result;
    try {//from  w  w w  .  j  av  a 2 s  .  com
        Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION)
                : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        result = new LinkedMultiValueMap<>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            UrlResource resource = new UrlResource(url);
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            for (Map.Entry<?, ?> entry : properties.entrySet()) {
                List<String> factoryClassNames = Arrays
                        .asList(StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));
                result.addAll((String) entry.getKey(), factoryClassNames);
            }
        }
        cache.put(classLoader, result);
        return result;
    } catch (IOException ex) {
        throw new IllegalArgumentException(
                "Unable to load factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}

From source file:org.springframework.core.SpringFactoriesLoader.java

private static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader,
        String factoriesLocation) {

    String factoryClassName = factoryClass.getName();

    try {/*w  ww . ja v a2s .c  o  m*/
        List<String> result = new ArrayList<String>();
        Enumeration<URL> urls = classLoader.getResources(factoriesLocation);
        while (urls.hasMoreElements()) {
            URL url = (URL) urls.nextElement();
            Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
            String factoryClassNames = properties.getProperty(factoryClassName);
            result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
        }
        return result;
    } catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load [" + factoryClass.getName()
                + "] factories from location [" + factoriesLocation + "]", ex);
    }

}