Search in sources :

Example 96 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project randomizedtesting by randomizedtesting.

the class JUnit4 method getWorkingDirectory.

private Path getWorkingDirectory(ForkedJvmInfo jvmInfo) throws IOException {
    Path baseDir = (dir == null ? getProject().getBaseDir().toPath() : dir);
    final Path forkedDir;
    if (isolateWorkingDirectories) {
        forkedDir = baseDir.resolve("J" + jvmInfo.id);
        if (Files.isDirectory(forkedDir)) {
            // If there are any files inside the forkedDir, issue a warning.
            List<String> existingFiles = listFiles(forkedDir);
            if (!existingFiles.isEmpty()) {
                switch(nonEmptyWorkDirAction) {
                    case IGNORE:
                        log("Cwd of a forked JVM already exists and is not empty: " + existingFiles + " (ignoring).", Project.MSG_DEBUG);
                        break;
                    case WIPE:
                        log("Cwd of a forked JVM already exists and is not empty, trying to wipe: " + existingFiles, Project.MSG_DEBUG);
                        try {
                            Files.walkFileTree(forkedDir, new SimpleFileVisitor<Path>() {

                                @Override
                                public FileVisitResult postVisitDirectory(Path dir, IOException iterationError) throws IOException {
                                    if (iterationError != null) {
                                        throw iterationError;
                                    }
                                    if (forkedDir != dir) {
                                        Files.delete(dir);
                                    }
                                    return FileVisitResult.CONTINUE;
                                }

                                @Override
                                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                                    Files.delete(file);
                                    return FileVisitResult.CONTINUE;
                                }

                                @Override
                                public FileVisitResult visitFileFailed(Path file, IOException e) throws IOException {
                                    throw e;
                                }
                            });
                        } catch (IOException e) {
                            throw new BuildException("An exception occurred while trying to wipe the working directory: " + forkedDir, e);
                        }
                        existingFiles = listFiles(forkedDir);
                        if (existingFiles.isEmpty()) {
                            break;
                        } else {
                        // Intentional fall-through.
                        }
                    case FAIL:
                        throw new BuildException("Cwd of a forked JVM already exists and is not empty " + "and setOnNonEmptyWorkDirectory=" + nonEmptyWorkDirAction + ": " + existingFiles);
                    default:
                        throw new RuntimeException("Unreachable.");
                }
            }
        } else {
            Files.createDirectories(forkedDir);
            temporaryFiles.add(forkedDir);
        }
    } else {
        forkedDir = baseDir;
    }
    return forkedDir;
}
Also used : Path(java.nio.file.Path) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 97 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project neo4j by neo4j.

the class FileVisitorsDecoratorsTest method shouldDelegateVisitFile.

@Test
public void shouldDelegateVisitFile() throws IOException {
    Path dir = Paths.get("some-dir");
    BasicFileAttributes attrs = mock(BasicFileAttributes.class);
    decorator.visitFile(dir, attrs);
    verify(wrapped).visitFile(dir, attrs);
}
Also used : Path(java.nio.file.Path) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Test(org.junit.Test)

Example 98 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project wire by square.

the class SchemaLoader method loadFromDirectories.

private Schema loadFromDirectories(Map<Path, Path> directories) throws IOException {
    final Deque<String> protos = new ArrayDeque<>(this.protos);
    if (protos.isEmpty()) {
        for (final Map.Entry<Path, Path> entry : directories.entrySet()) {
            Files.walkFileTree(entry.getValue(), new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (file.getFileName().toString().endsWith(".proto")) {
                        protos.add(entry.getValue().relativize(file).toString());
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }
    Map<String, ProtoFile> loaded = new LinkedHashMap<>();
    loaded.put(DESCRIPTOR_PROTO, loadDescriptorProto());
    while (!protos.isEmpty()) {
        String proto = protos.removeFirst();
        if (loaded.containsKey(proto)) {
            continue;
        }
        ProtoFileElement element = null;
        for (Map.Entry<Path, Path> entry : directories.entrySet()) {
            Source source = source(entry.getValue(), proto);
            if (source == null) {
                continue;
            }
            Path base = entry.getKey();
            try {
                Location location = Location.get(base.toString(), proto);
                String data = Okio.buffer(source).readUtf8();
                element = ProtoParser.parse(location, data);
                break;
            } catch (IOException e) {
                throw new IOException("Failed to load " + proto + " from " + base, e);
            } finally {
                source.close();
            }
        }
        if (element == null) {
            throw new FileNotFoundException("Failed to locate " + proto + " in " + sources);
        }
        ProtoFile protoFile = ProtoFile.get(element);
        loaded.put(proto, protoFile);
        // Queue dependencies to be loaded.
        for (String importPath : element.imports()) {
            protos.addLast(importPath);
        }
    }
    return new Linker(loaded.values()).link();
}
Also used : Path(java.nio.file.Path) FileNotFoundException(java.io.FileNotFoundException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) ProtoFileElement(com.squareup.wire.schema.internal.parser.ProtoFileElement) ArrayDeque(java.util.ArrayDeque) Source(okio.Source) BufferedSource(okio.BufferedSource) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 99 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project syncany by syncany.

the class FileVersionComparator method captureFileProperties.

public FileProperties captureFileProperties(File file, FileChecksum knownChecksum, boolean forceChecksum) {
    FileProperties fileProperties = new FileProperties();
    fileProperties.relativePath = FileUtil.getRelativeDatabasePath(rootFolder, file);
    Path filePath = null;
    try {
        filePath = Paths.get(file.getAbsolutePath());
        fileProperties.exists = Files.exists(filePath, LinkOption.NOFOLLOW_LINKS);
    } catch (InvalidPathException e) {
        // This throws an exception if the filename is invalid,
        // e.g. colon in filename on windows "file:name"
        logger.log(Level.FINE, "InvalidPath", e);
        logger.log(Level.WARNING, "- Path '{0}' is invalid on this file system. It cannot exist. ", file.getAbsolutePath());
        fileProperties.exists = false;
        return fileProperties;
    }
    if (!fileProperties.exists) {
        return fileProperties;
    }
    try {
        // Read operating system dependent file attributes
        BasicFileAttributes fileAttributes = null;
        if (EnvironmentUtil.isWindows()) {
            DosFileAttributes dosAttrs = Files.readAttributes(filePath, DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
            fileProperties.dosAttributes = FileUtil.dosAttrsToString(dosAttrs);
            fileAttributes = dosAttrs;
        } else if (EnvironmentUtil.isUnixLikeOperatingSystem()) {
            PosixFileAttributes posixAttrs = Files.readAttributes(filePath, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
            fileProperties.posixPermissions = PosixFilePermissions.toString(posixAttrs.permissions());
            fileAttributes = posixAttrs;
        } else {
            fileAttributes = Files.readAttributes(filePath, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
        }
        fileProperties.lastModified = fileAttributes.lastModifiedTime().toMillis();
        fileProperties.size = fileAttributes.size();
        // Type
        if (fileAttributes.isSymbolicLink()) {
            fileProperties.type = FileType.SYMLINK;
            fileProperties.linkTarget = FileUtil.readSymlinkTarget(file);
        } else if (fileAttributes.isDirectory()) {
            fileProperties.type = FileType.FOLDER;
            fileProperties.linkTarget = null;
        } else {
            fileProperties.type = FileType.FILE;
            fileProperties.linkTarget = null;
        }
        // Checksum
        if (knownChecksum != null) {
            fileProperties.checksum = knownChecksum;
        } else {
            if (fileProperties.type == FileType.FILE && forceChecksum) {
                try {
                    if (fileProperties.size > 0) {
                        fileProperties.checksum = new FileChecksum(FileUtil.createChecksum(file, checksumAlgorithm));
                    } else {
                        fileProperties.checksum = null;
                    }
                } catch (NoSuchAlgorithmException | IOException e) {
                    logger.log(Level.FINE, "Failed create checksum", e);
                    logger.log(Level.SEVERE, "SEVERE: Unable to create checksum for file {0}", file);
                    fileProperties.checksum = null;
                }
            } else {
                fileProperties.checksum = null;
            }
        }
        // Must be last (!), used for vanish-test later
        fileProperties.exists = Files.exists(filePath, LinkOption.NOFOLLOW_LINKS);
        fileProperties.locked = fileProperties.exists && FileUtil.isFileLocked(file);
        return fileProperties;
    } catch (IOException e) {
        logger.log(Level.FINE, "Failed to read file", e);
        logger.log(Level.SEVERE, "SEVERE: Cannot read file {0}. Assuming file is locked.", file);
        fileProperties.exists = true;
        fileProperties.locked = true;
        return fileProperties;
    }
}
Also used : Path(java.nio.file.Path) DosFileAttributes(java.nio.file.attribute.DosFileAttributes) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) PosixFileAttributes(java.nio.file.attribute.PosixFileAttributes) InvalidPathException(java.nio.file.InvalidPathException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) FileChecksum(org.syncany.database.FileContent.FileChecksum)

Example 100 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project zaproxy by zaproxy.

the class VulnerabilitiesLoader method getListOfVulnerabilitiesFiles.

/**
	 * Returns a {@code List} of resources files with {@code fileName} and {@code fileExtension} contained in the
	 * {@code directory}.
	 *
	 * @return the list of resources files contained in the {@code directory}
	 * @see LocaleUtils#createResourceFilesPattern(String, String)
	 */
private List<String> getListOfVulnerabilitiesFiles() {
    final Pattern filePattern = LocaleUtils.createResourceFilesPattern(fileName, fileExtension);
    final List<String> fileNames = new ArrayList<>();
    try {
        Files.walkFileTree(directory, Collections.<FileVisitOption>emptySet(), 1, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String fileName = file.getFileName().toString();
                if (filePattern.matcher(fileName).matches()) {
                    fileNames.add(fileName);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        logger.error("An error occurred while walking directory: " + directory, e);
    }
    return fileNames;
}
Also used : Path(java.nio.file.Path) Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)119 Path (java.nio.file.Path)93 IOException (java.io.IOException)87 FileVisitResult (java.nio.file.FileVisitResult)66 File (java.io.File)18 Test (org.junit.Test)13 SimpleFileVisitor (java.nio.file.SimpleFileVisitor)11 ArrayList (java.util.ArrayList)11 HashSet (java.util.HashSet)8 FileNotFoundException (java.io.FileNotFoundException)7 InputStream (java.io.InputStream)6 HashMap (java.util.HashMap)6 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)5 BasicFileAttributeView (java.nio.file.attribute.BasicFileAttributeView)5 SourcePath (com.facebook.buck.rules.SourcePath)4 ImmutableList (com.google.common.collect.ImmutableList)4 OutputStream (java.io.OutputStream)4 URI (java.net.URI)4 FileSystem (java.nio.file.FileSystem)4 FileVisitor (java.nio.file.FileVisitor)4