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

The following examples show how to use org.springframework.util.ResourceUtils#isUrl() . 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: ResourceWebHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Identifies invalid resource paths. By default rejects:
 * <ul>
 * <li>Paths that contain "WEB-INF" or "META-INF"
 * <li>Paths that contain "../" after a call to
 * {@link StringUtils#cleanPath}.
 * <li>Paths that represent a {@link ResourceUtils#isUrl
 * valid URL} or would represent one after the leading slash is removed.
 * </ul>
 * <p><strong>Note:</strong> this method assumes that leading, duplicate '/'
 * or control characters (e.g. white space) have been trimmed so that the
 * path starts predictably with a single '/' or does not have one.
 * @param path the path to validate
 * @return {@code true} if the path is invalid, {@code false} otherwise
 */
protected boolean isInvalidPath(String path) {
	if (path.contains("WEB-INF") || path.contains("META-INF")) {
		if (logger.isWarnEnabled()) {
			logger.warn("Path with \"WEB-INF\" or \"META-INF\": [" + path + "]");
		}
		return true;
	}
	if (path.contains(":/")) {
		String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
		if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
			if (logger.isWarnEnabled()) {
				logger.warn("Path represents URL or has \"url:\" prefix: [" + path + "]");
			}
			return true;
		}
	}
	if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
		if (logger.isWarnEnabled()) {
			logger.warn("Path contains \"../\" after call to StringUtils#cleanPath: [" + path + "]");
		}
		return true;
	}
	return false;
}
 
Example 2
Source File: DefaultArchivaAdministration.java    From archiva with Apache License 2.0 6 votes vote down vote up
private String fixUrl(String url, String propertyName)  throws RepositoryAdminException {
    if ( StringUtils.isNotEmpty( url ) )
    {
        if ( !ResourceUtils.isUrl( url ) )
        {
            throw new RepositoryAdminException( "Bad URL in " + propertyName + ": " + url );
        }
        try {
            URI urlToCheck = new URI(url);
            return urlToCheck.toString();
        } catch (URISyntaxException e) {
            throw new RepositoryAdminException( "Bad URL in " + propertyName + ": " + url );
        }
    }
    return url;

}
 
Example 3
Source File: ResourceHttpRequestHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Identifies invalid resource paths. By default rejects:
 * <ul>
 * <li>Paths that contain "WEB-INF" or "META-INF"
 * <li>Paths that contain "../" after a call to
 * {@link org.springframework.util.StringUtils#cleanPath}.
 * <li>Paths that represent a {@link org.springframework.util.ResourceUtils#isUrl
 * valid URL} or would represent one after the leading slash is removed.
 * </ul>
 * <p><strong>Note:</strong> this method assumes that leading, duplicate '/'
 * or control characters (e.g. white space) have been trimmed so that the
 * path starts predictably with a single '/' or does not have one.
 * @param path the path to validate
 * @return {@code true} if the path is invalid, {@code false} otherwise
 * @since 3.0.6
 */
protected boolean isInvalidPath(String path) {
	if (path.contains("WEB-INF") || path.contains("META-INF")) {
		if (logger.isWarnEnabled()) {
			logger.warn("Path with \"WEB-INF\" or \"META-INF\": [" + path + "]");
		}
		return true;
	}
	if (path.contains(":/")) {
		String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
		if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
			if (logger.isWarnEnabled()) {
				logger.warn("Path represents URL or has \"url:\" prefix: [" + path + "]");
			}
			return true;
		}
	}
	if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
		if (logger.isWarnEnabled()) {
			logger.warn("Path contains \"../\" after call to StringUtils#cleanPath: [" + path + "]");
		}
		return true;
	}
	return false;
}
 
Example 4
Source File: AbstractAppContextLoader.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected void replaceLocationsFromConf(String[] locations) {
    String confDirProp = AppContext.getProperty("cuba.confDir");
    if (confDirProp == null)
        throw new IllegalStateException("cuba.confDir app property is not set");
    File confDir = new File(confDirProp);
    for (int i = 0; i < locations.length; i++) {
        String location = locations[i];
        if (ResourceUtils.isUrl(location))
            continue;
        if (location.startsWith("/"))
            location = location.substring(1);
        File file = new File(confDir, location);
        if (file.exists()) {
            locations[i] = file.toURI().toString();
        }
    }
}
 
Example 5
Source File: ConfigurationResourceLoader.java    From cuba with Apache License 2.0 6 votes vote down vote up
/**
 * Search for a resource according to the following rules:
 * <ul>
 * <li>If the location represents an URL, return a new {@link org.springframework.core.io.UrlResource} for
 * this URL.</li>
 * <li>Try to find a file below the {@code conf} directory using {@code location} as relative path.
 * If found, return a new {@link org.springframework.core.io.UrlResource} for this file.</li>
 * <li> Otherwise return a new {@link org.springframework.core.io.ClassPathResource} to retrieve content
 * from classpath.</li>
 * </ul>
 *
 * @param location resource location
 * @return resource reference
 */
@Override
public Resource getResource(String location) {
    if (ResourceUtils.isUrl(location)) {
        return super.getResource(location);
    } else {
        if (location.startsWith("/"))
            location = location.substring(1);
        File file = new File(confDir, location);
        if (file.exists()) {
            location = file.toURI().toString();
        } else {
            location = "classpath:" + location;
        }
        return super.getResource(location);
    }
}
 
Example 6
Source File: DesiredCapabilityBuilder.java    From AppiumTestDistribution with GNU General Public License v3.0 6 votes vote down vote up
private void capabilityObject(DesiredCapabilities desiredCapabilities,
                              JSONObject platFormCapabilities, String key) {
    String appCapability = "app";
    if (appCapability.equals(key)) {
        Object values = platFormCapabilities.get(appCapability);
        List<HostArtifact> hostArtifacts = ArtifactsUploader.getInstance()
            .getHostArtifacts();
        String hostAppPath = hostAppPath(values, hostArtifacts);
        Path path = FileSystems.getDefault().getPath(hostAppPath);
        if (AppiumDeviceManager.getAppiumDevice().getDevice().isCloud()
            || ResourceUtils.isUrl(hostAppPath)) {
            desiredCapabilities.setCapability(appCapability, hostAppPath);
        } else {
            desiredCapabilities.setCapability(appCapability,
                path.normalize().toAbsolutePath().toString());
        }
    } else {
        desiredCapabilities.setCapability(key, platFormCapabilities.get(key));
    }
}
 
Example 7
Source File: ResourceHttpRequestHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Identifies invalid resource paths. By default rejects:
 * <ul>
 * <li>Paths that contain "WEB-INF" or "META-INF"
 * <li>Paths that contain "../" after a call to
 * {@link org.springframework.util.StringUtils#cleanPath}.
 * <li>Paths that represent a {@link org.springframework.util.ResourceUtils#isUrl
 * valid URL} or would represent one after the leading slash is removed.
 * </ul>
 * <p><strong>Note:</strong> this method assumes that leading, duplicate '/'
 * or control characters (e.g. white space) have been trimmed so that the
 * path starts predictably with a single '/' or does not have one.
 * @param path the path to validate
 * @return {@code true} if the path is invalid, {@code false} otherwise
 * @since 3.0.6
 */
protected boolean isInvalidPath(String path) {
	if (path.contains("WEB-INF") || path.contains("META-INF")) {
		if (logger.isWarnEnabled()) {
			logger.warn("Path with \"WEB-INF\" or \"META-INF\": [" + path + "]");
		}
		return true;
	}
	if (path.contains(":/")) {
		String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
		if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
			if (logger.isWarnEnabled()) {
				logger.warn("Path represents URL or has \"url:\" prefix: [" + path + "]");
			}
			return true;
		}
	}
	if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
		if (logger.isWarnEnabled()) {
			logger.warn("Path contains \"../\" after call to StringUtils#cleanPath: [" + path + "]");
		}
		return true;
	}
	return false;
}
 
Example 8
Source File: PathUtils.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
/**
 * Identifies invalid resource paths. By default rejects:
 * <ul>
 * <li>Paths that contain "WEB-INF" or "META-INF"
 * <li>Paths that contain "../" after a call to {@link StringUtils#cleanPath}.
 * <li>Paths that represent a {@link org.springframework.util.ResourceUtils#isUrl
 * valid URL} or would represent one after the leading slash is removed.
 * </ul>
 * <p>
 * <strong>Note:</strong> this method assumes that leading, duplicate '/' or control
 * characters (e.g. white space) have been trimmed so that the path starts predictably
 * with a single '/' or does not have one.
 * @param path the path to validate
 * @return {@code true} if the path is invalid, {@code false} otherwise
 * @since 3.0.6
 */
public static boolean isInvalidPath(String path) {
	if (path.contains("WEB-INF") || path.contains("META-INF")) {
		if (logger.isWarnEnabled()) {
			logger.warn("Path with \"WEB-INF\" or \"META-INF\": [" + path + "]");
		}
		return true;
	}
	if (path.contains(":/")) {
		String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
		if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
			if (logger.isWarnEnabled()) {
				logger.warn(
						"Path represents URL or has \"url:\" prefix: [" + path + "]");
			}
			return true;
		}
	}
	if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
		if (logger.isWarnEnabled()) {
			logger.warn("Path contains \"../\" after call to StringUtils#cleanPath: ["
					+ path + "]");
		}
		return true;
	}
	return false;
}
 
Example 9
Source File: SAML2SPLogic.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static void validateUrl(final String url) {
    boolean isValid = true;
    if (url.contains("..")) {
        isValid = false;
    }
    if (isValid) {
        isValid = ResourceUtils.isUrl(url);
    }

    if (!isValid) {
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add("Invalid URL: " + url);
        throw sce;
    }
}
 
Example 10
Source File: FileEditor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void setAsText(String text) throws IllegalArgumentException {
	if (!StringUtils.hasText(text)) {
		setValue(null);
		return;
	}

	// Check whether we got an absolute file path without "file:" prefix.
	// For backwards compatibility, we'll consider those as straight file path.
	if (!ResourceUtils.isUrl(text)) {
		File file = new File(text);
		if (file.isAbsolute()) {
			setValue(file);
			return;
		}
	}

	// Proceed with standard resource location parsing.
	this.resourceEditor.setAsText(text);
	Resource resource = (Resource) this.resourceEditor.getValue();

	// If it's a URL or a path pointing to an existing resource, use it as-is.
	if (ResourceUtils.isUrl(text) || resource.exists()) {
		try {
			setValue(resource.getFile());
		}
		catch (IOException ex) {
			throw new IllegalArgumentException(
					"Could not retrieve File for " + resource + ": " + ex.getMessage());
		}
	}
	else {
		// Create a relative File reference and hope for the best.
		setValue(new File(text));
	}
}
 
Example 11
Source File: ResourceHttpRequestHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Identifies invalid resource paths. By default rejects:
 * <ul>
 * <li>Paths that contain "WEB-INF" or "META-INF"
 * <li>Paths that contain "../" after a call to
 * {@link org.springframework.util.StringUtils#cleanPath}.
 * <li>Paths that represent a {@link org.springframework.util.ResourceUtils#isUrl
 * valid URL} or would represent one after the leading slash is removed.
 * </ul>
 * <p><strong>Note:</strong> this method assumes that leading, duplicate '/'
 * or control characters (e.g. white space) have been trimmed so that the
 * path starts predictably with a single '/' or does not have one.
 * @param path the path to validate
 * @return {@code true} if the path is invalid, {@code false} otherwise
 */
protected boolean isInvalidPath(String path) {
	if (logger.isTraceEnabled()) {
		logger.trace("Applying \"invalid path\" checks to path: " + path);
	}
	if (path.contains("WEB-INF") || path.contains("META-INF")) {
		if (logger.isTraceEnabled()) {
			logger.trace("Path contains \"WEB-INF\" or \"META-INF\".");
		}
		return true;
	}
	if (path.contains(":/")) {
		String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
		if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
			if (logger.isTraceEnabled()) {
				logger.trace("Path represents URL or has \"url:\" prefix.");
			}
			return true;
		}
	}
	if (path.contains("../")) {
		path = StringUtils.cleanPath(path);
		if (path.contains("../")) {
			if (logger.isTraceEnabled()) {
				logger.trace("Path contains \"../\" after call to StringUtils#cleanPath.");
			}
			return true;
		}
	}
	return false;
}
 
Example 12
Source File: FileEditor.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
public void setAsText(String text) throws IllegalArgumentException {
	if (!StringUtils.hasText(text)) {
		setValue(null);
		return;
	}

	// Check whether we got an absolute file path without "file:" prefix.
	// For backwards compatibility, we'll consider those as straight file path.
	if (!ResourceUtils.isUrl(text)) {
		File file = new File(text);
		if (file.isAbsolute()) {
			setValue(file);
			return;
		}
	}

	// Proceed with standard resource location parsing.
	this.resourceEditor.setAsText(text);
	Resource resource = (Resource) this.resourceEditor.getValue();

	// If it's a URL or a path pointing to an existing resource, use it as-is.
	if (ResourceUtils.isUrl(text) || resource.exists()) {
		try {
			setValue(resource.getFile());
		}
		catch (IOException ex) {
			throw new IllegalArgumentException(
					"Could not retrieve File for " + resource + ": " + ex.getMessage());
		}
	}
	else {
		// Create a relative File reference and hope for the best.
		setValue(new File(text));
	}
}
 
Example 13
Source File: RemotingServlet.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public String getContextConfigLocation() {
    String configProperty = AppContext.getProperty(SPRING_CONTEXT_CONFIG);
    if (StringUtils.isBlank(configProperty)) {
        throw new IllegalStateException("Missing " + SPRING_CONTEXT_CONFIG + " application property");
    }
    File baseDir = new File(AppContext.getProperty("cuba.confDir"));

    StringTokenizer tokenizer = new StringTokenizer(configProperty);
    String[] tokenArray = tokenizer.getTokenArray();
    StringBuilder locations = new StringBuilder();
    for (String token : tokenArray) {
        String location;
        if (ResourceUtils.isUrl(token)) {
            location = token;
        } else {
            if (token.startsWith("/"))
                token = token.substring(1);
            File file = new File(baseDir, token);
            if (file.exists()) {
                location = file.toURI().toString();
            } else {
                location = "classpath:" + token;
            }
        }
        locations.append(location).append(" ");
    }
    return locations.toString();
}
 
Example 14
Source File: ResourceHttpRequestHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Identifies invalid resource paths. By default rejects:
 * <ul>
 * <li>Paths that contain "WEB-INF" or "META-INF"
 * <li>Paths that contain "../" after a call to
 * {@link org.springframework.util.StringUtils#cleanPath}.
 * <li>Paths that represent a {@link org.springframework.util.ResourceUtils#isUrl
 * valid URL} or would represent one after the leading slash is removed.
 * </ul>
 * <p><strong>Note:</strong> this method assumes that leading, duplicate '/'
 * or control characters (e.g. white space) have been trimmed so that the
 * path starts predictably with a single '/' or does not have one.
 * @param path the path to validate
 * @return {@code true} if the path is invalid, {@code false} otherwise
 */
protected boolean isInvalidPath(String path) {
	if (logger.isTraceEnabled()) {
		logger.trace("Applying \"invalid path\" checks to path: " + path);
	}
	if (path.contains("WEB-INF") || path.contains("META-INF")) {
		if (logger.isTraceEnabled()) {
			logger.trace("Path contains \"WEB-INF\" or \"META-INF\".");
		}
		return true;
	}
	if (path.contains(":/")) {
		String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
		if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
			if (logger.isTraceEnabled()) {
				logger.trace("Path represents URL or has \"url:\" prefix.");
			}
			return true;
		}
	}
	if (path.contains("..")) {
		path = StringUtils.cleanPath(path);
		if (path.contains("../")) {
			if (logger.isTraceEnabled()) {
				logger.trace("Path contains \"../\" after call to StringUtils#cleanPath.");
			}
			return true;
		}
	}
	return false;
}
 
Example 15
Source File: PathResourceLookupFunction.java    From java-technology-stack with MIT License 5 votes vote down vote up
private boolean isInvalidPath(String path) {
	if (path.contains("WEB-INF") || path.contains("META-INF")) {
		return true;
	}
	if (path.contains(":/")) {
		String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
		if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
			return true;
		}
	}
	if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
		return true;
	}
	return false;
}
 
Example 16
Source File: ArtifactsUploader.java    From AppiumTestDistribution with GNU General Public License v3.0 5 votes vote down vote up
private String getArtifactPath(String hostMachine, String artifact) throws Exception {
    String path;
    if (!isCloud(hostMachine) && !isLocalhost(hostMachine) && !ResourceUtils.isUrl(artifact)) {
        path = uploadFile(hostMachine, artifact);
    } else {
        path = artifact;
    }
    return path;
}
 
Example 17
Source File: PathResourceLookupFunction.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private boolean isInvalidPath(String path) {
	if (path.contains("WEB-INF") || path.contains("META-INF")) {
		return true;
	}
	if (path.contains(":/")) {
		String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
		if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
			return true;
		}
	}
	if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
			return true;
		}
	return false;
}
 
Example 18
Source File: AbstractWebAppContextLoader.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected void loadPropertiesFromConfig(ServletContext sc, Properties properties, String propsConfigName) {
    SpringProfileSpecificNameResolver nameResolver = new SpringProfileSpecificNameResolver(sc);
    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    StringTokenizer tokenizer = new StringTokenizer(propsConfigName);
    tokenizer.setQuoteChar('"');
    for (String str : tokenizer.getTokenArray()) {
        log.trace("Processing properties location: {}", str);
        String baseName = StringSubstitutor.replaceSystemProperties(str);
        for (String name : nameResolver.getDerivedNames(baseName)) {
            InputStream stream = null;
            try {
                if (ResourceUtils.isUrl(name) || name.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
                    Resource resource = resourceLoader.getResource(name);
                    if (resource.exists())
                        stream = resource.getInputStream();
                } else {
                    stream = sc.getResourceAsStream(name);
                }

                if (stream != null) {
                    log.info("Loading app properties from {}", name);
                    BOMInputStream bomInputStream = new BOMInputStream(stream);
                    try (Reader reader = new InputStreamReader(bomInputStream, StandardCharsets.UTF_8)) {
                        properties.load(reader);
                    }
                } else {
                    log.trace("Resource {} not found, ignore it", name);
                }
            } catch (IOException e) {
                throw new RuntimeException("Unable to read properties from stream", e);
            } finally {
                try {
                    if (stream != null) {
                        stream.close();
                    }
                } catch (final IOException ioe) {
                    // ignore
                }
            }
        }
    }
}
 
Example 19
Source File: ResourcePatternUtils.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Return whether the given resource location is a URL: either a
 * special "classpath" or "classpath*" pseudo URL or a standard URL.
 * @param resourceLocation the location String to check
 * @return whether the location qualifies as a URL
 * @see ResourcePatternResolver#CLASSPATH_ALL_URL_PREFIX
 * @see org.springframework.util.ResourceUtils#CLASSPATH_URL_PREFIX
 * @see org.springframework.util.ResourceUtils#isUrl(String)
 * @see java.net.URL
 */
public static boolean isUrl(String resourceLocation) {
	return (resourceLocation != null &&
			(resourceLocation.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX) ||
					ResourceUtils.isUrl(resourceLocation)));
}
 
Example 20
Source File: ResourcePatternUtils.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Return whether the given resource location is a URL: either a
 * special "classpath" or "classpath*" pseudo URL or a standard URL.
 * @param resourceLocation the location String to check
 * @return whether the location qualifies as a URL
 * @see ResourcePatternResolver#CLASSPATH_ALL_URL_PREFIX
 * @see org.springframework.util.ResourceUtils#CLASSPATH_URL_PREFIX
 * @see org.springframework.util.ResourceUtils#isUrl(String)
 * @see java.net.URL
 */
public static boolean isUrl(@Nullable String resourceLocation) {
	return (resourceLocation != null &&
			(resourceLocation.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX) ||
					ResourceUtils.isUrl(resourceLocation)));
}