Example usage for org.springframework.util ResourceUtils isJarURL

List of usage examples for org.springframework.util ResourceUtils isJarURL

Introduction

In this page you can find the example usage for org.springframework.util ResourceUtils isJarURL.

Prototype

public static boolean isJarURL(URL url) 

Source Link

Document

Determine whether the given URL points to a resource in a jar file.

Usage

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./*from  w  ww. j  a  v a  2  s. c  om*/
 * @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.extensions.config.source.UrlConfigSource.java

/**
 * Processes the given JAR file pattern source. The classpath
 * will be searched for JAR files that contain files that match
 * the given pattern.// w w  w . j a v a  2  s .c om
 * 
 * NOTE: Currently only files within the META-INF folder are supported
 * i.e. patterns that look like "jar:*!/META-INF/[filename]"
 * 
 * @param sourcePattern The wildcard pattern for files to find within JARs
 */
protected void processWildcardJarSource(String sourcePattern) {
    String file = sourcePattern.substring(7);

    if (file.startsWith(META_INF) == false) {
        throw new UnsupportedOperationException(
                "Only JAR file wildcard searches within the META-INF folder are currently supported");
    }

    try {
        if (applicationContext == null) {
            // get a list of all the JAR files that have the META-INF folder
            Enumeration<URL> urls = this.getClass().getClassLoader().getResources(META_INF);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                // only add the item if is a reference to a JAR file
                if (url.getProtocol().equals(JarConfigSource.JAR_PROTOCOL)) {
                    URLConnection conn = url.openConnection();
                    if (conn instanceof JarURLConnection) {
                        // open the jar file and see if it contains what we're looking for
                        JarURLConnection jarConn = (JarURLConnection) conn;
                        JarFile jar = ((JarURLConnection) conn).getJarFile();
                        ZipEntry entry = jar.getEntry(file);
                        if (entry != null) {
                            if (logger.isInfoEnabled())
                                logger.info("Found " + file + " in " + jarConn.getJarFileURL());

                            String sourceString = JarConfigSource.JAR_PROTOCOL + ":"
                                    + jarConn.getJarFileURL().toExternalForm()
                                    + JarConfigSource.JAR_PATH_SEPARATOR + file;

                            super.addSourceString(sourceString);
                        } else if (logger.isDebugEnabled()) {
                            logger.debug("Did not find " + file + " in " + jarConn.getJarFileURL());
                        }
                    }
                }
            }
        } else {
            Resource[] resources = applicationContext.getResources(PREFIX_CLASSPATH_ALL + file);

            for (Resource resource : resources) {
                URL resourceUrl = resource.getURL();
                if (ResourceUtils.isJarURL(resourceUrl)
                        || ResourceUtils.URL_PROTOCOL_VFSZIP.equals(resourceUrl.getProtocol())) {
                    URL jarURL = extractJarFileURL(resourceUrl);

                    String sourceString = JarConfigSource.JAR_PROTOCOL + ":" + jarURL.toString()
                            + JarConfigSource.JAR_PATH_SEPARATOR + file;

                    super.addSourceString(sourceString);
                } else if (ResourceUtils.URL_PROTOCOL_VFS.equals(resourceUrl.getProtocol())) {
                    super.addSourceString(resourceUrl.toString());
                }
            }
        }
    } catch (IOException ioe) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to process JAR file wildcard: " + sourcePattern, ioe);
    }
}

From source file:org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.java

private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
    if (this.componentsIndex != null) {
        Set<String> candidates = new HashSet<>();
        for (AnnotationTypeFilter filter : entityTypeFilters) {
            candidates/*from  w  w w .ja v a 2s  .c o  m*/
                    .addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
        }
        candidates.forEach(scannedUnit::addManagedClassName);
        Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
        managedPackages.forEach(scannedUnit::addManagedPackage);
        return;
    }

    try {
        String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
        Resource[] resources = this.resourcePatternResolver.getResources(pattern);
        MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                if (matchesFilter(reader, readerFactory)) {
                    scannedUnit.addManagedClassName(className);
                    if (scannedUnit.getPersistenceUnitRootUrl() == null) {
                        URL url = resource.getURL();
                        if (ResourceUtils.isJarURL(url)) {
                            scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
                        }
                    }
                } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
                    scannedUnit.addManagedPackage(
                            className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
                }
            }
        }
    } catch (IOException ex) {
        throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
    }
}

From source file:org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.java

/**
 * Try to determine the persistence unit root URL based on the given
 * "defaultPersistenceUnitRootLocation".
 * @return the persistence unit root URL to pass to the JPA PersistenceProvider
 * @see #setDefaultPersistenceUnitRootLocation
 *//*from  www  . ja v  a  2s.com*/
@Nullable
private URL determineDefaultPersistenceUnitRootUrl() {
    if (this.defaultPersistenceUnitRootLocation == null) {
        return null;
    }
    try {
        URL url = this.resourcePatternResolver.getResource(this.defaultPersistenceUnitRootLocation).getURL();
        return (ResourceUtils.isJarURL(url) ? ResourceUtils.extractJarFileURL(url) : url);
    } catch (IOException ex) {
        throw new PersistenceException("Unable to resolve persistence unit root URL", ex);
    }
}

From source file:org.springframework.orm.jpa.persistenceunit.PersistenceUnitReader.java

/**
 * Determine the persistence unit root URL based on the given resource
 * (which points to the {@code persistence.xml} file we're reading).
 * @param resource the resource to check
 * @return the corresponding persistence unit root URL
 * @throws IOException if the checking failed
 *//*  w  w w  .j  a va  2 s . c o  m*/
@Nullable
static URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
    URL originalURL = resource.getURL();

    // If we get an archive, simply return the jar URL (section 6.2 from the JPA spec)
    if (ResourceUtils.isJarURL(originalURL)) {
        return ResourceUtils.extractJarFileURL(originalURL);
    }

    // Check META-INF folder
    String urlToString = originalURL.toExternalForm();
    if (!urlToString.contains(META_INF)) {
        if (logger.isInfoEnabled()) {
            logger.info(resource.getFilename()
                    + " should be located inside META-INF directory; cannot determine persistence unit root URL for "
                    + resource);
        }
        return null;
    }
    if (urlToString.lastIndexOf(META_INF) == urlToString.lastIndexOf('/') - (1 + META_INF.length())) {
        if (logger.isInfoEnabled()) {
            logger.info(resource.getFilename()
                    + " is not located in the root of META-INF directory; cannot determine persistence unit root URL for "
                    + resource);
        }
        return null;
    }

    String persistenceUnitRoot = urlToString.substring(0, urlToString.lastIndexOf(META_INF));
    if (persistenceUnitRoot.endsWith("/")) {
        persistenceUnitRoot = persistenceUnitRoot.substring(0, persistenceUnitRoot.length() - 1);
    }
    return new URL(persistenceUnitRoot);
}