Search in sources :

Example 1 with DirectoryIteratorException

use of java.nio.file.DirectoryIteratorException in project jdk8u_jdk by JetBrains.

the class StreamTest method testDirectoryIteratorException.

public void testDirectoryIteratorException() throws IOException {
    Path dir = testFolder.resolve("dir2");
    Path trigger = dir.resolve("DirectoryIteratorException");
    Files.createFile(trigger);
    FaultyFileSystem.FaultyFSProvider fsp = FaultyFileSystem.FaultyFSProvider.getInstance();
    FaultyFileSystem fs = (FaultyFileSystem) fsp.newFileSystem(dir, null);
    try {
        fsp.setFaultyMode(false);
        Path fakeRoot = fs.getRoot();
        try {
            try (Stream<Path> s = Files.list(fakeRoot)) {
                s.forEach(path -> assertEquals(path.getFileName().toString(), "DirectoryIteratorException"));
            }
        } catch (UncheckedIOException uioe) {
            fail("Unexpected exception.");
        }
        fsp.setFaultyMode(true);
        try {
            try (DirectoryStream<Path> ds = Files.newDirectoryStream(fakeRoot)) {
                Iterator<Path> itor = ds.iterator();
                while (itor.hasNext()) {
                    itor.next();
                }
            }
            fail("Shoule throw DirectoryIteratorException");
        } catch (DirectoryIteratorException die) {
        }
        try {
            try (Stream<Path> s = Files.list(fakeRoot)) {
                s.forEach(path -> fail("should not get here"));
            }
        } catch (UncheckedIOException uioe) {
            assertTrue(uioe.getCause() instanceof FaultyFileSystem.FaultyException);
        } catch (DirectoryIteratorException die) {
            fail("Should have been converted into UncheckedIOException.");
        }
    } finally {
        // Cleanup
        if (fs != null) {
            fs.close();
        }
        Files.delete(trigger);
    }
}
Also used : Path(java.nio.file.Path) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) UncheckedIOException(java.io.UncheckedIOException)

Example 2 with DirectoryIteratorException

use of java.nio.file.DirectoryIteratorException in project oap by oaplatform.

the class FileWalkerCache method newDirectoryStream.

public DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException {
    final ArrayList<Path> list = map.get(dir);
    if (list == null) {
        final ArrayList<Path> paths = map.computeIfAbsent(dir, (d) -> new ArrayList<>());
        return java.nio.file.Files.newDirectoryStream(dir, (file) -> {
            paths.add(file);
            exists.put(file, true);
            return filter.accept(file);
        });
    }
    return new DirectoryStream<Path>() {

        @Override
        public Iterator<Path> iterator() {
            return Iterators.filter(list.iterator(), (p) -> {
                try {
                    return filter.accept(p);
                } catch (IOException e) {
                    throw new DirectoryIteratorException(e);
                }
            });
        }

        @Override
        public void close() throws IOException {
        }
    };
}
Also used : Path(java.nio.file.Path) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) DirectoryStream(java.nio.file.DirectoryStream) IOException(java.io.IOException)

Example 3 with DirectoryIteratorException

use of java.nio.file.DirectoryIteratorException in project SpongeCommon by SpongePowered.

the class SpongePlayerDataHandler method init.

public static void init() {
    final SpongePlayerDataHandler handlerInstance = Holder.INSTANCE;
    if (!Sponge.isServerAvailable()) {
        return;
    }
    handlerInstance.playerDataMap = new ConcurrentHashMap<>();
    final Path filePath = WorldManager.getCurrentSavesDirectory().get().resolve("data").resolve(SPONGE_DATA);
    try {
        handlerInstance.playerDir = filePath;
        Files.createDirectories(handlerInstance.playerDir);
        final List<Path> playerFiles = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(filePath, "*.{dat}")) {
            for (Path entry : stream) {
                playerFiles.add(entry);
            }
        } catch (DirectoryIteratorException e) {
            SpongeImpl.getLogger().error("Something happened when trying to gather all player files", e);
        }
        for (Path playerFile : playerFiles) {
            if (Files.isReadable(playerFile)) {
                NBTTagCompound compound;
                try (final InputStream stream = Files.newInputStream(playerFile)) {
                    compound = CompressedStreamTools.readCompressed(stream);
                }
                // TODO Hard exception? Logger entry?
                if (compound == null) {
                    throw new RuntimeException("Failed to decompress player data within [" + playerFile + "]!");
                }
                DataContainer container = NbtTranslator.getInstance().translateFrom(compound);
                SpongePlayerData data = container.getSerializable(DataQuery.of(), SpongePlayerData.class).get();
                handlerInstance.playerDataMap.put(data.uuid, data);
            }
        }
        playerFiles.clear();
    } catch (FileAlreadyExistsException e) {
        SpongeImpl.getLogger().error("Someone went and created a file for the desired path: {}", filePath);
    } catch (Exception e) {
        e.printStackTrace();
    }
    handlerInstance.hasInitialized = true;
}
Also used : Path(java.nio.file.Path) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) DataContainer(org.spongepowered.api.data.DataContainer)

Example 4 with DirectoryIteratorException

use of java.nio.file.DirectoryIteratorException in project sis by apache.

the class Store method components.

/**
 * Returns all resources found in the folder given at construction time.
 * Only the resources recognized by a {@link DataStore} will be included.
 * This includes sub-folders. Resources are in no particular order.
 */
@Override
@SuppressWarnings("ReturnOfCollectionOrArrayField")
public synchronized Collection<Resource> components() throws DataStoreException {
    if (components == null) {
        final List<DataStore> resources = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(location, this)) {
            for (final Path candidate : stream) {
                /*
                     * The candidate path may be a symbolic link to a file that we have previously read.
                     * In such case, use the existing data store.   A use case is a directory containing
                     * hundred of GeoTIFF files all accompanied by ".prj" files having identical content.
                     * (Note: those ".prj" files should be invisible since they should be identified as
                     * GeoTIFF auxiliary files, but current Store implementation does not know that).
                     */
                final Path real = candidate.toRealPath();
                DataStore next = children.get(real);
                if (next instanceof Store) {
                    // Warn about directories only.
                    ((Store) next).sharedRepository(real);
                }
                if (next == null) {
                    /*
                         * The candidate file has never been read before. Try to read it now.
                         * If the file format is unknown (UnsupportedStorageException), we will
                         * check if we can open it as a child folder store before to skip it.
                         */
                    final StorageConnector connector = new StorageConnector(candidate);
                    connector.setOption(OptionKey.LOCALE, locale);
                    connector.setOption(OptionKey.TIMEZONE, timezone);
                    connector.setOption(OptionKey.ENCODING, encoding);
                    try {
                        if (componentProvider == null) {
                            // May throw UnsupportedStorageException.
                            next = DataStores.open(connector);
                        } else if (componentProvider.probeContent(connector).isSupported()) {
                            // Open a file of specified format.
                            next = componentProvider.open(connector);
                        } else if (Files.isDirectory(candidate)) {
                            // Open a sub-directory.
                            next = new Store(this, connector);
                        } else {
                            // Not the format specified at construction time.
                            connector.closeAllExcept(null);
                            continue;
                        }
                    } catch (UnsupportedStorageException ex) {
                        if (!Files.isDirectory(candidate)) {
                            connector.closeAllExcept(null);
                            listeners.warning(Level.FINE, null, ex);
                            continue;
                        }
                        next = new Store(this, connector);
                    } catch (DataStoreException ex) {
                        try {
                            connector.closeAllExcept(null);
                        } catch (DataStoreException s) {
                            ex.addSuppressed(s);
                        }
                        throw ex;
                    }
                    /*
                         * At this point we got the data store. It could happen that a store for
                         * the same file has been added concurrently, so we need to check again.
                         */
                    final DataStore existing = children.putIfAbsent(real, next);
                    if (existing != null) {
                        next.close();
                        next = existing;
                        if (next instanceof Store) {
                            // Warn about directories only.
                            ((Store) next).sharedRepository(real);
                        }
                    }
                }
                resources.add(next);
            }
        } catch (DirectoryIteratorException | UncheckedIOException ex) {
            // The cause is an IOException (no other type allowed).
            throw new DataStoreException(canNotRead(), ex.getCause());
        } catch (IOException ex) {
            throw new DataStoreException(canNotRead(), ex);
        } catch (BackingStoreException ex) {
            throw ex.unwrapOrRethrow(DataStoreException.class);
        }
        components = UnmodifiableArrayList.wrap(resources.toArray(new Resource[resources.size()]));
    }
    // Safe because unmodifiable list.
    return components;
}
Also used : Path(java.nio.file.Path) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) StorageConnector(org.apache.sis.storage.StorageConnector) DataStoreException(org.apache.sis.storage.DataStoreException) ArrayList(java.util.ArrayList) UnmodifiableArrayList(org.apache.sis.internal.util.UnmodifiableArrayList) BackingStoreException(org.apache.sis.util.collection.BackingStoreException) DataStore(org.apache.sis.storage.DataStore) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) DataStore(org.apache.sis.storage.DataStore) UnsupportedStorageException(org.apache.sis.storage.UnsupportedStorageException)

Example 5 with DirectoryIteratorException

use of java.nio.file.DirectoryIteratorException in project Wurst-MC-1.12 by Wurst-Imperium.

the class AutoBuildMod method loadTemplates.

public void loadTemplates() {
    TreeMap<String, int[][]> templates = new TreeMap<>();
    ArrayList<Path> oldTemplates = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(WurstFolders.AUTOBUILD, "*.json")) {
        for (Path path : stream) try (BufferedReader reader = Files.newBufferedReader(path)) {
            JsonObject json = JsonUtils.jsonParser.parse(reader).getAsJsonObject();
            int[][] blocks = JsonUtils.gson.fromJson(json.get("blocks"), int[][].class);
            if (blocks[0].length == 4) {
                oldTemplates.add(path);
                continue;
            }
            String name = path.getFileName().toString();
            name = name.substring(0, name.lastIndexOf(".json"));
            templates.put(name, blocks);
        } catch (Exception e) {
            System.err.println("Failed to load template: " + path.getFileName());
            e.printStackTrace();
        }
    } catch (IOException | DirectoryIteratorException e) {
        throw new ReportedException(CrashReport.makeCrashReport(e, "Loading AutoBuild templates"));
    }
    // rename old templates
    for (Path path : oldTemplates) try {
        Path newPath = path.resolveSibling(path.getFileName() + "_old");
        Files.move(path, newPath);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // add default templates and try again
    if (templates.isEmpty() || !oldTemplates.isEmpty()) {
        createDefaultTemplates();
        loadTemplates();
        return;
    }
    setTemplates(templates);
}
Also used : Path(java.nio.file.Path) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) TreeMap(java.util.TreeMap) ReportedException(net.minecraft.util.ReportedException) IOException(java.io.IOException) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) BufferedReader(java.io.BufferedReader) ReportedException(net.minecraft.util.ReportedException)

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