Java Code Examples for org.springframework.core.io.Resource#getURL()

The following examples show how to use org.springframework.core.io.Resource#getURL() . 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: WebJarResourceResolver.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected void scanResources(ApplicationContext applicationContext) throws IOException {
    // retrieve all resources from all JARs
    Resource[] resources = applicationContext.getResources("classpath*:META-INF/resources/webjars/**");

    for (Resource resource : resources) {
        URL url = resource.getURL();
        String urlString = url.toString();
        int classPathStartIndex = urlString.indexOf(CLASSPATH_WEBJAR_PREFIX);
        if (classPathStartIndex > 0) {
            String resourcePath = urlString.substring(classPathStartIndex + CLASSPATH_WEBJAR_PREFIX.length());
            if (!Strings.isNullOrEmpty(resourcePath)
                    && !resourcePath.endsWith("/")) {
                mapping.put(resourcePath, new UrlHolder(url));
            }
        } else {
            log.debug("Ignored WebJAR resource {} since it does not contain class path prefix {}",
                    urlString, CLASSPATH_WEBJAR_PREFIX);
        }
    }

    this.fullPathIndex = getFullPathIndex(mapping.keySet());
}
 
Example 2
Source File: ResourceLoaderClassLoadHelper.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public URL getResource(String name) {
	Assert.state(this.resourceLoader != null, "ResourceLoaderClassLoadHelper not initialized");
	Resource resource = this.resourceLoader.getResource(name);
	if (resource.exists()) {
		try {
			return resource.getURL();
		}
		catch (IOException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn("Could not load " + resource);
			}
			return null;
		}
	}
	else {
		return getClassLoader().getResource(name);
	}
}
 
Example 3
Source File: ResourceLoaderClassLoadHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public URL getResource(String name) {
	Resource resource = this.resourceLoader.getResource(name);
	if (resource.exists()) {
		try {
			return resource.getURL();
		}
		catch (IOException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn("Could not load " + resource);
			}
			return null;
		}
	}
	else {
		return getClassLoader().getResource(name);
	}
}
 
Example 4
Source File: JourneySimulator.java    From istio-fleetman with MIT License 6 votes vote down vote up
/**
 * Read the data from the resources directory - should work for an executable Jar as
 * well as through direct execution
 */
@PostConstruct
private void setUpData() 
{
	PathMatchingResourcePatternResolver path = new PathMatchingResourcePatternResolver();
	try
	{
		for (Resource nextFile : path.getResources("tracks/*"))
		{
			URL resource = nextFile.getURL();
			File f = new File(resource.getFile()); 
			String vehicleName = VehicleNameUtils.prettifyName(f.getName());				
			vehicleNames.add(vehicleName);
			populateReportQueueForVehicle(vehicleName);
		}
	}
	catch (IOException e)
	{
		throw new RuntimeException(e);
	}
	positionTracker.clearHistories();
}
 
Example 5
Source File: StyleConverterServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
private URL getUrl(String resourceLocation) throws LayerException {
	if (resourceLocation.startsWith(GeomajasConstant.CLASSPATH_URL_PREFIX)) {
		resourceLocation = resourceLocation.substring(GeomajasConstant.CLASSPATH_URL_PREFIX.length());
	}
	Resource resource = applicationContext.getResource(resourceLocation);
	try {
		if (resource.exists()) {
			return resource.getURL();
		} else {
			String gwtResource = GeomajasConstant.CLASSPATH_URL_PREFIX + resourceLocation;
			Resource[] matching = applicationContext.getResources(gwtResource);
			if (matching.length > 0) {
				return matching[0].getURL();
			} else {
				log.warn(MISSING_RESOURCE, gwtResource);
				throw new LayerException(ExceptionCode.RESOURCE_NOT_FOUND, gwtResource);
			}
		}
	} catch (IOException e) {
		log.warn(MISSING_RESOURCE, resourceLocation);
		throw new LayerException(e, ExceptionCode.RESOURCE_NOT_FOUND, resourceLocation);
	}
}
 
Example 6
Source File: ControlledValidationXmlBeanDefinitionReader.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) {
    // sadly, the Spring class we are extending has the critical function
    // getValidationModeForResource
    // marked private instead of protected, so trickery is called for here.
    boolean suppressValidation = false;
    try {
        URL url = resource.getURL();
        if (url.getFile().contains("META-INF/cxf/")) {
            suppressValidation = true;
        }
    } catch (IOException e) {
        // this space intentionally left blank.
    }

    int savedValidation = visibleValidationMode;
    if (suppressValidation) {
        setValidationMode(VALIDATION_NONE);
    }
    int r = super.doLoadBeanDefinitions(inputSource, resource);
    setValidationMode(savedValidation);
    return r;
}
 
Example 7
Source File: DefaultModuleDefinition.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
protected void checkNameMatchesSelf() throws IOException {
    String expectedLocation = ModuleLocationUtils.getModuleLocation(baseDir, name);
    Resource self = resolver.getResource(expectedLocation);

    if (!self.exists()) {
        throw new IOException("Resource [" + location() + "] is expected to exist at [" + expectedLocation + "] please ensure the name property is correct");
    }

    String moduleUrl = moduleProperties.getURL().toExternalForm();
    String selfUrl = self.getURL().toExternalForm();

    if (!moduleUrl.equals(selfUrl)) {
        throw new IOException("Resource [" + location() + "] and [" + self.getURL() + "] do not appear to be the same resource, " +
            "please ensure the name property is correct or that the " + "module is not defined twice");
    }
}
 
Example 8
Source File: DefaultPersistenceUnitManager.java    From spring4-understanding with Apache License 2.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 {
		Resource res = this.resourcePatternResolver.getResource(this.defaultPersistenceUnitRootLocation);
		return res.getURL();
	}
	catch (IOException ex) {
		throw new PersistenceException("Unable to resolve persistence unit root URL", ex);
	}
}
 
Example 9
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 10
Source File: MockPortletContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public URL getResource(String path) throws MalformedURLException {
	Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
	try {
		return resource.getURL();
	}
	catch (IOException ex) {
		logger.info("Couldn't get URL for " + resource, ex);
		return null;
	}
}
 
Example 11
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 12
Source File: JourneySimulator.java    From k8s-fleetman with MIT License 5 votes vote down vote up
/**
 * Read the data from the resources directory - should work for an executable Jar as
 * well as through direct execution
 */
private Map<String, List<String>> setUpData() 
{
	Map<String, List<String>> reports = new HashMap<>();
	PathMatchingResourcePatternResolver path = new PathMatchingResourcePatternResolver();

	try
	{
		for (Resource nextFile : path.getResources("tracks/*"))
		{
			URL resource = nextFile.getURL();
			File f = new File(resource.getFile()); 
			String vehicleName = VehicleNameUtils.prettifyName(f.getName());
			InputStream is = PositionsimulatorApplication.class.getResourceAsStream("/tracks/" + f.getName());
			try (Scanner sc = new Scanner(is))
			{
				List<String> thisVehicleReports = new ArrayList<>();
				while (sc.hasNextLine())
				{
					String nextReport = sc.nextLine();
					thisVehicleReports.add(nextReport);
				}
				reports.put(vehicleName,thisVehicleReports);
			}
		}
		return Collections.unmodifiableMap(reports);
	}
	catch (IOException e)
	{
		throw new RuntimeException(e);
	}
}
 
Example 13
Source File: TemplatedProjectInitializer.java    From ogham with Apache License 2.0 5 votes vote down vote up
private void copy(String resourceFolder, Path generatedProjectPath) throws IOException {
	ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
	Resource[] resources = resolver.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceFolder + "/**");
	for (Resource resource : resources) {
		if (resource.exists() && resource.isReadable() && resource.contentLength() > 0) {
			URL url = resource.getURL();
			String urlString = url.toExternalForm();
			String targetName = urlString.substring(urlString.indexOf(resourceFolder) + resourceFolder.length() + 1);
			Path destination = generatedProjectPath.resolve(targetName);
			Files.createDirectories(destination.getParent());
			Files.copy(resource.getInputStream(), destination);
		}
	}
}
 
Example 14
Source File: ServerTraceMetadataLoaderService.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private URL toUrl(Resource resource) {
    try {
        return resource.getURL();
    } catch (IOException e) {
        throw new IllegalStateException("Failed to get url from " + resource.getDescription(), e);
    }
}
 
Example 15
Source File: HazelcastJetServerConfiguration.java    From hazelcast-jet-contrib with Apache License 2.0 5 votes vote down vote up
private static JetConfig getJetConfig(Resource configLocation) throws IOException {
    URL configUrl = configLocation.getURL();
    String configFileName = configUrl.getPath();
    InputStream inputStream = configUrl.openStream();
    if (configFileName.endsWith(".yaml") || configFileName.endsWith("yml")) {
        return new YamlJetConfigBuilder(inputStream).build();
    }
    return new XmlJetConfigBuilder(inputStream).build();
}
 
Example 16
Source File: MockPortletContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public URL getResource(String path) throws MalformedURLException {
	Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
	try {
		return resource.getURL();
	}
	catch (IOException ex) {
		logger.info("Couldn't get URL for " + resource, ex);
		return null;
	}
}
 
Example 17
Source File: StyleConverterServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
public URL locateResource(String uri) {
	URL url = null;
	try {
		Resource resource = resourceService.find(uri);
		url = resource.getURL();
	} catch (Exception e) { // NOSONAR
		log.warn(MISSING_RESOURCE, uri);
	}
	return url;
}
 
Example 18
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 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: LocalJaxWsServiceFactory.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Set the WSDL document URL as a {@link Resource}.
 * @throws IOException
 * @since 3.2
 */
public void setWsdlDocumentResource(Resource wsdlDocumentResource) throws IOException {
	Assert.notNull(wsdlDocumentResource, "WSDL Resource must not be null.");
	this.wsdlDocumentUrl = wsdlDocumentResource.getURL();
}