Example usage for org.springframework.core.io.support ResourcePatternResolver getResources

List of usage examples for org.springframework.core.io.support ResourcePatternResolver getResources

Introduction

In this page you can find the example usage for org.springframework.core.io.support ResourcePatternResolver getResources.

Prototype

Resource[] getResources(String locationPattern) throws IOException;

Source Link

Document

Resolve the given location pattern into Resource objects.

Usage

From source file:org.spring.resource.PatternResolverTest.java

public static void main(String[] args) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    ///////*from ww w .j a v a2s .co m*/
    // xml??
    //////

    Resource resources[] = resolver.getResources("classpath*:*.xml");
    for (Resource resource : resources) {
        System.out.println("?" + resource.getDescription());
    }
}

From source file:com.google.code.activetemplates.impl.handlers.BuiltinHandlerSPI.java

private static final <T> Set<Class<T>> getClasses(String pkg, Class<T> clazz) throws Exception {

    pkg = pkg.replace('.', '/');
    Set<Class<T>> classes = new HashSet<Class<T>>();

    ResourcePatternResolver res = new PathMatchingResourcePatternResolver();
    Resource[] resources = res.getResources("classpath*:" + pkg + "/*.class");
    for (Resource r : resources) {

        String className = r.getURL().getFile();
        className = className.substring(className.indexOf(pkg), className.length() - ".class".length());
        className = className.replace('/', '.');

        try {/*w  w w  .  j a  v a2s  .c  o  m*/
            Class<?> cl = Class.forName(className);
            if (clazz.isAssignableFrom(cl)) {
                @SuppressWarnings("unchecked")
                Class<T> tcl = (Class<T>) cl;
                classes.add(tcl);
            }
        } catch (ClassNotFoundException e) {
        }
    }
    return classes;

}

From source file:com.intuit.cto.selfservice.service.Util.java

/**
 * Extract files from a package on the classpath into a directory.
 * @param packagePath e.g. "com/stuff" (always forward slash not backslash, never dot)
 * @param toDir directory to extract to/*from w  w  w . j  av a  2s. co m*/
 * @return int the number of files copied
 * @throws java.io.IOException if something goes wrong, including if nothing was found on classpath
 */
public static int extractFromClasspathToFile(String packagePath, File toDir) throws IOException {
    String locationPattern = "classpath*:" + packagePath + "/**";
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resourcePatternResolver.getResources(locationPattern);
    if (resources.length == 0) {
        throw new IOException("Nothing found at " + locationPattern);
    }
    int counter = 0;
    for (Resource resource : resources) {
        if (resource.isReadable()) { // Skip hidden or system files
            URL url = resource.getURL();
            String path = url.toString();
            if (!path.endsWith("/")) { // Skip directories
                int p = path.lastIndexOf(packagePath) + packagePath.length();
                path = path.substring(p);
                File targetFile = new File(toDir, path);
                long len = resource.contentLength();
                if (!targetFile.exists() || targetFile.length() != len) { // Only copy new files
                    FileUtils.copyURLToFile(url, targetFile);
                    counter++;
                }
            }
        }
    }
    logger.info("Unpacked {} files from {} to {}", new Object[] { counter, locationPattern, toDir });
    return counter;
}

From source file:com.github.mjeanroy.springmvc.view.mustache.commons.IOUtils.java

private static InputStream getInputStreamWithResolver(ResourcePatternResolver resolver, String name) {
    try {//w  w w .j a  va  2  s .  c  om
        Resource[] resources = resolver.getResources(name);

        // Not Found
        if (resources.length == 0) {
            log.debug("Found zero results with pattern: {}", name);
            return null;
        }

        log.debug("Found {} results with pattern: {}", resources.length, name);

        if (log.isTraceEnabled()) {
            for (Resource resource : resources) {
                log.trace("  -> Found: {}", resource.getFilename());
            }
        }

        return resources[0].getInputStream();
    } catch (IOException ex) {
        throw new MustacheIOException("I/O Error with " + name, ex);
    }
}

From source file:edu.duke.cabig.c3pr.rules.deploy.SystemRulesDeployer.java

public static Resource[] getResources(String pattern) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    if (log.isDebugEnabled())
        log.debug("Looking for resources matching " + pattern);
    Resource[] resources = resolver.getResources(pattern);
    return resources;
}

From source file:gov.nih.nci.cabig.caaers.api.InvestigatorMigratorServiceTest.java

private static Resource[] getResources(String pattern) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources(pattern);
    return resources;
}

From source file:de.fiz.ddb.aas.util.AasConfiguration.java

/**
 * Get an InputStream for the given file.
 *
 * @param filename The name of the file.
 * @return The InputStream or null if the file could not be located.
 * @throws FileNotFoundException If access to the specified file fails.
 *///from  w  ww . j a  v  a 2s. c o  m
private static InputStream getInputStream(final String filename) throws IOException, FileNotFoundException {
    final ResourcePatternResolver applicationContext = new ClassPathXmlApplicationContext(new String[] {});
    final Resource[] resource = applicationContext.getResources("classpath*:" + filename);
    if (resource.length == 0) {
        throw new FileNotFoundException("Unable to find file '" + filename + "' in classpath.");
    }
    return resource[0].getInputStream();
}

From source file:com.trigonic.utils.spring.beans.ImportHelper.java

private static void importAbsoluteResourcePattern(XmlBeanDefinitionReader reader, String location,
        Set<Resource> actualResources, ResourcePatternResolver resourceLoader) {
    try {//www .  j ava 2s .  c  om
        List<Resource> resources = new ArrayList<Resource>(
                Arrays.asList(resourceLoader.getResources(location)));
        int loadCount = 0;
        for (Resource resource : resources) {
            if (resource.exists()) {
                loadCount += reader.loadBeanDefinitions(resource);
                actualResources.add(resource);
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
        }
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException(
                "Could not resolve bean definition resource pattern [" + location + "]", ex);
    }
}

From source file:gov.nih.nci.cabig.caaers.utils.XmlValidator.java

/**
 * This method fetches the specified resource pattern from classpath.
 * In this context used to fetch xsd files.
 * @param pattern//from  w  w  w .jav a2s.  com
 * @return
 * @throws IOException
 */
public static Resource[] getResources(String pattern) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    if (logger.isDebugEnabled())
        logger.debug("Looking for resources matching " + pattern);
    Resource[] resources = resolver.getResources(pattern);
    return resources;
}

From source file:ch.vorburger.mariadb4j.Util.java

/**
 * Extract files from a package on the classpath into a directory.
 * //from  w ww.  j a  v a  2  s.c  om
 * @param packagePath e.g. "com/stuff" (always forward slash not backslash, never dot)
 * @param toDir directory to extract to
 * @return int the number of files copied
 * @throws java.io.IOException if something goes wrong, including if nothing was found on
 *             classpath
 */
public static int extractFromClasspathToFile(String packagePath, File toDir) throws IOException {
    String locationPattern = "classpath*:" + packagePath + "/**";
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resourcePatternResolver.getResources(locationPattern);
    if (resources.length == 0) {
        throw new IOException("Nothing found at " + locationPattern);
    }
    int counter = 0;
    for (Resource resource : resources) {
        if (resource.isReadable()) { // Skip hidden or system files
            final URL url = resource.getURL();
            String path = url.toString();
            if (!path.endsWith("/")) { // Skip directories
                int p = path.lastIndexOf(packagePath) + packagePath.length();
                path = path.substring(p);
                final File targetFile = new File(toDir, path);
                long len = resource.contentLength();
                if (!targetFile.exists() || targetFile.length() != len) { // Only copy new files
                    tryN(5, 500, new Procedure<IOException>() {

                        @Override
                        public void apply() throws IOException {
                            FileUtils.copyURLToFile(url, targetFile);
                        }
                    });
                    counter++;
                }
            }
        }
    }
    if (counter > 0) {
        Object[] info = new Object[] { counter, locationPattern, toDir };
        logger.info("Unpacked {} files from {} to {}", info);
    }
    return counter;
}