List of usage examples for java.nio.file Files readSymbolicLink
public static Path readSymbolicLink(Path link) throws IOException
From source file:com.spotify.scio.util.RemoteFileUtil.java
private Path downloadImpl(URI src) { try {/*from w ww. j av a 2 s.c o m*/ Path dst = getDestination(src); if (src.getScheme() == null || src.getScheme().equals("file")) { // Local URI Path srcPath = src.getScheme() == null ? Paths.get(src.toString()) : Paths.get(src); if (Files.isSymbolicLink(dst) && Files.readSymbolicLink(dst).equals(srcPath)) { LOG.info("URI {} already symlink-ed", src); } else { Files.createSymbolicLink(dst, srcPath); LOG.info("Symlink-ed {} to {}", src, dst); } } else { // Remote URI long srcSize = getRemoteSize(src); boolean shouldDownload = true; if (Files.exists(dst)) { long dstSize = Files.size(dst); if (srcSize == dstSize) { LOG.info("URI {} already downloaded", src); shouldDownload = false; } else { LOG.warn("Destination exists with wrong size. {} [{}B] -> {} [{}B]", src, srcSize, dst, dstSize); Files.delete(dst); } } if (shouldDownload) { copyToLocal(src, dst); LOG.info("Downloaded {} -> {} [{}B]", src, dst, srcSize); } } return dst; } catch (IOException e) { throw new UncheckedIOException(e); } }
From source file:com.facebook.buck.util.unarchive.UntarTest.java
/** * Assert that a symlink exists inside of the temp directory with given contents and that links to * the right file//from w w w .ja v a 2 s. c om */ private void assertOutputSymlinkExists(Path symlinkPath, Path expectedLinkedToPath, String expectedContents) throws IOException { Path fullPath = tmpFolder.getRoot().resolve(symlinkPath); if (Platform.detect() != Platform.WINDOWS) { Assert.assertTrue(String.format("Expected %s to be a symlink", fullPath), Files.isSymbolicLink(fullPath)); Path linkedToPath = Files.readSymbolicLink(fullPath); Assert.assertEquals(String.format("Expected symlink at %s to point to %s, not %s", symlinkPath, expectedLinkedToPath, linkedToPath), expectedLinkedToPath, linkedToPath); } Path realExpectedLinkedToPath = filesystem.getRootPath() .resolve(symlinkPath.getParent().resolve(expectedLinkedToPath).normalize()); Assert.assertTrue( String.format("Expected link %s to be the same file as %s", fullPath, realExpectedLinkedToPath), Files.isSameFile(fullPath, realExpectedLinkedToPath)); String contents = Joiner.on('\n').join(Files.readAllLines(fullPath)); Assert.assertEquals(expectedContents, contents); }
From source file:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testExtractSymlink() throws InterruptedException, IOException { assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS))); // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("link.txt"); entry.setUnixMode((int) MostFiles.S_IFLNK); String target = "target.txt"; entry.setSize(target.getBytes(Charsets.UTF_8).length); entry.setMethod(ZipEntry.STORED); zip.putArchiveEntry(entry);// w w w. ja v a 2 s .co m zip.write(target.getBytes(Charsets.UTF_8)); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE); Path link = extractFolder.toAbsolutePath().resolve("link.txt"); assertTrue(Files.isSymbolicLink(link)); assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt")); }
From source file:uk.co.unclealex.executable.impl.MakeLinksCommandRunnerTest.java
protected void checkDirectoriesEqual(Path expectedDir, Path actualDir) throws IOException { Assert.assertTrue("Path " + expectedDir + "is not a directory.", Files.isDirectory(expectedDir, LinkOption.NOFOLLOW_LINKS)); Assert.assertTrue("Path " + actualDir + "is not a directory.", Files.isDirectory(actualDir, LinkOption.NOFOLLOW_LINKS)); Assert.assertArrayEquals("Directory " + actualDir + " has the wrong file entries.", filenamesIn(expectedDir), filenamesIn(actualDir)); DirectoryStream<Path> directoryStream = Files.newDirectoryStream(actualDir); for (Path expectedChild : directoryStream) { Path actualChild = expectedDir.resolve(expectedChild.getFileName()); if (Files.isDirectory(expectedChild, LinkOption.NOFOLLOW_LINKS)) { Assert.assertTrue("Path " + actualChild + " is not a directory.", Files.isDirectory(actualChild, LinkOption.NOFOLLOW_LINKS)); checkDirectoriesEqual(expectedChild, actualChild); } else if (Files.isSymbolicLink(expectedChild)) { Assert.assertTrue("Path " + actualChild + " is not a symbolic link", Files.isSymbolicLink(actualChild)); Assert.assertEquals("Symbolic link " + actualChild + " points to the wrong place.", Files.readSymbolicLink(expectedChild), Files.readSymbolicLink(actualChild)); } else {// w w w . j av a2 s .c om Assert.assertTrue("Path " + actualChild + " has the wrong content.", FileUtils.contentEquals(expectedChild.toFile(), actualChild.toFile())); } } }
From source file:org.apache.karaf.tooling.ArchiveMojo.java
private void addFileToTarGz(TarArchiveOutputStream tOut, Path f, String base) throws IOException { if (Files.isDirectory(f)) { String entryName = base + f.getFileName().toString() + "/"; TarArchiveEntry tarEntry = new TarArchiveEntry(entryName); tOut.putArchiveEntry(tarEntry);// www . ja va2 s. c o m tOut.closeArchiveEntry(); try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) { for (Path child : children) { addFileToTarGz(tOut, child, entryName); } } } else if (useSymLinks && Files.isSymbolicLink(f)) { String entryName = base + f.getFileName().toString(); TarArchiveEntry tarEntry = new TarArchiveEntry(entryName, TarConstants.LF_SYMLINK); tarEntry.setLinkName(Files.readSymbolicLink(f).toString()); tOut.putArchiveEntry(tarEntry); tOut.closeArchiveEntry(); } else { String entryName = base + f.getFileName().toString(); TarArchiveEntry tarEntry = new TarArchiveEntry(entryName); tarEntry.setSize(Files.size(f)); if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin/"))) { if (entryName.endsWith(".bat")) { tarEntry.setMode(0644); } else { tarEntry.setMode(0755); } } tOut.putArchiveEntry(tarEntry); Files.copy(f, tOut); tOut.closeArchiveEntry(); } }
From source file:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testExtractBrokenSymlinkWithOwnerExecutePermissions() throws InterruptedException, IOException { assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS))); // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("link.txt"); entry.setUnixMode((int) MostFiles.S_IFLNK); String target = "target.txt"; entry.setSize(target.getBytes(Charsets.UTF_8).length); entry.setMethod(ZipEntry.STORED); // Mark the file as being executable. Set<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE); long externalAttributes = entry.getExternalAttributes() + (MorePosixFilePermissions.toMode(filePermissions) << 16); entry.setExternalAttributes(externalAttributes); zip.putArchiveEntry(entry);/* ww w.j av a 2 s . c om*/ zip.write(target.getBytes(Charsets.UTF_8)); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE); Path link = extractFolder.toAbsolutePath().resolve("link.txt"); assertTrue(Files.isSymbolicLink(link)); assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt")); }
From source file:org.everit.osgi.dev.maven.util.FileManager.java
public boolean copyFile(final File source, final File target, final CopyModeType copyMode) throws MojoExecutionException { boolean fileChange = false; if (CopyModeType.FILE.equals(copyMode)) { if (target.exists() && Files.isSymbolicLink(target.toPath())) { target.delete();//from w w w.j ava2s . co m } fileChange = overCopyFile(source, target); } else { try { if (target.exists()) { Path targetPath = target.toPath(); if (Files.isSymbolicLink(targetPath)) { Path symbolicLinkTarget = Files.readSymbolicLink(targetPath); File symbolicLinkTargetFile = symbolicLinkTarget.toFile(); if (!symbolicLinkTargetFile.equals(source)) { target.delete(); createSymbolicLink(target, source); fileChange = true; } } else { target.delete(); createSymbolicLink(target, source); fileChange = true; } } else { createSymbolicLink(target, source); fileChange = true; } } catch (IOException e) { throw new MojoExecutionException( "Could not check the target of the symbolic link " + target.getAbsolutePath(), e); } } return fileChange; }
From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java
private File copyOrphanFileToWorkspace(File file, Workspace workspace) throws URISyntaxException { File wsOrphansDirectory = new File(workspaceBaseDirectory, workspace.getWorkspaceID() + "/" + orphansDirectoryName); File origOrphansDirectory = archiveFileLocationProvider .getOrphansDirectory(workspace.getTopNodeArchiveURL().toURI()); File destPath = new File(wsOrphansDirectory, origOrphansDirectory.toPath().relativize(file.getParentFile().toPath()).toString()); File destFile = null;/*from ww w .j av a2 s . co m*/ try { //create directories if (destPath.exists()) { logger.info("Workspace directory: [" + destPath.toPath().toString() + "] for orphan: [" + file.getName() + "] already exists"); } else { if (destPath.mkdirs()) { logger.info("Workspace directory: [" + destPath.toPath().toString() + "] for orphan: [" + file.getName() + "] successfully created"); } else { String errorMessage = "Workspace directory: [" + destPath.toPath().toString() + "] for orphan: [" + file.getName() + "] could not be created"; throw new IOException(errorMessage); } } if (Files.isSymbolicLink(file.toPath())) { file = Files.readSymbolicLink(file.toPath()).toFile(); } destFile = new File(destPath, file.getName()); Files.copy(file.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { logger.error("Cannot copy metadata file: [" + file.toPath() + "] to workspace directory: [" + destPath.toString(), e); } return destFile; }
From source file:org.apache.karaf.tooling.ArchiveMojo.java
private void addFileToZip(ZipArchiveOutputStream tOut, Path f, String base) throws IOException { if (Files.isDirectory(f)) { String entryName = base + f.getFileName().toString() + "/"; ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName); tOut.putArchiveEntry(zipEntry);//from ww w. j av a 2s .c o m tOut.closeArchiveEntry(); try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) { for (Path child : children) { addFileToZip(tOut, child, entryName); } } } else if (useSymLinks && Files.isSymbolicLink(f)) { String entryName = base + f.getFileName().toString(); ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName); zipEntry.setUnixMode(UnixStat.LINK_FLAG | UnixStat.DEFAULT_FILE_PERM); tOut.putArchiveEntry(zipEntry); tOut.write(Files.readSymbolicLink(f).toString().getBytes()); tOut.closeArchiveEntry(); } else { String entryName = base + f.getFileName().toString(); ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName); zipEntry.setSize(Files.size(f)); if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin"))) { if (!entryName.endsWith(".bat")) { zipEntry.setUnixMode(0755); } else { zipEntry.setUnixMode(0644); } } tOut.putArchiveEntry(zipEntry); Files.copy(f, tOut); tOut.closeArchiveEntry(); } }
From source file:com.heliosapm.script.AbstractDeployedScript.java
/** * Creates a new AbstractDeployedScript/*www . j a v a2 s. c o m*/ * @param sourceFile The originating source file */ public AbstractDeployedScript(File sourceFile) { super(SharedNotificationExecutor.getInstance(), notificationInfos); this.sourceFile = sourceFile; shortName = URLHelper.getPlainFileName(sourceFile); final Path link = this.sourceFile.toPath(); Path tmpPath = null; if (Files.isSymbolicLink(link)) { try { tmpPath = Files.readSymbolicLink(link); } catch (Exception ex) { tmpPath = null; } } linkedFile = tmpPath == null ? null : tmpPath.toFile().getAbsoluteFile(); String tmp = URLHelper.getFileExtension(sourceFile); if (tmp == null || tmp.trim().isEmpty()) throw new RuntimeException("The source file [" + sourceFile + "] has no extension"); extension = tmp.toLowerCase(); rootDir = ScriptFileWatcher.getInstance().getRootDir(sourceFile.getParentFile().getAbsolutePath()); pathSegments = calcPathSegments(); log = LoggerFactory.getLogger( StringHelper.fastConcatAndDelim("/", pathSegments) + "/" + sourceFile.getName().replace('.', '_')); objectName = buildObjectName(); if (CONFIG_DOMAIN.equals(objectName.getDomain())) { config = null; } else { config = new Configuration(objectName, this); config.registerInternalListener(this); } checksum = URLHelper.adler32(URLHelper.toURL(sourceFile)); lastModified = URLHelper.getLastModified(URLHelper.toURL(sourceFile)); execElapsedTimes = metrics.histogram(MetricRegistry.name("name=" + shortName, "fx=execution")); }