List of usage examples for java.nio.file Files isSymbolicLink
public static boolean isSymbolicLink(Path path)
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);/*from www. ja v a 2s . com*/ 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.codice.ddf.migration.util.MigratableUtilTest.java
@Test public void copyDirectorySourceHasSymbolicLink() throws IOException { when(Files.isSymbolicLink(VALID_SOURCE_PATH)).thenReturn(true); MigratableUtil migratableUtil = new MigratableUtil(); migratableUtil.copyDirectory(VALID_SOURCE_PATH, VALID_DESTINATION_PATH, warnings); assertWarnings("contains a symbolic link"); }
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;// ww w .ja v a 2 s . com 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);/* www. j av a 2s. c om*/ 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:org.codice.ddf.configuration.migration.ImportMigrationEntryImpl.java
@VisibleForTesting boolean isMigratable() { final MigrationReport report = getContext().getReport(); if (path.isAbsolute()) { report.record(new MigrationWarning(Messages.IMPORT_OPTIONAL_PATH_DELETE_WARNING, path, String.format("is outside [%s]", getContext().getPathUtils().getDDFHome()))); return false; } else if (AccessUtils.doPrivileged(() -> Files.isSymbolicLink(getAbsolutePath()))) { report.record(//from w w w . jav a 2 s . c om new MigrationWarning(Messages.IMPORT_OPTIONAL_PATH_DELETE_WARNING, path, "is a symbolic link")); return false; } return true; }
From source file:com.spectralogic.ds3cli.command.PutBulk.java
private Iterable<Path> getFilesToPut() throws IOException { final Iterable<Path> filesToPut; if (this.pipe) { filesToPut = this.pipedFiles; } else {//from w ww . j ava 2 s . co m filesToPut = FileUtils.listObjectsForDirectory(this.inputDirectory); } return new FilteringIterable<>(filesToPut, new FilteringIterable.FilterFunction<Path>() { @Override public boolean filter(final Path item) { final boolean filter = !(followSymlinks || !Files.isSymbolicLink(item)); if (filter) { LOG.info("Skipping: {}", item.toString()); } return filter; } }); }
From source file:org.flowerplatform.web.git.GitUtils.java
/** * Deletes the given file and its content. * <p>//from w ww .java 2s. c o m * If the file is a symbolic link, deletes only the file. * Otherwise, deletes also the content from the original location * (file.listFiles() returns the children files from original location). */ public void delete(File f) { if (f.isDirectory() && !Files.isSymbolicLink(Paths.get(f.toURI()))) { for (File c : f.listFiles()) { delete(c); } } f.delete(); }
From source file:com.heliosapm.script.AbstractDeployedScript.java
/** * Creates a new AbstractDeployedScript/*from www . ja v a 2 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")); }
From source file:edu.kit.dama.staging.util.DataOrganizationUtils.java
/** * Creates a DataOrganizationNode from a local path. This method will take * pLocalFile, removed pLocalBasePath from the file's path and creates a new * DataOrganizationNode consisting of pNewBaseURL and the relative path of * pLocalFile. Directories are included by iterative calls until the end of * the directory structure was reached.//from w w w.j a va 2 s . c om * * @param pDigitalObjectId The digital object ID used for the root node * @param pAbstractFile The file/directory forming the DataOrganizationNode * @param pBaseUrl The base URL which will be removed from all LFNs in order * to get its relative path. * @param pNewBaseUrl The base URL to which the relative path of pFile is * appended to form a DataOrganizationNode. It is expected that this URL is * a directory. * @param pIncludeAttributes If TRUE obtainable file attributes (e.g. * filesize, directory/file flag, lastModified) are included into the tree. * * @return An IDataOrganizationNode object representing the entire file * structure below pLocalFile. * * @throws AdalapiException If the access to pFile fails. * @throws MalformedURLException If pBaseUrl is invalid. */ private static IDataOrganizationNode createNodeFromFile(String pDigitalObjectId, AbstractFile pAbstractFile, String pBaseUrl, URL pNewBaseUrl, boolean pIncludeAttributes) throws AdalapiException, MalformedURLException { String sBaseUrl = pNewBaseUrl.toString(); if (!sBaseUrl.endsWith("/")) {//add slash to base URL as this should be a directory sBaseUrl += "/"; } LOGGER.debug("Creating node from file {} with baseUrl {} for new baseUrl {}", pAbstractFile, pBaseUrl, pNewBaseUrl); DataOrganizationNodeImpl ret; String fromPath = FilenameUtils.normalize(pAbstractFile.getUrl().getPath(), true); if (pAbstractFile.isDirectory()) {//local file is a directory, proceed accordingly in a recursive way CollectionNodeImpl cn = new CollectionNodeImpl(new LFNImpl(sBaseUrl)); if (fromPath.equals(pBaseUrl)) {//we have the root path, so use the digital object ID as node identifier cn.setName(pDigitalObjectId); } else {//we have another path, so use the directory name as node identifier cn.setName(pAbstractFile.getName()); } //list all files and add them to the current node Collection<AbstractFile> ls = pAbstractFile.list(); long dirSize = 0; if (ls != null) { for (AbstractFile child : ls) {//add all children recursively if (child.isLocal()) {//perform symlink check try { if (Files.isSymbolicLink(Paths.get(pAbstractFile.getUrl().toURI()))) { LOGGER.warn("Symbolic link detected in child in local file at {}. Ignoring it.", child); //do nothing with this child } else { //no symlink, add child IDataOrganizationNode childNode = createNodeFromFile(pDigitalObjectId, child, pBaseUrl, pNewBaseUrl, pIncludeAttributes); cn.addChild(childNode); for (IAttribute attribute : childNode.getAttributes()) { if (attribute.getKey().equals(SIZE_KEY)) { dirSize += Long.parseLong(attribute.getValue()); } } } } catch (URISyntaxException ex) { //ignored } } else {//for remote files we cannot perform symlink checks IDataOrganizationNode childNode = createNodeFromFile(pDigitalObjectId, child, pBaseUrl, pNewBaseUrl, pIncludeAttributes); cn.addChild(childNode); for (IAttribute attribute : childNode.getAttributes()) { if (attribute.getKey().equals(SIZE_KEY)) { dirSize += Long.parseLong(attribute.getValue()); } } } } } if (pIncludeAttributes) { cn.addAttribute(new AttributeImpl(DIRECTORY_KEY, Boolean.TRUE.toString())); cn.addAttribute(new AttributeImpl(LAST_MODIFIED_KEY, Long.toString(pAbstractFile.lastModified()))); cn.addAttribute(new AttributeImpl(SIZE_KEY, Long.toString(dirSize))); cn.addAttribute(new AttributeImpl(CHILDREN_KEY, Integer.toString(pAbstractFile.list().size()))); } ret = cn; } else {//current file is no directory, just append it as filenode ret = new FileNodeImpl(new LFNImpl(pAbstractFile.getUrl())); ret.setName(pAbstractFile.getName()); if (pIncludeAttributes) { ret.addAttribute(new AttributeImpl(DIRECTORY_KEY, Boolean.FALSE.toString())); ret.addAttribute(new AttributeImpl(LAST_MODIFIED_KEY, Long.toString(pAbstractFile.lastModified()))); ret.addAttribute(new AttributeImpl(SIZE_KEY, Long.toString(pAbstractFile.getSize()))); } } return ret; }
From source file:desktopsearch.ExploreFiles.java
private void RecursivelyExplore(File Directory) { String[] List = Directory.list(); String AbsPath = Directory.getAbsolutePath() + "/"; String SQLQuery = null;//from www . j ava 2 s.c om ArrayList<String> DirList = new ArrayList(); String FormattedPath = Directory.getPath(); if (FormattedPath.contains("'")) { FormattedPath = FormattedPath.replace("'", "''"); } try { for (int i = 0; i < List.length; i++) { File path = new File(AbsPath + List[i]); Path Location = Paths.get(path.getAbsolutePath()); FileTime LastModifiedTime = Files.getLastModifiedTime(Location); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(LastModifiedTime.toMillis()); try { if (path.isFile()) { String Type = FilenameUtils.getExtension(Directory.getPath() + "/" + List[i]); if (Type.endsWith("~") || Type.equals("")) { Type = "Text"; } if (List[i].contains("'")) { List[i] = List[i].replace("'", "''"); System.out.println(List[i]); } SQLQuery = "INSERT INTO FileInfo VALUES('" + Directory.getPath() + "','" + List[i] + "','" + Type + "','" + calendar.getTime() + "'," + (path.length() / 1024) + ");"; } else { if (List[i].contains("'")) { List[i] = List[i].replace("'", "''"); System.out.println(List[i]); } if (!Files.isSymbolicLink(Location)) { long size = FileUtils.sizeOfDirectory(path); SQLQuery = "INSERT INTO FileInfo VALUES('" + Directory.getPath() + "','" + List[i] + "','FOLDER','" + calendar.getTime() + "'," + size + ");"; } else { SQLQuery = "INSERT INTO FileInfo VALUES('" + Directory.getPath() + "','" + List[i] + "','LINK','" + calendar.getTime() + "',0);"; } DirList.add(List[i]); } output.println(SQLQuery); } catch (Exception exp) { exp.printStackTrace(); } ; } for (int i = 0; i < DirList.size(); i++) { File subDir = new File(AbsPath + DirList.get(i)); Path path = Paths.get(AbsPath + DirList.get(i)); if (subDir.canRead() && !Files.isSymbolicLink(path)) { RecursivelyExplore(subDir); } } } catch (Exception e) { e.printStackTrace(); } }