Search in sources :

Example 6 with DirectoryIteratorException

use of java.nio.file.DirectoryIteratorException in project structr by structr.

the class DirectFileImportCommand method execute.

@Override
public void execute(final Map<String, Object> attributes) throws FrameworkException {
    indexer = StructrApp.getInstance(securityContext).getFulltextIndexer();
    final String sourcePath = getParameterValueAsString(attributes, "source", null);
    final String modeString = getParameterValueAsString(attributes, "mode", Mode.COPY.name()).toUpperCase();
    final String existingString = getParameterValueAsString(attributes, "existing", Existing.SKIP.name()).toUpperCase();
    final boolean doIndex = Boolean.parseBoolean(getParameterValueAsString(attributes, "index", Boolean.TRUE.toString()));
    if (StringUtils.isBlank(sourcePath)) {
        throw new FrameworkException(422, "Please provide 'source' attribute for deployment source directory path.");
    }
    if (!EnumUtils.isValidEnum(Mode.class, modeString)) {
        throw new FrameworkException(422, "Unknown value for 'mode' attribute. Valid values are: copy, move");
    }
    if (!EnumUtils.isValidEnum(Existing.class, existingString)) {
        throw new FrameworkException(422, "Unknown value for 'existing' attribute. Valid values are: skip, overwrite, rename");
    }
    // use actual enums
    final Existing existing = Existing.valueOf(existingString);
    final Mode mode = Mode.valueOf(modeString);
    final List<Path> paths = new ArrayList<>();
    if (sourcePath.contains(PathHelper.PATH_SEP)) {
        final String folderPart = PathHelper.getFolderPath(sourcePath);
        final String namePart = PathHelper.getName(sourcePath);
        if (StringUtils.isNotBlank(folderPart)) {
            final Path source = Paths.get(folderPart);
            if (!Files.exists(source)) {
                throw new FrameworkException(422, "Source path " + sourcePath + " does not exist.");
            }
            if (!Files.isDirectory(source)) {
                throw new FrameworkException(422, "Source path " + sourcePath + " is not a directory.");
            }
            try {
                try (final DirectoryStream<Path> stream = Files.newDirectoryStream(source, namePart)) {
                    for (final Path entry : stream) {
                        paths.add(entry);
                    }
                } catch (final DirectoryIteratorException ex) {
                    throw ex.getCause();
                }
            } catch (final IOException ioex) {
                throw new FrameworkException(422, "Unable to parse source path " + sourcePath + ".");
            }
        }
    } else {
        // Relative path
        final Path source = Paths.get(Settings.BasePath.getValue()).resolve(sourcePath);
        if (!Files.exists(source)) {
            throw new FrameworkException(422, "Source path " + sourcePath + " does not exist.");
        }
        paths.add(source);
    }
    final SecurityContext ctx = SecurityContext.getSuperUserInstance();
    final App app = StructrApp.getInstance(ctx);
    String targetPath = getParameterValueAsString(attributes, "target", "/");
    Folder targetFolder = null;
    ctx.setDoTransactionNotifications(false);
    if (StringUtils.isNotBlank(targetPath) && !("/".equals(targetPath))) {
        try (final Tx tx = app.tx()) {
            targetFolder = app.nodeQuery(Folder.class).and(StructrApp.key(Folder.class, "path"), targetPath).getFirst();
            if (targetFolder == null) {
                throw new FrameworkException(422, "Target path " + targetPath + " does not exist.");
            }
            tx.success();
        }
    }
    String msg = "Starting direct file import from source directory " + sourcePath + " into target path " + targetPath;
    logger.info(msg);
    publishProgressMessage(msg);
    paths.forEach((path) -> {
        try {
            final String newTargetPath;
            // If path is a directory, create it and use it as the new target folder
            if (Files.isDirectory(path)) {
                Path parentPath = path.getParent();
                if (parentPath == null) {
                    parentPath = path;
                }
                createFileOrFolder(ctx, app, parentPath, path, Files.readAttributes(path, BasicFileAttributes.class), sourcePath, targetPath, mode, existing, doIndex);
                newTargetPath = targetPath + PathHelper.PATH_SEP + PathHelper.clean(path.getFileName().toString());
            } else {
                newTargetPath = targetPath;
            }
            Files.walkFileTree(path, new FileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                    return createFileOrFolder(ctx, app, path, file, attrs, sourcePath, newTargetPath, mode, existing, doIndex);
                }

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

                @Override
                public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (final IOException ex) {
            logger.debug("Mode: " + modeString + ", path: " + sourcePath, ex);
        }
    });
    msg = "Finished direct file import from source directory " + sourcePath + ". Imported " + folderCount + " folders and " + fileCount + " files.";
    logger.info(msg);
    publishProgressMessage(msg);
}
Also used : Path(java.nio.file.Path) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) FrameworkException(org.structr.common.error.FrameworkException) Tx(org.structr.core.graph.Tx) ArrayList(java.util.ArrayList) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) Folder(org.structr.web.entity.Folder) SecurityContext(org.structr.common.SecurityContext) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 7 with DirectoryIteratorException

use of java.nio.file.DirectoryIteratorException in project musiccabinet by hakko.

the class DirectoryBrowserService method getContent.

private DirectoryContent getContent(Directory dir) {
    Set<File> foundFiles = new HashSet<>();
    Set<String> foundSubDirs = new HashSet<>();
    DirectoryContent content = new DirectoryContent(dir.getPath(), foundSubDirs, foundFiles);
    Path path = Paths.get(dir.getPath());
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
        for (Path file : stream) {
            BasicFileAttributeView view = getFileAttributeView(file, BasicFileAttributeView.class);
            BasicFileAttributes attr = view.readAttributes();
            if (attr.isDirectory()) {
                foundSubDirs.add(file.toAbsolutePath().toString());
            } else if (attr.isRegularFile()) {
                foundFiles.add(new File(file, attr));
            }
        }
    } catch (IOException | DirectoryIteratorException e) {
        throw new ApplicationContextException("Couldn't read " + dir.getPath(), e);
    }
    return content;
}
Also used : Path(java.nio.file.Path) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) IOException(java.io.IOException) ApplicationContextException(org.springframework.context.ApplicationContextException) BasicFileAttributeView(java.nio.file.attribute.BasicFileAttributeView) DirectoryContent(com.github.hakko.musiccabinet.domain.model.aggr.DirectoryContent) File(com.github.hakko.musiccabinet.domain.model.library.File) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) HashSet(java.util.HashSet)

Example 8 with DirectoryIteratorException

use of java.nio.file.DirectoryIteratorException in project jetty.project by eclipse.

the class PathResource method list.

@Override
public String[] list() {
    try (DirectoryStream<Path> dir = Files.newDirectoryStream(path)) {
        List<String> entries = new ArrayList<>();
        for (Path entry : dir) {
            String name = entry.getFileName().toString();
            if (Files.isDirectory(entry)) {
                name += "/";
            }
            entries.add(name);
        }
        int size = entries.size();
        return entries.toArray(new String[size]);
    } catch (DirectoryIteratorException e) {
        LOG.debug(e);
    } catch (IOException e) {
        LOG.debug(e);
    }
    return null;
}
Also used : Path(java.nio.file.Path) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) ArrayList(java.util.ArrayList) IOException(java.io.IOException)

Example 9 with DirectoryIteratorException

use of java.nio.file.DirectoryIteratorException in project kanzi by flanglet.

the class Kanzi method createFileList.

public static void createFileList(String target, List<Path> files) throws IOException {
    if (target == null)
        return;
    Path root = Paths.get(target);
    if (Files.exists(root) == false)
        throw new IOException("Cannot access input file '" + root + "'");
    if ((Files.isRegularFile(root) == true) && (Files.isHidden(root) == true))
        throw new IOException("Cannot access input file '" + root + "'");
    if (Files.isRegularFile(root) == true) {
        if (target.charAt(0) != '.')
            files.add(root);
        return;
    }
    // If not a regular file and not a directory (a link ?), fail
    if (Files.isDirectory(root) == false)
        throw new IOException("Invalid file type '" + root + "'");
    String suffix = File.separator + ".";
    String strRoot = root.toString();
    boolean isRecursive = !strRoot.endsWith(suffix);
    if (isRecursive == true) {
        if (strRoot.endsWith(File.separator) == false)
            root = Paths.get(strRoot + File.separator);
    } else {
        // Remove suffix
        root = Paths.get(strRoot.substring(0, strRoot.length() - 1));
    }
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(root)) {
        for (Path entry : stream) {
            if ((Files.exists(entry) == false) || (Files.isHidden(entry) == true))
                continue;
            if ((Files.isRegularFile(entry) == true) && (entry.getFileName().toString().startsWith(".") == false))
                files.add(entry);
            else if ((isRecursive == true) && (Files.isDirectory(entry) == true))
                createFileList(entry.toString(), files);
        }
    } catch (DirectoryIteratorException e) {
        throw e.getCause();
    }
}
Also used : Path(java.nio.file.Path) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) IOException(java.io.IOException)

Aggregations

DirectoryIteratorException (java.nio.file.DirectoryIteratorException)9 Path (java.nio.file.Path)9 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)5 UncheckedIOException (java.io.UncheckedIOException)2 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)2 DirectoryContent (com.github.hakko.musiccabinet.domain.model.aggr.DirectoryContent)1 File (com.github.hakko.musiccabinet.domain.model.library.File)1 JsonObject (com.google.gson.JsonObject)1 BufferedReader (java.io.BufferedReader)1 InputStream (java.io.InputStream)1 DirectoryStream (java.nio.file.DirectoryStream)1 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)1 FileVisitResult (java.nio.file.FileVisitResult)1 BasicFileAttributeView (java.nio.file.attribute.BasicFileAttributeView)1 HashSet (java.util.HashSet)1 TreeMap (java.util.TreeMap)1 NBTTagCompound (net.minecraft.nbt.NBTTagCompound)1 ReportedException (net.minecraft.util.ReportedException)1 UnmodifiableArrayList (org.apache.sis.internal.util.UnmodifiableArrayList)1