Java Code Examples for org.springframework.util.ResourceUtils#isJarURL()

The following examples show how to use org.springframework.util.ResourceUtils#isJarURL() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JarResource.java    From spring-boot-jar-resources with Apache License 2.0 6 votes vote down vote up
@Override
public File getFile() throws IOException {
    URL resourceUrl = getURL();
    if(ResourceUtils.isJarURL(resourceUrl)) {
        File tempFile = FILE_REGISTRY.get(resourceUrl);
        if(tempFile == null || !tempFile.exists()) {
            log.debug("Extracting File for URL: {}", resourceUrl);
            tempFile = JarUtils.getFile(delegate, extractPath);
            FILE_REGISTRY.put(resourceUrl, tempFile);
        } else {
            log.debug("File found in registry for URL: {}", resourceUrl);
        }
        return new File(tempFile.toURI());
    }
    return delegate.getFile();
}
 
Example 2
Source File: AbstractFileResolvingResource.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public long lastModified() throws IOException {
	URL url = getURL();
	if (ResourceUtils.isFileURL(url) || ResourceUtils.isJarURL(url)) {
		// Proceed with file system resolution
		try {
			return super.lastModified();
		}
		catch (FileNotFoundException ex) {
			// Defensively fall back to URL connection check instead
		}
	}
	// Try a URL connection last-modified header
	URLConnection con = url.openConnection();
	customizeConnection(con);
	return con.getLastModified();
}
 
Example 3
Source File: AbstractConfigLoader.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private int doSort(ConfigModelWrapper w1, ConfigModelWrapper w2) {
  ConfigModel m1 = w1.model;
  ConfigModel m2 = w2.model;
  boolean isM1Jar = ResourceUtils.isJarURL(m1.getUrl());
  boolean isM2Jar = ResourceUtils.isJarURL(m2.getUrl());
  if (isM1Jar != isM2Jar) {
    if (isM1Jar) {
      return -1;
    }

    return 1;
  }
  // min order load first
  int result = Integer.compare(m1.getOrder(), m2.getOrder());
  if (result != 0) {
    return result;
  }

  return doFinalSort(w1, w2);
}
 
Example 4
Source File: AbstractContentTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Helper method to load one of the "The quick brown fox" files from the
 * classpath.
 * 
 * @param quickname file required, eg <b>quick.txt</b>
 * @return Returns a test resource loaded from the classpath or <tt>null</tt> if
 *      no resource could be found.
 * @throws IOException
 */
public static File loadNamedQuickTestFile(String quickname) throws IOException
{
    String quickNameAndPath = "quick/" + quickname;
    URL url = AbstractContentTransformerTest.class.getClassLoader().getResource(quickNameAndPath);
    if (url == null)
    {
        return null;
    }
    if (ResourceUtils.isJarURL(url))
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Using a temp file for quick resource that's in a jar." + quickNameAndPath);
        }
        try
        {
            InputStream is = AbstractContentTransformerTest.class.getClassLoader().getResourceAsStream(quickNameAndPath);
            File tempFile = TempFileProvider.createTempFile(is, quickname, ".tmp");
            return tempFile;
        }
        catch (Exception error)
        {
            logger.error("Failed to load a quick file from a jar. "+error);
            return null;
        }
    }
    return ResourceUtils.getFile(url);
}
 
Example 5
Source File: DataDictionary.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Parses the path name from a resource's description
 * @param resource a resource which hides a path from us
 * @return the path name if we could parse it out
 */
protected String parseResourcePathFromUrl(Resource resource) throws IOException {
    final URL resourceUrl = resource.getURL();
    if (ResourceUtils.isJarURL(resourceUrl)) {
        final Matcher resourceUrlPathMatcher = resourceJarUrlPattern.matcher(resourceUrl.getPath());
        if (resourceUrlPathMatcher.matches() && !StringUtils.isBlank(resourceUrlPathMatcher.group(1))) {
            return "classpath:" + resourceUrlPathMatcher.group(1);
        }
    } else if (ResourceUtils.URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol()) && resource.exists()) {
        return "file:" + resourceUrl.getFile();
    }
    return null;
}
 
Example 6
Source File: AbstractFileResolvingResource.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This implementation determines the underlying File (or jar file, in case
 * of a resource in a jar/zip).
 */
@Override
protected File getFileForLastModifiedCheck() throws IOException {
    URL url = getURL();
    if (ResourceUtils.isJarURL(url)) {
        URL actualUrl = ResourceUtils.extractJarFileURL(url);
        if (actualUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
            return VfsResourceDelegate.getResource(actualUrl).getFile();
        }
        return ResourceUtils.getFile(actualUrl, "Jar URL");
    } else {
        return getFile();
    }
}
 
Example 7
Source File: AbstractFileResolvingResource.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation determines the underlying File
 * (or jar file, in case of a resource in a jar/zip).
 */
@Override
protected File getFileForLastModifiedCheck() throws IOException {
	URL url = getURL();
	if (ResourceUtils.isJarURL(url)) {
		URL actualUrl = ResourceUtils.extractArchiveURL(url);
		if (actualUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
			return VfsResourceDelegate.getResource(actualUrl).getFile();
		}
		return ResourceUtils.getFile(actualUrl, "Jar URL");
	}
	else {
		return getFile();
	}
}
 
Example 8
Source File: PersistenceUnitReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 */
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);
}
 
Example 9
Source File: DefaultPersistenceUnitManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 */
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);
	}
}
 
Example 10
Source File: AbstractFileResolvingResource.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
@Override
public long lastModified() throws IOException {
    URL url = getURL();
    if (ResourceUtils.isFileURL(url) || ResourceUtils.isJarURL(url)) {
        // Proceed with file system resolution...
        return super.lastModified();
    } else {
        // Try a URL connection last-modified header...
        URLConnection con = url.openConnection();
        customizeConnection(con);
        return con.getLastModified();
    }
}
 
Example 11
Source File: PersistenceUnitReader.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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
 */
@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);
}
 
Example 12
Source File: DefaultPersistenceUnitManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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
 */
@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);
	}
}
 
Example 13
Source File: PersistenceUnitReader.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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
 */
protected 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);
}
 
Example 14
Source File: PersistenceUnitReader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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
 */
@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);
}
 
Example 15
Source File: DefaultPersistenceUnitManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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
 */
@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);
	}
}
 
Example 16
Source File: AbstractFileResolvingResource.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * This implementation determines the underlying File
 * (or jar file, in case of a resource in a jar/zip).
 */
@Override
protected File getFileForLastModifiedCheck() throws IOException {
	URL url = getURL();
	if (ResourceUtils.isJarURL(url)) {
		URL actualUrl = ResourceUtils.extractArchiveURL(url);
		if (actualUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
			return VfsResourceDelegate.getResource(actualUrl).getFile();
		}
		return ResourceUtils.getFile(actualUrl, "Jar URL");
	}
	else {
		return getFile();
	}
}
 
Example 17
Source File: JarUtils.java    From spring-boot-jar-resources with Apache License 2.0 4 votes vote down vote up
@SneakyThrows
public static File getFile(Resource resource, String extractPath) {
    return ResourceUtils.isJarURL(resource.getURL()) ? getFromJar(resource, extractPath) : resource.getFile();
}
 
Example 18
Source File: DefaultPersistenceUnitManager.java    From java-technology-stack with MIT License 4 votes vote down vote up
private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
	if (this.componentsIndex != null) {
		Set<String> candidates = new HashSet<>();
		for (AnnotationTypeFilter filter : entityTypeFilters) {
			candidates.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);
	}
}
 
Example 19
Source File: DefaultPersistenceUnitManager.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
	if (this.componentsIndex != null) {
		Set<String> candidates = new HashSet<>();
		for (AnnotationTypeFilter filter : entityTypeFilters) {
			candidates.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);
	}
}
 
Example 20
Source File: PathMatchingResourcePatternResolver.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Return whether the given resource handle indicates a jar resource
 * that the {@code doFindPathMatchingJarResources} method can handle.
 * <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)
 * @see #doFindPathMatchingJarResources
 * @see org.springframework.util.ResourceUtils#isJarURL
 */
protected boolean isJarResource(Resource resource) throws IOException {
	return ResourceUtils.isJarURL(resource.getURL());
}