List of usage examples for java.nio.file Path startsWith
default boolean startsWith(String other)
From source file:com.google.devtools.build.android.PackedResourceTarExpander.java
@Override public ImmutableList<Path> modify(ImmutableList<Path> resourceRoots) { final Builder<Path> outDirs = ImmutableList.builder(); for (final Path unresolvedRoot : resourceRoots) { Path root = unresolvedRoot.toAbsolutePath(); try {/*from w w w .j a v a2 s .com*/ final Path packedResources = root.resolve("raw/blaze_internal_packed_resources.tar"); if (Files.exists(packedResources)) { Preconditions.checkArgument(root.startsWith(workingDirectory), "%s is not under %s", root, workingDirectory); final Path resourcePrefix = workingDirectory.relativize(root); final Path targetDirectory = out.resolve(resourcePrefix); outDirs.add(targetDirectory); copyRemainingResources(root, packedResources); // Group the unpacked resource by the path they came from. final Path tarOut = out.resolve("blaze_internal_packed_resources").resolve(resourcePrefix); unTarPackedResources(tarOut, packedResources); outDirs.add(tarOut); } else { outDirs.add(root); } } catch (IOException e) { Throwables.propagate(e); } } return outDirs.build(); }
From source file:de.unirostock.sems.caroweb.Converter.java
private void checkout(HttpServletRequest request, HttpServletResponse response, Path storage, String req) throws ServletException, IOException { Path target = storage.resolve(req).toAbsolutePath().normalize(); if (!target.startsWith(storage) || !Files.exists(target)) { error(request, response, "you're not allowed to download that file."); return;// ww w . j av a2 s. c om } try { String mime = target.toString().endsWith("omex") ? "application/zip" : "application/vnd.wf4ever.robundle+zip"; response.reset(); response.setBufferSize(CaRoWebutils.DEFAULT_BUFFER_SIZE); response.setContentType(mime); response.setHeader("Content-Length", String.valueOf(target.toFile().length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + req + "\""); response.setHeader("Expires", CaRoWebutils.downloadDateFormater .format(new Date(System.currentTimeMillis() + CaRoWebutils.CACHE_TIME * 1000))); response.setHeader("Cache-Control", "max-age=" + CaRoWebutils.CACHE_TIME); response.setHeader("Last-Modified", CaRoWebutils.downloadDateFormater .format(new Date(Files.getLastModifiedTime(target).toMillis()))); response.setHeader("ETag", GeneralTools.hash(target + "-" + Files.getLastModifiedTime(target))); BufferedInputStream input = new BufferedInputStream(new FileInputStream(target.toFile()), CaRoWebutils.DEFAULT_BUFFER_SIZE); BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(), CaRoWebutils.DEFAULT_BUFFER_SIZE); // pass the stream to client byte[] buffer = new byte[CaRoWebutils.DEFAULT_BUFFER_SIZE]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } input.close(); output.close(); return; } catch (IOException e) { // whoops, that's our fault. shouldn't happen. hopefully. LOGGER.error("unable to dump file " + target + " (at least not in an expected form)"); } error(request, response, "couldn't dump file"); }
From source file:adalid.util.meta.sql.MetaFolderSql.java
private Path getRelativeToBasePath(File file) { Path path = Paths.get(file.getPath()); if (path.startsWith(baseFolderPath)) { try {//from w ww. j a v a 2 s. c o m return baseFolderPath.relativize(path); } catch (IllegalArgumentException ex) { return path; } } else { return path; } }
From source file:org.codice.ddf.configuration.migration.AbstractMigrationTest.java
/** * Creates a test file with the given name in the specified directory resolved under ${ddf.home}. * * <p><i>Note:</i> The file will be created with the filename (no directory) as its content. * * @param dir the directory where to create the test file * @param name the name of the test file to create in the specified directory * @param resource the resource to copy to the test file * @return a path corresponding to the test file created (relativized from ${ddf.home}) * @throws IOException if an I/O error occurs while creating the test file *//*from ww w . ja v a 2 s. co m*/ public Path createFileFromResource(Path dir, String name, String resource) throws IOException { final File file = new File(ddfHome.resolve(dir).toFile(), name); final InputStream is = AbstractMigrationTest.class.getResourceAsStream(resource); if (is == null) { throw new FileNotFoundException("resource '" + resource + "' not found"); } dir.toFile().mkdirs(); FileUtils.copyInputStreamToFile(is, file); final Path path = file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS); return path.startsWith(ddfHome) ? ddfHome.relativize(path) : path; }
From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java
/** * Creates a test softlink with the given name in the specified directory resolved under * ${ddf.home}.// www .j ava2 s.c o m * * @param dir the directory where to create the test softlink * @param name the name of the test softlink to create in the specified directory * @param dest the destination path for the softlink * @return a path corresponding to the test softlink created (relativized from ${ddf.home}) * @throws IOException if an I/O error occurs while creating the test softlink * @throws UnsupportedOperationException if the implementation does not support symbolic links */ public Path createSoftLink(Path dir, String name, Path dest) throws IOException { final Path path = ddfHome.resolve(dir).resolve(name); dir.toFile().mkdirs(); try { Files.createSymbolicLink(path, dest); } catch (FileSystemException exception) { // symlinks cannot be reliably created on Windows throw new AssumptionViolatedException("The system cannot create symlinks.", exception); } final Path apath = path.toRealPath(LinkOption.NOFOLLOW_LINKS); return apath.startsWith(ddfHome) ? ddfHome.relativize(apath) : apath; }
From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java
/** * Creates a test file with the given name in the specified directory resolved under ${ddf.home}. * * <p><i>Note:</i> The file will be created with the filename (no directory) as its content. * * @param dir the directory where to create the test file * @param name the name of the test file to create in the specified directory * @return a path corresponding to the test file created (relativized from ${ddf.home}) * @throws IOException if an I/O error occurs while creating the test file *//*from w ww . j a v a2s . c o m*/ public Path createFile(Path dir, String name) throws IOException { final File file = new File(ddfHome.resolve(dir).toFile(), name); dir.toFile().mkdirs(); FileUtils.writeStringToFile(file, name, Charsets.UTF_8); final Path path = file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS); return path.startsWith(ddfHome) ? ddfHome.relativize(path) : path; }
From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java
/** * Creates a test file with the given name in the specified directory resolved under ${ddf.home}. * * <p><i>Note:</i> The file will be created with the filename (no directory) as its content. * * @param dir the directory where to create the test file * @param name the name of the test file to create in the specified directory * @param resource the resource to copy to the test file * @return a path corresponding to the test file created (relativized from ${ddf.home}) * @throws IOException if an I/O error occurs while creating the test file *//*from www . j a v a 2 s . c o m*/ public Path createFileFromResource(Path dir, String name, String resource) throws IOException { final File file = new File(ddfHome.resolve(dir).toFile(), name); final InputStream is = AbstractMigrationSupport.class.getResourceAsStream(resource); if (is == null) { throw new FileNotFoundException("resource '" + resource + "' not found"); } dir.toFile().mkdirs(); FileUtils.copyInputStreamToFile(is, file); final Path path = file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS); return path.startsWith(ddfHome) ? ddfHome.relativize(path) : path; }
From source file:com.facebook.buck.util.unarchive.Untar.java
@VisibleForTesting ImmutableSet<Path> extractArchive(Path archiveFile, ProjectFilesystem filesystem, Path filesystemRelativePath, Optional<Path> stripPath, ExistingFileMode existingFileMode, PatternsMatcher entriesToExclude, boolean writeSymlinksAfterCreatingFiles) throws IOException { ImmutableSet.Builder<Path> paths = ImmutableSet.builder(); HashSet<Path> dirsToTidy = new HashSet<>(); TreeMap<Path, Long> dirCreationTimes = new TreeMap<>(); DirectoryCreator creator = new DirectoryCreator(filesystem); // On windows, we create hard links instead of symlinks. This is fine, but the // destination file may not exist yet, which is an error. So, just hold onto the paths until // all files are extracted, and /then/ try to do the links Map<Path, Path> windowsSymlinkMap = new HashMap<>(); try (TarArchiveInputStream archiveStream = getArchiveInputStream(archiveFile)) { TarArchiveEntry entry;//from w w w . j a va 2 s . com while ((entry = archiveStream.getNextTarEntry()) != null) { String entryName = entry.getName(); if (entriesToExclude.matchesAny(entryName)) { continue; } Path destFile = Paths.get(entryName); Path destPath; if (stripPath.isPresent()) { if (!destFile.startsWith(stripPath.get())) { continue; } destPath = filesystemRelativePath.resolve(stripPath.get().relativize(destFile)).normalize(); } else { destPath = filesystemRelativePath.resolve(destFile).normalize(); } if (entry.isDirectory()) { dirsToTidy.add(destPath); mkdirs(creator, destPath); dirCreationTimes.put(destPath, entry.getModTime().getTime()); } else if (entry.isSymbolicLink()) { if (writeSymlinksAfterCreatingFiles) { recordSymbolicLinkForWindows(creator, destPath, entry, windowsSymlinkMap); } else { writeSymbolicLink(creator, destPath, entry); } paths.add(destPath); setAttributes(filesystem, destPath, entry); } else if (entry.isFile()) { writeFile(creator, archiveStream, destPath); paths.add(destPath); setAttributes(filesystem, destPath, entry); } } writeWindowsSymlinks(creator, windowsSymlinkMap); } catch (CompressorException e) { throw new IOException(String.format("Could not get decompressor for archive at %s", archiveFile), e); } setDirectoryModificationTimes(filesystem, dirCreationTimes); ImmutableSet<Path> filePaths = paths.build(); if (existingFileMode == ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES) { // Clean out directories of files that were not in the archive tidyDirectories(filesystem, dirsToTidy, filePaths); } return filePaths; }
From source file:fr.gael.dhus.olingo.v1.entity.Product.java
@Override public Map<String, Object> toEntityResponse(String root_url) { // superclass node response is not required. Only Item response is // necessary. Map<String, Object> res = super.itemToEntityResponse(root_url); res.put(NodeEntitySet.CHILDREN_NUMBER, getChildrenNumber()); LinkedHashMap<String, Date> dates = new LinkedHashMap<String, Date>(); dates.put(V1Model.TIME_RANGE_START, getContentStart()); dates.put(V1Model.TIME_RANGE_END, getContentEnd()); res.put(ProductEntitySet.CONTENT_DATE, dates); HashMap<String, String> checksum = new LinkedHashMap<String, String>(); checksum.put(V1Model.ALGORITHM, getChecksumAlgorithm()); checksum.put(V1Model.VALUE, getChecksumValue()); res.put(ProductEntitySet.CHECKSUM, checksum); res.put(ProductEntitySet.INGESTION_DATE, getIngestionDate()); res.put(ProductEntitySet.CREATION_DATE, getCreationDate()); res.put(ProductEntitySet.EVICTION_DATE, getEvictionDate()); res.put(ProductEntitySet.CONTENT_GEOMETRY, getGeometry()); Path incoming_path = Paths.get(CONFIG_MGR.getArchiveConfiguration().getIncomingConfiguration().getPath()); String prod_path = this.getDownloadablePath(); if (prod_path != null) // Can happen with not yet ingested products {//from www. jav a 2 s . c o m Path prod_path_path = Paths.get(prod_path); if (prod_path_path.startsWith(incoming_path)) { prod_path = incoming_path.relativize(prod_path_path).toString(); } else { prod_path = null; } } else { prod_path = null; } res.put(ProductEntitySet.LOCAL_PATH, prod_path); try { String url = root_url + V1Model.PRODUCT.getName() + "('" + getId() + "')/$value"; MetalinkBuilder mb = new MetalinkBuilder(); mb.addFile(getName() + ".zip").addUrl(url, null, 0); StringWriter sw = new StringWriter(); Document doc = mb.build(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(new DOMSource(doc), new StreamResult(sw)); res.put(ProductEntitySet.METALINK, sw.toString()); } catch (ParserConfigurationException e) { LOGGER.error("Error when creating Product EntityResponse", e); } catch (TransformerException e) { LOGGER.error("Error when creating Product EntityResponse", e); } return res; }
From source file:org.darkware.wpman.security.ChecksumDatabase.java
/** * Normalize the given {@code Path} so that internal {@code Path} operations don't have to think about * absolute/relative comparisons or paths that don't represent concrete files. * * @param file The {@code Path} to normalize. * @return An absolute {@code Path} to a concrete file which is a descendant of the database root. * @throws IllegalArgumentException If the path does not exist, was not a path to a regular file, or pointed * to a file that was outside the database root. *//*from w ww .ja va2 s. c o m*/ protected Path normalize(final Path file) { Path normalized = file; if (normalized.isAbsolute()) { if (!file.startsWith(this.root)) throw new IllegalArgumentException("The given file is outside the database root path."); } else { normalized = this.root.resolve(normalized); } if (Files.notExists(normalized)) throw new IllegalArgumentException("The given file does not exist."); if (!Files.isRegularFile(normalized)) throw new IllegalArgumentException("The given path is not a file."); return normalized; }