Example usage for java.nio.file FileVisitResult TERMINATE

List of usage examples for java.nio.file FileVisitResult TERMINATE

Introduction

In this page you can find the example usage for java.nio.file FileVisitResult TERMINATE.

Prototype

FileVisitResult TERMINATE

To view the source code for java.nio.file FileVisitResult TERMINATE.

Click Source Link

Document

Terminate.

Usage

From source file:Main.java

public static FileVisitor<Path> getFileVisitor() {

    class DeleteDirVisitor extends SimpleFileVisitor<Path> {
        @Override/*from   w  w  w  . java  2  s .c o  m*/
        public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
            FileVisitResult result = FileVisitResult.CONTINUE;
            if (e != null) {
                System.out.format("Error deleting  %s.  %s%n", dir, e.getMessage());
                result = FileVisitResult.TERMINATE;
            } else {
                Files.delete(dir);
                System.out.format("Deleted directory  %s%n", dir);
            }
            return result;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            System.out.format("Deleted file %s%n", file);
            return FileVisitResult.CONTINUE;
        }
    }
    FileVisitor<Path> visitor = new DeleteDirVisitor();
    return visitor;
}

From source file:Search.java

@Override
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
    search((Path) file);//from  w  ww  .j  a  va2 s. co  m
    if (!found) {
        return FileVisitResult.CONTINUE;
    } else {
        return FileVisitResult.TERMINATE;
    }
}

From source file:org.jetbrains.webdemo.backend.executor.ExecutorUtils.java

public static ExecutionResult executeCompiledFiles(Map<String, byte[]> files, String mainClass,
        List<Path> kotlinRuntimeJars, String arguments, Path executorsPolicy, boolean isJunit)
        throws Exception {
    Path codeDirectory = null;//from   w w  w. j  a v a2  s . c  om
    try {
        codeDirectory = storeFilesInTemporaryDirectory(files);
        JavaExecutorBuilder executorBuilder = new JavaExecutorBuilder().enableAssertions().setMemoryLimit(32)
                .enableSecurityManager().setPolicyFile(executorsPolicy).addToClasspath(kotlinRuntimeJars)
                .addToClasspath(jarFiles).addToClasspath(codeDirectory);
        if (isJunit) {
            executorBuilder.addToClasspath(junit);
            executorBuilder.addToClasspath(hamcrest);
            executorBuilder.setMainClass("org.jetbrains.webdemo.executors.JunitExecutor");
            executorBuilder.addArgument(codeDirectory.toString());
        } else {
            executorBuilder.setMainClass("org.jetbrains.webdemo.executors.JavaExecutor");
            executorBuilder.addArgument(mainClass);
        }

        for (String argument : arguments.split(" ")) {
            if (argument.trim().isEmpty())
                continue;
            executorBuilder.addArgument(argument);
        }

        ProgramOutput output = executorBuilder.build().execute();
        return parseOutput(output.getStandardOutput(), isJunit);
    } finally {
        try {
            if (codeDirectory != null) {
                Files.walkFileTree(codeDirectory, new FileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        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 exc) throws IOException {
                        return FileVisitResult.TERMINATE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir);
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
        } catch (IOException e) {
            ErrorWriter.getInstance().writeExceptionToExceptionAnalyzer(e, "Can't delete code directory");
        }
    }
}

From source file:fr.ortolang.diffusion.store.binary.BinaryStoreServiceTest.java

@After
public void tearDown() {
    try {/*  ww w.j a va2 s  . co m*/
        Files.walkFileTree(service.getBase(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                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 exc) throws IOException {
                LOGGER.log(Level.SEVERE, "unable to purge temporary created filesystem", exc);
                return FileVisitResult.TERMINATE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:com.dotcms.content.elasticsearch.business.ESIndexHelper.java

/**
 * Finds file within the directory named "snapshot-"
 * @param snapshotDirectory//from   w  w w  .  j a  v  a  2 s . co m
 * @return
 * @throws IOException
 */
public String findSnapshotName(File snapshotDirectory) throws IOException {
    String name = null;
    if (snapshotDirectory.isDirectory()) {
        class SnapshotVisitor extends SimpleFileVisitor<Path> {
            private String fileName;

            public String getFileName() {
                return fileName;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().startsWith(SNAPSHOT_PREFIX)) {
                    fileName = file.getFileName().toString();
                    return FileVisitResult.TERMINATE;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        }
        Path directory = Paths.get(snapshotDirectory.getAbsolutePath());
        SnapshotVisitor snapshotVisitor = new SnapshotVisitor();
        Files.walkFileTree(directory, snapshotVisitor);

        String fullName = snapshotVisitor.getFileName();
        if (fullName != null) {
            name = fullName.replaceFirst(SNAPSHOT_PREFIX, "");
        }
    }
    return name;
}

From source file:net.mozq.picto.core.ProcessCore.java

public static void findFiles(ProcessCondition processCondition, Consumer<ProcessData> processDataSetter,
        BooleanSupplier processStopper) throws IOException {

    Set<FileVisitOption> fileVisitOptionSet;
    if (processCondition.isFollowLinks()) {
        fileVisitOptionSet = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    } else {//from w ww .j  a  v  a  2s  .co  m
        fileVisitOptionSet = Collections.emptySet();
    }

    Files.walkFileTree(processCondition.getSrcRootPath(), fileVisitOptionSet, processCondition.getDept(),
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (processStopper.getAsBoolean()) {
                        return FileVisitResult.TERMINATE;
                    }

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                    if (attrs.isDirectory()) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    if (processStopper.getAsBoolean()) {
                        return FileVisitResult.TERMINATE;
                    }

                    if (!processCondition.getPathFilter().accept(file, attrs)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    Path rootRelativeSubPath = processCondition.getSrcRootPath().relativize(file.getParent());

                    ImageMetadata imageMetadata = getImageMetadata(file);

                    Date baseDate;
                    if (processCondition.isChangeFileCreationDate()
                            || processCondition.isChangeFileModifiedDate()
                            || processCondition.isChangeFileAccessDate()
                            || processCondition.isChangeExifDate()) {
                        baseDate = getBaseDate(processCondition, file, attrs, imageMetadata);
                    } else {
                        baseDate = null;
                    }

                    String destSubPathname = processCondition.getDestSubPathFormat().format(varName -> {
                        try {
                            switch (varName) {
                            case "Now":
                                return new Date();
                            case "ParentSubPath":
                                return rootRelativeSubPath.toString();
                            case "FileName":
                                return file.getFileName().toString();
                            case "BaseName":
                                return FileUtilz.getBaseName(file.getFileName().toString());
                            case "Extension":
                                return FileUtilz.getExt(file.getFileName().toString());
                            case "Size":
                                return Long.valueOf(Files.size(file));
                            case "CreationDate":
                                return (processCondition.isChangeFileCreationDate()) ? baseDate
                                        : new Date(attrs.creationTime().toMillis());
                            case "ModifiedDate":
                                return (processCondition.isChangeFileModifiedDate()) ? baseDate
                                        : new Date(attrs.lastModifiedTime().toMillis());
                            case "AccessDate":
                                return (processCondition.isChangeFileAccessDate()) ? baseDate
                                        : new Date(attrs.lastAccessTime().toMillis());
                            case "PhotoTakenDate":
                                return (processCondition.isChangeExifDate()) ? baseDate
                                        : getPhotoTakenDate(file, imageMetadata);
                            case "Width":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXIF_IMAGE_WIDTH);
                            case "Height":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXIF_IMAGE_LENGTH);
                            case "FNumber":
                                return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FNUMBER);
                            case "Aperture":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
                            case "MaxAperture":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_MAX_APERTURE_VALUE);
                            case "ISO":
                                return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_ISO);
                            case "FocalLength":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_FOCAL_LENGTH); // ?
                            case "FocalLength35mm":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_FOCAL_LENGTH_IN_35MM_FORMAT);
                            case "ShutterSpeed":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_SHUTTER_SPEED_VALUE);
                            case "Exposure":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE); // 
                            case "ExposureTime":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXPOSURE_TIME); // 
                            case "ExposureMode":
                                return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_MODE);
                            case "ExposureProgram":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXPOSURE_PROGRAM);
                            case "Brightness":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_BRIGHTNESS_VALUE);
                            case "WhiteBalance":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_WHITE_BALANCE_1);
                            case "LightSource":
                                return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_LIGHT_SOURCE);
                            case "Lens":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS);
                            case "LensMake":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MAKE);
                            case "LensModel":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MODEL);
                            case "LensSerialNumber":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_LENS_SERIAL_NUMBER);
                            case "Make":
                                return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MAKE);
                            case "Model":
                                return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MODEL);
                            case "SerialNumber":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_SERIAL_NUMBER);
                            case "Software":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_SOFTWARE);
                            case "ProcessingSoftware":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_PROCESSING_SOFTWARE);
                            case "OwnerName":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_OWNER_NAME);
                            case "CameraOwnerName":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_CAMERA_OWNER_NAME);
                            case "GPSLat":
                                return getEXIFGpsLat(imageMetadata);
                            case "GPSLatDeg":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE,
                                        0);
                            case "GPSLatMin":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE,
                                        1);
                            case "GPSLatSec":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE,
                                        2);
                            case "GPSLatRef":
                                return getEXIFStringValue(imageMetadata,
                                        GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF);
                            case "GPSLon":
                                return getEXIFGpsLon(imageMetadata);
                            case "GPSLonDeg":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE,
                                        0);
                            case "GPSLonMin":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE,
                                        1);
                            case "GPSLonSec":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE,
                                        2);
                            case "GPSLonRef":
                                return getEXIFStringValue(imageMetadata,
                                        GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF);
                            case "GPSAlt":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE);
                            case "GPSAltRef":
                                return getEXIFIntValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE_REF);
                            default:
                                throw new PictoInvalidDestinationPathException(Messages
                                        .getString("message.warn.invalid.destSubPath.varName", varName));
                            }
                        } catch (PictoException e) {
                            throw e;
                        } catch (Exception e) {
                            throw new PictoInvalidDestinationPathException(
                                    Messages.getString("message.warn.invalid.destSubPath.pattern"), e);
                        }
                    });

                    Path destSubPath = processCondition.getDestRootPath().resolve(destSubPathname).normalize();

                    if (!destSubPath.startsWith(processCondition.getDestRootPath())) {
                        throw new PictoInvalidDestinationPathException(
                                Messages.getString("message.warn.invalid.destination.path", destSubPath));
                    }

                    ProcessData processData = new ProcessData();
                    processData.setSrcPath(file);
                    processData.setSrcFileAttributes(attrs);
                    processData.setDestPath(destSubPath);
                    processData.setBaseDate(baseDate);

                    processDataSetter.accept(processData);

                    return FileVisitResult.CONTINUE;
                }
            });
}

From source file:fr.ortolang.diffusion.client.cmd.CopyCommand.java

private void copy(Path localPath, String workspace, String remotePath) {
    try {/*from ww w  .  ja v a 2 s  .co m*/
        Files.walkFileTree(localPath, new FileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                switch (mode) {
                case "objects":
                    String remoteDir = remotePath + localPath.getParent().relativize(dir).toString();
                    System.out.println("Copying dir " + dir + " to " + workspace + ":" + remoteDir);
                    try {
                        client.writeCollection(workspace, remoteDir, "");
                    } catch (OrtolangClientException | OrtolangClientAccountException e) {
                        e.printStackTrace();
                        errors.append("-> Unable to copy dir ").append(dir).append(" to ").append(remoteDir)
                                .append("\r\n");
                        return FileVisitResult.TERMINATE;
                    }
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                switch (mode) {
                case "objects":
                    String remoteFile = remotePath + localPath.getParent().relativize(file).toString();
                    System.out.println("Copying file " + file + " to " + workspace + ":" + remoteFile);
                    try {
                        client.writeDataObject(workspace, remoteFile, "", file.toFile(), null);
                    } catch (OrtolangClientException | OrtolangClientAccountException e) {
                        e.printStackTrace();
                        errors.append("-> Unable to copy file ").append(file).append(" to ").append(remoteFile)
                                .append("\r\n");
                        return FileVisitResult.TERMINATE;
                    }
                    break;
                case "metadata":
                    String remoteDir = remotePath
                            + localPath.getParent().relativize(file).getParent().toString();
                    System.out.println("Creating metadata file " + file + " to " + workspace + ":" + remoteDir);
                    String name = file.getFileName().toString();
                    try {
                        client.writeMetaData(workspace, remoteDir, name, null, file.toFile());
                    } catch (OrtolangClientException | OrtolangClientAccountException e) {
                        e.printStackTrace();
                        errors.append("-> Unable to copy file ").append(file).append(" to ").append(remoteDir)
                                .append("\r\n");
                        return FileVisitResult.TERMINATE;
                    }
                    break;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        System.out.println("Unable to walk file tree: " + e.getMessage());
    }
}

From source file:com.nridge.connector.fs.con_fs.core.FileCrawler.java

/**
 * Invoked for a directory before entries in the directory are visited.
 * Unless overridden, this method returns {@link java.nio.file.FileVisitResult#CONTINUE}
 *
 * @param aDirectory Directory instance.
 * @param aFileAttributes File attribute instance.
 */// ww  w  .  j  av a2s.  com
@Override
public FileVisitResult preVisitDirectory(Path aDirectory, BasicFileAttributes aFileAttributes)
        throws IOException {
    Logger appLogger = mAppMgr.getLogger(this, "preVisitDirectory");

    if (mAppMgr.isAlive()) {
        String pathName = aDirectory.toAbsolutePath().toString();
        if (mCrawlFollow.isMatchedNormalized(pathName)) {
            appLogger.debug(String.format("Following Path: %s", pathName));
            return FileVisitResult.CONTINUE;
        } else {
            appLogger.debug(String.format("Skipping Path: %s", pathName));
            return FileVisitResult.SKIP_SUBTREE;
        }
    } else
        return FileVisitResult.TERMINATE;
}

From source file:de.alexkamp.sandbox.ChrootSandbox.java

@Override
public void walkDirectoryTree(String basePath, final DirectoryWalker walker) throws IOException {
    final int baseNameCount = data.getBaseDir().toPath().getNameCount();

    File base = new File(data.getBaseDir(), basePath);

    Files.walkFileTree(base.toPath(), new FileVisitor<Path>() {
        @Override/*ww w  .j  a  v a2s  . co m*/
        public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                throws IOException {
            if (walker.visitDirectory(calcSubpath(path))) {
                return FileVisitResult.CONTINUE;
            }
            return FileVisitResult.SKIP_SUBTREE;
        }

        private String calcSubpath(Path path) {
            if (path.getNameCount() == baseNameCount) {
                return "/";
            }
            return "/" + path.subpath(baseNameCount, path.getNameCount()).toString();
        }

        @Override
        public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                throws IOException {
            String subpath = calcSubpath(path);
            if (walker.visitFile(subpath)) {
                try (InputStream is = Files.newInputStream(path)) {
                    walker.visitFileContent(subpath, is);
                }
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
            if (walker.failed(e)) {
                return FileVisitResult.CONTINUE;
            } else {
                return FileVisitResult.TERMINATE;
            }
        }

        @Override
        public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:com.ejisto.util.IOUtils.java

public static boolean emptyDir(File file) {
    Path directory = file.toPath();
    if (!Files.isDirectory(directory)) {
        return true;
    }/*from  ww  w. j  a va2s .  com*/
    try {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {

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

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
                return FileVisitResult.TERMINATE;
            }
        });
    } catch (IOException e) {
        IOUtils.log.error(format("error while trying to empty the directory %s", directory.toString()), e);
        return false;
    }
    return true;
}