List of usage examples for java.nio.file Path relativize
Path relativize(Path other);
From source file:org.apache.beam.runners.apex.ApexYarnLauncher.java
/** * Create a jar file from the given directory. * @param dir source directory/*from w w w. j a v a2s . com*/ * @param jarFile jar file name * @throws IOException when file cannot be created */ public static void createJar(File dir, File jarFile) throws IOException { final Map<String, ?> env = Collections.singletonMap("create", "true"); if (jarFile.exists() && !jarFile.delete()) { throw new RuntimeException("Failed to remove " + jarFile); } URI uri = URI.create("jar:" + jarFile.toURI()); try (final FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { File manifestFile = new File(dir, JarFile.MANIFEST_NAME); Files.createDirectory(zipfs.getPath("META-INF")); try (final OutputStream out = Files.newOutputStream(zipfs.getPath(JarFile.MANIFEST_NAME))) { if (!manifestFile.exists()) { new Manifest().write(out); } else { FileUtils.copyFile(manifestFile, out); } } final java.nio.file.Path root = dir.toPath(); Files.walkFileTree(root, new java.nio.file.SimpleFileVisitor<Path>() { String relativePath; @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { relativePath = root.relativize(dir).toString(); if (!relativePath.isEmpty()) { if (!relativePath.endsWith("/")) { relativePath += "/"; } if (!relativePath.equals("META-INF/")) { final Path dstDir = zipfs.getPath(relativePath); Files.createDirectory(dstDir); } } return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String name = relativePath + file.getFileName(); if (!JarFile.MANIFEST_NAME.equals(name)) { try (final OutputStream out = Files.newOutputStream(zipfs.getPath(name))) { FileUtils.copyFile(file.toFile(), out); } } return super.visitFile(file, attrs); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { relativePath = root.relativize(dir.getParent()).toString(); if (!relativePath.isEmpty() && !relativePath.endsWith("/")) { relativePath += "/"; } return super.postVisitDirectory(dir, exc); } }); } }
From source file:com.amazonaws.codepipeline.jenkinsplugin.CompressionTools.java
private static void compressArchive(final Path pathToCompress, final ArchiveOutputStream archiveOutputStream, final ArchiveEntryFactory archiveEntryFactory, final CompressionType compressionType, final BuildListener listener) throws IOException { final List<File> files = addFilesToCompress(pathToCompress, listener); LoggingHelper.log(listener, "Compressing directory '%s' as a '%s' archive", pathToCompress.toString(), compressionType.name());/*from w w w. j a v a 2s. c o m*/ for (final File file : files) { final String newTarFileName = pathToCompress.relativize(file.toPath()).toString(); final ArchiveEntry archiveEntry = archiveEntryFactory.create(file, newTarFileName); archiveOutputStream.putArchiveEntry(archiveEntry); try (final FileInputStream fileInputStream = new FileInputStream(file)) { IOUtils.copy(fileInputStream, archiveOutputStream); } archiveOutputStream.closeArchiveEntry(); } }
From source file:org.sonarsource.commandlinezip.ZipUtils7.java
public static void fastZip(final Path srcDir, Path zip) throws IOException { try (final OutputStream out = FileUtils.openOutputStream(zip.toFile()); final ZipOutputStream zout = new ZipOutputStream(out)) { zout.setMethod(ZipOutputStream.STORED); Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() { @Override// ww w . j a v a 2 s . c om public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) { String entryName = srcDir.relativize(file).toString(); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); IOUtils.copy(in, zout); zout.closeEntry(); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dir.equals(srcDir)) { return FileVisitResult.CONTINUE; } String entryName = srcDir.relativize(dir).toString(); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); zout.closeEntry(); return FileVisitResult.CONTINUE; } }); } }
From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java
private static void addAllToZippedArchive(Map<Path, String> starts, Path zipFilePath) throws IOException { try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(zipFilePath.toFile())) { for (Path start : starts.keySet()) { final String rootEntryName = starts.get(start); Files.walkFileTree(start, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Skip pyc files. if (file.getFileName().toString().endsWith(".pyc")) return FileVisitResult.CONTINUE; String entryName = rootEntryName; String relativePath = start.relativize(file).toString(); // If empty, file is the start file. if (!relativePath.isEmpty()) { entryName = entryName + "/" + relativePath; }/* w w w. j av a2 s . com*/ // Zip uses forward slashes entryName = entryName.replace(File.separatorChar, '/'); ZipArchiveEntry entry = new ZipArchiveEntry(file.toFile(), entryName); if (Files.isExecutable(file)) entry.setUnixMode(0100770); else entry.setUnixMode(0100660); zos.putArchiveEntry(entry); Files.copy(file, zos); zos.closeArchiveEntry(); return FileVisitResult.CONTINUE; } public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { final String dirName = dir.getFileName().toString(); // Don't include pyc files or .toolkit if (dirName.equals("__pycache__")) return FileVisitResult.SKIP_SUBTREE; ZipArchiveEntry dirEntry = new ZipArchiveEntry(dir.toFile(), rootEntryName + "/" + start.relativize(dir).toString().replace(File.separatorChar, '/') + "/"); zos.putArchiveEntry(dirEntry); zos.closeArchiveEntry(); return FileVisitResult.CONTINUE; } }); } } }
From source file:org.omegat.util.FileUtil.java
public static List<String> buildRelativeFilesList(File rootDir, List<String> includes, List<String> excludes) throws IOException { Path root = rootDir.toPath(); Pattern[] includeMasks = FileUtil.compileFileMasks(includes); Pattern[] excludeMasks = FileUtil.compileFileMasks(excludes); BiPredicate<Path, BasicFileAttributes> pred = (p, attr) -> { return p.toFile().isFile() && FileUtil.checkFileInclude(root.relativize(p).toString(), includeMasks, excludeMasks); };/*from w w w . j a v a 2s. co m*/ try (Stream<Path> stream = Files.find(root, Integer.MAX_VALUE, pred, FileVisitOption.FOLLOW_LINKS)) { return stream.map(p -> root.relativize(p).toString().replace('\\', '/')) .sorted(StreamUtil.localeComparator(Function.identity())).collect(Collectors.toList()); } }
From source file:com.facebook.buck.util.unarchive.Unzip.java
/** * Get a listing of all files in a zip file that start with a prefix, ignore others * * @param zip The zip file to scan/*from w ww. ja va 2s. co m*/ * @param relativePath The relative path where the extraction will be rooted * @param prefix The prefix that will be stripped off. * @return The list of paths in {@code zip} sorted by path so dirs come before contents. Prefixes * are stripped from paths in the zip file, such that foo/bar/baz.txt with a prefix of foo/ * will be in the map at {@code relativePath}/bar/baz.txt */ private static SortedMap<Path, ZipArchiveEntry> getZipFilePathsStrippingPrefix(ZipFile zip, Path relativePath, Path prefix, PatternsMatcher entriesToExclude) { SortedMap<Path, ZipArchiveEntry> pathMap = new TreeMap<>(); for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) { String entryName = entry.getName(); if (entriesToExclude.matchesAny(entryName)) { continue; } Path entryPath = Paths.get(entryName); if (entryPath.startsWith(prefix)) { Path target = relativePath.resolve(prefix.relativize(entryPath)).normalize(); pathMap.put(target, entry); } } return pathMap; }
From source file:com.ejisto.util.IOUtils.java
public static Collection<String> findAllClassesInJarFile(File jarFile) throws IOException { final List<String> ret = new ArrayList<>(); Map<String, String> env = new HashMap<>(); env.put("create", "false"); try (FileSystem targetFs = FileSystems.newFileSystem(URI.create("jar:file:" + jarFile.getAbsolutePath()), env)) {/*from www. j av a 2 s . c om*/ final Path root = targetFs.getPath("/"); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String ext = ".class"; if (attrs.isRegularFile() && file.getFileName().toString().endsWith(ext)) { String path = root.relativize(file).toString(); ret.add(translatePath(path.substring(0, path.length() - ext.length()), "/")); } return FileVisitResult.CONTINUE; } }); } return ret; }
From source file:org.roda.core.plugins.plugins.characterization.SiegfriedPluginUtils.java
private static <T extends IsRODAObject> List<LinkingIdentifier> runSiegfriedOnRepresentationOrFile( Plugin<T> plugin, ModelService model, String aipId, String representationId, List<String> fileDirectoryPath, String fileId, Path path) throws RequestNotValidException, GenericException, NotFoundException, AuthorizationDeniedException, PluginException { List<LinkingIdentifier> sources = new ArrayList<>(); if (FSUtils.exists(path)) { String siegfriedOutput = SiegfriedPluginUtils.runSiegfriedOnPath(path); final JsonNode jsonObject = JsonUtils.parseJson(siegfriedOutput); final JsonNode files = jsonObject.get("files"); for (JsonNode file : files) { Path fullFsPath = Paths.get(file.get("filename").asText()); Path relativeFsPath = path.relativize(fullFsPath); String jsonFileId = fullFsPath.getFileName().toString(); List<String> jsonFilePath = new ArrayList<>(fileDirectoryPath); if (fileId != null) { jsonFilePath.add(fileId); }// w w w. j a va 2s . c om for (int j = 0; j < relativeFsPath.getNameCount() && StringUtils.isNotBlank(relativeFsPath.getName(j).toString()); j++) { jsonFilePath.add(relativeFsPath.getName(j).toString()); } jsonFilePath.remove(jsonFilePath.size() - 1); ContentPayload payload = new StringContentPayload(file.toString()); model.createOrUpdateOtherMetadata(aipId, representationId, jsonFilePath, jsonFileId, SiegfriedPlugin.FILE_SUFFIX, RodaConstants.OTHER_METADATA_TYPE_SIEGFRIED, payload, false); sources.add(PluginHelper.getLinkingIdentifier(aipId, representationId, jsonFilePath, jsonFileId, RodaConstants.PRESERVATION_LINKING_OBJECT_SOURCE)); // Update PREMIS files final JsonNode matches = file.get("matches"); for (JsonNode match : matches) { String format = null; String version = null; String pronom = null; String mime = null; String[] pluginVersion = plugin.getVersion().split("\\."); if ("1".equals(pluginVersion[0])) { if (Integer.parseInt(pluginVersion[1]) > 4) { if ("pronom".equalsIgnoreCase(match.get("ns").textValue())) { format = match.get("format").textValue(); version = match.get("version").textValue(); pronom = match.get("id").textValue(); mime = match.get("mime").textValue(); } } else { if ("pronom".equalsIgnoreCase(match.get("id").textValue())) { format = match.get("format").textValue(); version = match.get("version").textValue(); pronom = match.get("puid").textValue(); mime = match.get("mime").textValue(); } } } PremisV3Utils.updateFormatPreservationMetadata(model, aipId, representationId, jsonFilePath, jsonFileId, format, version, pronom, mime, true); } } } return sources; }
From source file:org.roda.core.storage.fs.FSUtils.java
public static Path getBinaryHistoryMetadataPath(Path historyDataPath, Path historyMetadataPath, Path path) { Path relativePath = historyDataPath.relativize(path); String fileName = relativePath.getFileName().toString(); return historyMetadataPath.resolve(relativePath.getParent().resolve(fileName + METADATA_SUFFIX)); }
From source file:org.roda.core.storage.fs.FSUtils.java
public static StoragePath getStoragePath(Path basePath, Path absolutePath) throws RequestNotValidException { return getStoragePath(basePath.relativize(absolutePath)); }