Java Code Examples for org.springframework.util.StringUtils.cleanPath()

The following are Jave code examples for showing how to use cleanPath() of the org.springframework.util.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: AIweb   File: UploadKaServiceImpl.java   Source Code and License Vote up 8 votes
@Override
public void store(MultipartFile file) {
    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    try {
        if (file.isEmpty()) {
            throw new UploadException("Failed to store empty file " + filename);
        }
        if (filename.contains("..")) {
            // This is a security check
            throw new UploadException(
                    "Cannot store file with relative path outside current directory "
                            + filename);
        }
        Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new UploadException("Failed to store file " + filename, e);
    }
}
 
Example 2
Project: jmzTab-m   File: FileSystemStorageService.java   Source Code and License Vote up 7 votes
@Override
public UserSessionFile store(MultipartFile file, String sessionId) {
    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    try {
        if (file.isEmpty()) {
            throw new StorageException(
                "Failed to store empty file " + filename);
        }

        Path sessionPath = buildSessionPath(sessionId);
        Files.createDirectories(sessionPath);
        Files.copy(file.getInputStream(), buildPathToFile(sessionPath,
            filename),
            StandardCopyOption.REPLACE_EXISTING);
        return new UserSessionFile(filename, sessionId);
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }
}
 
Example 3
Project: spring-boot-tus   File: StorageServiceImpl.java   Source Code and License Vote up 6 votes
public int processStream(String uuid, InputStream inputStream) throws Exception {
    String filename = StringUtils.cleanPath(uuid);
    File file = new File(storageDir.resolve(filename).toString());

    if (!file.isFile()){
        new FileOutputStream(file).close();
        if(!file.isFile()){
            log.error("Cannot create new file");
            throw new TusPermissionDeniedException("Cannot create new file");
        }
    }

    InputStream storageFile;
    try{
        storageFile = new FileInputStream(file);
    }catch(IOException e){
        log.error("Cannot read old file");
        throw new TusPermissionDeniedException("Cannot read old file");
    }

    storageFile = new SequenceInputStream(storageFile, inputStream);
    Files.copy(storageFile, storageDir.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
    file = new File(storageDir.resolve(filename).toString());

    return (int) file.length();
}
 
Example 4
Project: artifactory-resource   File: DirectoryTests.java   Source Code and License Vote up 6 votes
@Test
public void toStringShouldReturnFilePath() throws Exception {
	File file = this.temporaryFolder.newFolder();
	Directory directory = new Directory(file);
	String expected = StringUtils.cleanPath(file.getPath());
	assertThat(directory.toString()).isEqualTo(expected);
}
 
Example 5
Project: AIweb   File: UploadServiceImpl.java   Source Code and License Vote up 6 votes
@Override
public void store(MultipartFile file) {
    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    try {
        if (file.isEmpty()) {
            throw new UploadException("Failed to store empty file " + filename);
        }
        if (filename.contains("..")) {
            // This is a security check
            throw new UploadException(
                    "Cannot store file with relative path outside current directory "
                            + filename);
        }
        Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new UploadException("Failed to store file " + filename, e);
    }
}
 
Example 6
Project: gemini.blueprint   File: JarCreator.java   Source Code and License Vote up 5 votes
/**
 * Small utility method used for determining the file name by striping the
 * root path from the file full path.
 * 
 * @param rootPath
 * @param resource
 * @return
 */
private String determineRelativeName(String rootPath, Resource resource) {
	try {
		String path = StringUtils.cleanPath(resource.getURL().getPath());
		return path.substring(path.indexOf(rootPath) + rootPath.length());
	}
	catch (IOException ex) {
		throw (RuntimeException) new IllegalArgumentException("illegal resource " + resource.toString()).initCause(ex);
	}
}
 
Example 7
Project: gemini.blueprint   File: OsgiBundleResource.java   Source Code and License Vote up 5 votes
/**
 * 
 * Constructs a new <code>OsgiBundleResource</code> instance.
 * 
 * @param bundle OSGi bundle used by this resource
 * @param path resource path inside the bundle.
 */
public OsgiBundleResource(Bundle bundle, String path) {
	Assert.notNull(bundle, "Bundle must not be null");
	this.bundle = bundle;

	// check path
	Assert.notNull(path, "Path must not be null");

	this.path = StringUtils.cleanPath(path);

	this.searchType = OsgiResourceUtils.getSearchType(this.path);

	switch (this.searchType) {
		case OsgiResourceUtils.PREFIX_TYPE_NOT_SPECIFIED:
			pathWithoutPrefix = path;
			break;
		case OsgiResourceUtils.PREFIX_TYPE_BUNDLE_SPACE:
			pathWithoutPrefix = path.substring(BUNDLE_URL_PREFIX.length());
			break;
		case OsgiResourceUtils.PREFIX_TYPE_BUNDLE_JAR:
			pathWithoutPrefix = path.substring(BUNDLE_JAR_URL_PREFIX.length());
			break;
		case OsgiResourceUtils.PREFIX_TYPE_CLASS_SPACE:
			pathWithoutPrefix = path.substring(ResourceLoader.CLASSPATH_URL_PREFIX.length());
			break;
		// prefix unknown so the path will be resolved outside the context
		default:
			pathWithoutPrefix = null;
	}
}
 
Example 8
Project: lams   File: HierarchicalUriComponents.java   Source Code and License Vote up 5 votes
/**
 * Normalize the path removing sequences like "path/..".
 * @see StringUtils#cleanPath(String)
 */
@Override
public UriComponents normalize() {
	String normalizedPath = StringUtils.cleanPath(getPath());
	return new HierarchicalUriComponents(getScheme(), this.userInfo, this.host,
			this.port, new FullPathComponent(normalizedPath), this.queryParams,
			getFragment(), this.encoded, false);
}
 
Example 9
Project: spring-boot-tus   File: StorageServiceImpl.java   Source Code and License Vote up 5 votes
public Resource loadResource(String uuid) throws Exception {
    String filename = StringUtils.cleanPath(uuid);

    Resource resource = new UrlResource(storageDir.resolve(filename).toUri());
    if (resource.exists() || resource.isReadable()) {
        return resource;
    }
    else {
        throw new TusStorageException(filename);

    }
}
 
Example 10
Project: artifactory-resource   File: MavenMetadataGenerator.java   Source Code and License Vote up 5 votes
private void generate(Directory root, File pomFile) {
	String name = StringUtils.getFilename(pomFile.getName());
	String extension = StringUtils.getFilenameExtension(pomFile.getName());
	String prefix = name.substring(0, name.length() - extension.length() - 1);
	File[] files = pomFile.getParentFile().listFiles((f) -> include(f, prefix));
	MultiValueMap<File, MavenCoordinates> coordinates = new LinkedMultiValueMap<>();
	for (File file : files) {
		String rootPath = StringUtils.cleanPath(root.getFile().getPath());
		String relativePath = StringUtils.cleanPath(file.getPath())
				.substring(rootPath.length() + 1);
		coordinates.add(file.getParentFile(),
				MavenCoordinates.fromPath(relativePath));
	}
	coordinates.forEach(this::writeMetadata);
}
 
Example 11
Project: artifactory-resource   File: DirectoryScanner.java   Source Code and License Vote up 5 votes
private BiPredicate<Path, BasicFileAttributes> getFilter(Directory root,
		List<String> include, List<String> exclude) {
	PathFilter filter = new PathFilter(include, exclude);
	String rootPath = StringUtils.cleanPath(root.getFile().getPath());
	return (path, fileAttributes) -> {
		if (!path.toFile().isFile()) {
			return false;
		}
		String relativePath = StringUtils.cleanPath(path.toString())
				.substring(rootPath.length() + 1);
		return filter.isMatch(relativePath);
	};
}
 
Example 12
Project: artifactory-resource   File: InCommandTests.java   Source Code and License Vote up 5 votes
@Test
public void runShouldCallHandler() throws Exception {
	InRequest request = mock(InRequest.class);
	InResponse response = mock(InResponse.class);
	given(this.systemInput.read(InRequest.class)).willReturn(request);
	given(this.handler.handle(eq(request), any())).willReturn(response);
	File tempFolder = this.temporaryFolder.newFolder();
	String dir = StringUtils.cleanPath(tempFolder.getPath());
	this.command.run(new DefaultApplicationArguments(new String[] { "in", dir }));
	verify(this.handler).handle(eq(request), this.directoryCaptor.capture());
	verify(this.systemOutput).write(response);
	assertThat(this.directoryCaptor.getValue().getFile()).isEqualTo(tempFolder);
}
 
Example 13
Project: artifactory-resource   File: OutCommandTests.java   Source Code and License Vote up 5 votes
@Test
public void runShouldCallHandler() throws Exception {
	OutRequest request = mock(OutRequest.class);
	OutResponse response = mock(OutResponse.class);
	given(this.systemInput.read(OutRequest.class)).willReturn(request);
	given(this.handler.handle(eq(request), any())).willReturn(response);
	File tempFolder = this.temporaryFolder.newFolder();
	String dir = StringUtils.cleanPath(tempFolder.getPath());
	this.command.run(new DefaultApplicationArguments(new String[] { "out", dir }));
	verify(this.handler).handle(eq(request), this.directoryCaptor.capture());
	verify(this.systemOutput).write(response);
	assertThat(this.directoryCaptor.getValue().getFile()).isEqualTo(tempFolder);
}
 
Example 14
Project: artifactory-resource   File: DirectoryTests.java   Source Code and License Vote up 5 votes
@Test
public void createFromArgsShouldUseArgument() throws Exception {
	File file = this.temporaryFolder.newFolder();
	String path = StringUtils.cleanPath(file.getPath());
	ApplicationArguments args = new DefaultApplicationArguments(
			new String[] { "in", path });
	Directory directory = Directory.fromArgs(args);
	assertThat(directory.getFile()).isEqualTo(file);
}
 
Example 15
Project: gemini.blueprint   File: AbstractSingleSpringContextTests.java   Source Code and License Vote up 4 votes
/**
 * Subclasses can override this method to return the locations of their
 * config files, unless they override {@link #contextKey()} and
 * {@link #loadContext(Object)} instead.
 * <p>A plain path will be treated as class path location, e.g.:
 * "org/springframework/whatever/foo.xml". Note however that you may prefix
 * path locations with standard Spring resource prefixes. Therefore, a
 * config location path prefixed with "classpath:" with behave the same as a
 * plain path, but a config location such as
 * "file:/some/path/path/location/appContext.xml" will be treated as a
 * filesystem location.
 * <p>The default implementation builds config locations for the config paths
 * specified through {@link #getConfigPaths()}.
 * @return an array of config locations
 * @see #getConfigPaths()
 * @see org.springframework.core.io.ResourceLoader#getResource(String)
 */
protected String[] getConfigLocations() {
	String[] paths = getConfigPaths();
	String[] locations = new String[paths.length];
	for (int i = 0; i < paths.length; i++) {
		String path = paths[i];
		if (path.startsWith("/")) {
			locations[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
		}
		else {
			locations[i] = ResourceUtils.CLASSPATH_URL_PREFIX +
					StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(getClass()) + "/" + path);
		}
	}
	return locations;
}
 
Example 16
Project: artifactory-resource   File: DeployableFileArtifact.java   Source Code and License Vote up 4 votes
private static String cleanPath(String path) {
	path = StringUtils.cleanPath(path);
	path = (path.startsWith("/") ? path : "/" + path);
	return path;
}
 
Example 17
Project: artifactory-resource   File: Directory.java   Source Code and License Vote up 4 votes
@Override
public String toString() {
	return StringUtils.cleanPath(this.file.getPath());
}
 
Example 18
Project: artifactory-resource   File: Directory.java   Source Code and License Vote up 4 votes
public Directory getSubDirectory(String path) {
	if (StringUtils.hasText(path)) {
		return new Directory(new File(this.file, StringUtils.cleanPath(path)));
	}
	return this;
}
 
Example 19
Project: artifactory-resource   File: FileComparatorTests.java   Source Code and License Vote up 4 votes
private File makeFile(String path) {
	String tempPath = this.temporaryFolder.getRoot().getAbsolutePath();
	return new File(
			StringUtils.cleanPath(tempPath) + "/" + StringUtils.cleanPath(path));
}
 
Example 20
Project: artifactory-resource   File: DirectoryScannerTests.java   Source Code and License Vote up 4 votes
private String relativePath(Directory directory, File file) {
	String root = StringUtils.cleanPath(directory.getFile().getPath());
	String path = StringUtils.cleanPath(file.getPath());
	return path.substring(root.length());
}