Search in sources :

Example 46 with BasicFileAttributes

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

the class EeLegacySubsystemTestCase method testLegacyConfigurations.

@Test
public void testLegacyConfigurations() throws Exception {
    // Get a list of all the logging_x_x.xml files
    final Pattern pattern = Pattern.compile("(subsystem)_\\d+_\\d+\\.xml");
    // Using the CP as that's the standardSubsystemTest will use to find the config file
    final String cp = WildFlySecurityManager.getPropertyPrivileged("java.class.path", ".");
    final String[] entries = cp.split(Pattern.quote(File.pathSeparator));
    final List<String> configs = new ArrayList<>();
    for (String entry : entries) {
        final Path path = Paths.get(entry);
        if (Files.isDirectory(path)) {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                    final String name = file.getFileName().toString();
                    if (pattern.matcher(name).matches()) {
                        configs.add(name);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }
    // The paths shouldn't be empty
    Assert.assertFalse("No configs were found", configs.isEmpty());
    for (String configId : configs) {
        // Run the standard subsystem test, but don't compare the XML as it should never match
        standardSubsystemTest(configId, false);
    }
}
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) AbstractSubsystemBaseTest(org.jboss.as.subsystem.test.AbstractSubsystemBaseTest) Test(org.junit.Test)

Example 47 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project android by JetBrains.

the class PatchGenerator method generateFullPackage.

/**
   * Read a zip containing a complete sdk package and generate an equivalent patch that includes the complete content of the package.
   */
public static boolean generateFullPackage(@NotNull File srcRoot, @Nullable final File existingRoot, @NotNull File outputJar, @NotNull String oldDescription, @NotNull String description, @NotNull ProgressIndicator progress) {
    Digester digester = new Digester("md5");
    Runner.initLogger();
    progress.logInfo("Generating patch...");
    final Set<String> srcFiles = new HashSet<>();
    try {
        Files.walkFileTree(srcRoot.toPath(), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String relativePath = srcRoot.toPath().relativize(file).toString();
                srcFiles.add(relativePath.replace(srcRoot.separatorChar, '/'));
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        progress.logWarning("Failed to read unzipped files!", e);
        return false;
    }
    final List<String> deleteFiles = new ArrayList<>();
    if (existingRoot != null) {
        try {
            Files.walkFileTree(existingRoot.toPath(), new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String relativePath = existingRoot.toPath().relativize(file).toString();
                    String path = relativePath.replace(srcRoot.separatorChar, '/');
                    if (!srcFiles.contains(path)) {
                        deleteFiles.add(path);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            progress.logWarning("Failed to read existing files!", e);
            return false;
        }
    }
    PatchSpec spec = new PatchSpec().setOldVersionDescription(oldDescription).setNewVersionDescription(description).setRoot("").setBinary(true).setOldFolder(existingRoot == null ? "" : existingRoot.getAbsolutePath()).setNewFolder(srcRoot.getAbsolutePath()).setStrict(true).setCriticalFiles(new ArrayList<>(srcFiles)).setDeleteFiles(deleteFiles).setHashAlgorithm("md5");
    ProgressUI ui = new ProgressUI(progress);
    File patchZip = new File(outputJar.getParent(), "patch-file.zip");
    try {
        Patch patchInfo = new Patch(spec, ui);
        if (!patchZip.getParentFile().exists()) {
            patchZip.getParentFile().mkdirs();
        }
        patchZip.createNewFile();
        PatchFileCreator.create(spec, patchZip, ui);
        // The expected format is for the patch to be inside the package zip.
        try (FileSystem destFs = FileSystems.newFileSystem(URI.create("jar:" + outputJar.toURI()), ImmutableMap.of("create", "true", "useTempFile", true));
            InputStream is = new BufferedInputStream(new FileInputStream(patchZip))) {
            Files.copy(is, destFs.getPath("patch-file.zip"));
        }
    } catch (IOException | OperationCancelledException e) {
        progress.logWarning("Failed to create patch", e);
        return false;
    }
    return true;
}
Also used : FileSystem(java.nio.file.FileSystem) ZipFile(java.util.zip.ZipFile) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 48 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project streamsx.topology by IBMStreams.

the class ZippedToolkitRemoteContext method addAllToZippedArchive.

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;
                    }
                    // 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;
                }
            });
        }
    }
}
Also used : Path(java.nio.file.Path) ZipArchiveOutputStream(org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 49 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project jdk8u_jdk by JetBrains.

the class FileTreeWalker method visit.

/**
     * Visits the given file, returning the {@code Event} corresponding to that
     * visit.
     *
     * The {@code ignoreSecurityException} parameter determines whether
     * any SecurityException should be ignored or not. If a SecurityException
     * is thrown, and is ignored, then this method returns {@code null} to
     * mean that there is no event corresponding to a visit to the file.
     *
     * The {@code canUseCached} parameter determines whether cached attributes
     * for the file can be used or not.
     */
private Event visit(Path entry, boolean ignoreSecurityException, boolean canUseCached) {
    // need the file attributes
    BasicFileAttributes attrs;
    try {
        attrs = getAttributes(entry, canUseCached);
    } catch (IOException ioe) {
        return new Event(EventType.ENTRY, entry, ioe);
    } catch (SecurityException se) {
        if (ignoreSecurityException)
            return null;
        throw se;
    }
    // at maximum depth or file is not a directory
    int depth = stack.size();
    if (depth >= maxDepth || !attrs.isDirectory()) {
        return new Event(EventType.ENTRY, entry, attrs);
    }
    // check for cycles when following links
    if (followLinks && wouldLoop(entry, attrs.fileKey())) {
        return new Event(EventType.ENTRY, entry, new FileSystemLoopException(entry.toString()));
    }
    // file is a directory, attempt to open it
    DirectoryStream<Path> stream = null;
    try {
        stream = Files.newDirectoryStream(entry);
    } catch (IOException ioe) {
        return new Event(EventType.ENTRY, entry, ioe);
    } catch (SecurityException se) {
        if (ignoreSecurityException)
            return null;
        throw se;
    }
    // push a directory node to the stack and return an event
    stack.push(new DirectoryNode(entry, attrs.fileKey(), stream));
    return new Event(EventType.START_DIRECTORY, entry, attrs);
}
Also used : IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 50 with BasicFileAttributes

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

the class FileUtilSupport method copy.

/**
     * Copy a file or directory. It is recommended to use
     * {@link java.nio.file.Files#copy(java.nio.file.Path, java.io.OutputStream)}
     * for files.
     *
     * @param source the file or directory to copy
     * @param dest   must be the file or directory, not the containing directory
     * @throws java.io.IOException if file cannot be copied
     */
public void copy(File source, File dest) throws IOException {
    if (!source.exists()) {
        log.error("Attempting to copy non-existant file: {}", source);
        return;
    }
    if (!dest.exists()) {
        if (source.isDirectory()) {
            boolean ok = dest.mkdirs();
            if (!ok) {
                throw new IOException("Could not use mkdirs to create destination directory");
            }
        } else {
            boolean ok = dest.createNewFile();
            if (!ok) {
                throw new IOException("Could not create destination file");
            }
        }
    }
    Path srcPath = source.toPath();
    Path dstPath = dest.toPath();
    if (source.isDirectory()) {
        Files.walkFileTree(srcPath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
                Files.createDirectories(dstPath.resolve(srcPath.relativize(dir)));
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                Files.copy(file, dstPath.resolve(srcPath.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}
Also used : Path(java.nio.file.Path) 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