Example usage for java.nio.file Path getFileSystem

List of usage examples for java.nio.file Path getFileSystem

Introduction

In this page you can find the example usage for java.nio.file Path getFileSystem.

Prototype

FileSystem getFileSystem();

Source Link

Document

Returns the file system that created this object.

Usage

From source file:org.audiveris.omr.classifier.AbstractClassifier.java

/**
 * Store the engine internals, always as user files.
 *
 * @param fileName file name for classifier data (model & norms)
 *//*from  ww  w  .  ja  va2  s.c  o m*/
protected void store(String fileName) {
    final Path path = WellKnowns.TRAIN_FOLDER.resolve(fileName);

    try {
        if (!Files.exists(WellKnowns.TRAIN_FOLDER)) {
            Files.createDirectories(WellKnowns.TRAIN_FOLDER);
            logger.info("Created directory {}", WellKnowns.TRAIN_FOLDER);
        }

        Path root = ZipFileSystem.create(path); // Delete if already exists

        storeModel(root);
        storeNorms(root);

        root.getFileSystem().close();

        logger.info("{} data stored to {}", getName(), path);
    } catch (Exception ex) {
        logger.warn("Error storing {} {}", getName(), ex.toString(), ex);
    }
}

From source file:org.cryptomator.cryptofs.CryptoDirectoryStreamTest.java

License:asdf

@Before
@SuppressWarnings("unchecked")
public void setup() throws IOException {
    filenameCryptor = cryptorProvider.createNew().fileNameCryptor();

    ciphertextDirPath = Mockito.mock(Path.class);
    FileSystem fs = Mockito.mock(FileSystem.class);
    Mockito.when(ciphertextDirPath.getFileSystem()).thenReturn(fs);
    FileSystemProvider provider = Mockito.mock(FileSystemProvider.class);
    Mockito.when(fs.provider()).thenReturn(provider);
    dirStream = Mockito.mock(DirectoryStream.class);
    Mockito.when(provider.newDirectoryStream(Mockito.same(ciphertextDirPath), Mockito.any()))
            .thenReturn(dirStream);/*  www . j a v  a  2 s.  c  om*/
    longFileNameProvider = Mockito.mock(LongFileNameProvider.class);
    conflictResolver = Mockito.mock(ConflictResolver.class);
    finallyUtil = mock(FinallyUtil.class);
    Mockito.when(longFileNameProvider.inflate(Mockito.anyString())).then(invocation -> {
        String shortName = invocation.getArgument(0);
        if (shortName.contains("invalid")) {
            throw new IOException("invalid shortened name");
        } else {
            return StringUtils.removeEnd(shortName, ".lng");
        }
    });
    cryptoPathMapper = Mockito.mock(CryptoPathMapper.class);
    Mockito.when(cryptoPathMapper.resolveDirectory(Mockito.any())).then(invocation -> {
        Path dirFilePath = invocation.getArgument(0);
        if (dirFilePath.toString().contains("invalid")) {
            throw new IOException("Invalid directory.");
        }
        Path dirPath = Mockito.mock(Path.class);
        BasicFileAttributes attrs = Mockito.mock(BasicFileAttributes.class);
        Mockito.when(dirPath.getFileSystem()).thenReturn(fs);
        Mockito.when(provider.readAttributes(dirPath, BasicFileAttributes.class)).thenReturn(attrs);
        Mockito.when(attrs.isDirectory()).thenReturn(!dirFilePath.toString().contains("noDirectory"));
        return new Directory("asdf", dirPath);
    });

    Mockito.when(conflictResolver.resolveConflictsIfNecessary(Mockito.any(), Mockito.any()))
            .then(returnsFirstArg());

    doAnswer(invocation -> {
        for (Object runnable : invocation.getArguments()) {
            ((RunnableThrowingException<?>) runnable).run();
        }
        return null;
    }).when(finallyUtil).guaranteeInvocationOf(any(RunnableThrowingException.class),
            any(RunnableThrowingException.class), any(RunnableThrowingException.class));
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Modifies given allFiles object to exclude all files given by the excl pattern
 * /* www  .  j  a  v a 2  s . c o  m*/
 * Semantics: Remove all files from the set, which match the given pattern
 */
private void handleExclude(Exclude excl, Path localRoot, Set<Path> allFiles) {
    PathMatcher pathMatcher = localRoot.getFileSystem().getPathMatcher("glob:" + excl.getPattern());
    Iterator<Path> it = allFiles.iterator();
    while (it.hasNext()) {
        Path curPath = it.next();
        if (pathMatcher.matches(curPath)) {
            it.remove();
        }
    }
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Modifies given allFiles object to include all files given by the incl pattern
 * /*from   ww w . j  a  va 2s . c o m*/
 * Semantics: Add all files from localRoot to allFiles matching the pattern
 */
private void handleInclude(final Include incl, final Path localRoot, final Set<Path> allFiles) {
    final PathMatcher pathMatcher = localRoot.getFileSystem().getPathMatcher("glob:" + incl.getPattern());
    try {
        Files.walkFileTree(localRoot, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path relFile = localRoot.relativize(file);
                if (pathMatcher.matches(relFile)) {
                    allFiles.add(file);
                }
                return CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (pathMatcher.matches(dir)) {
                    Set<Path> filesToAdd = CSARImporter.this.getAllFiles(dir);
                    allFiles.addAll(filesToAdd);
                    return SKIP_SUBTREE;
                } else {
                    return CONTINUE;
                }
            }
        });
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.elasticsearch.bootstrap.JarHell.java

/**
 * Checks the set of URLs for duplicate classes
 * @throws IllegalStateException if jar hell was found
 *///from  w  ww  .  j a  v a  2 s .  c  o  m
@SuppressForbidden(reason = "needs JarFile for speed, just reading entries")
public static void checkJarHell(URL urls[]) throws Exception {
    ESLogger logger = Loggers.getLogger(JarHell.class);
    // we don't try to be sneaky and use deprecated/internal/not portable stuff
    // like sun.boot.class.path, and with jigsaw we don't yet have a way to get
    // a "list" at all. So just exclude any elements underneath the java home
    String javaHome = System.getProperty("java.home");
    logger.debug("java.home: {}", javaHome);
    final Map<String, Path> clazzes = new HashMap<>(32768);
    Set<Path> seenJars = new HashSet<>();
    for (final URL url : urls) {
        final Path path = PathUtils.get(url.toURI());
        // exclude system resources
        if (path.startsWith(javaHome)) {
            logger.debug("excluding system resource: {}", path);
            continue;
        }
        if (path.toString().endsWith(".jar")) {
            if (!seenJars.add(path)) {
                logger.debug("excluding duplicate classpath element: {}", path);
                continue; // we can't fail because of sheistiness with joda-time
            }
            logger.debug("examining jar: {}", path);
            try (JarFile file = new JarFile(path.toString())) {
                Manifest manifest = file.getManifest();
                if (manifest != null) {
                    checkManifest(manifest, path);
                }
                // inspect entries
                Enumeration<JarEntry> elements = file.entries();
                while (elements.hasMoreElements()) {
                    String entry = elements.nextElement().getName();
                    if (entry.endsWith(".class")) {
                        // for jar format, the separator is defined as /
                        entry = entry.replace('/', '.').substring(0, entry.length() - 6);
                        checkClass(clazzes, entry, path);
                    }
                }
            }
        } else {
            logger.debug("examining directory: {}", path);
            // case for tests: where we have class files in the classpath
            final Path root = PathUtils.get(url.toURI());
            final String sep = root.getFileSystem().getSeparator();
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String entry = root.relativize(file).toString();
                    if (entry.endsWith(".class")) {
                        // normalize with the os separator
                        entry = entry.replace(sep, ".").substring(0, entry.length() - 6);
                        checkClass(clazzes, entry, path);
                    }
                    return super.visitFile(file, attrs);
                }
            });
        }
    }
}

From source file:org.everit.osgi.dev.maven.util.FileManager.java

private static void setPermissionsOnFile(final File file, final ZipArchiveEntry entry) throws IOException {
    if (entry.getPlatform() == ZipArchiveEntry.PLATFORM_FAT) {
        return;/*from   ww  w.  j a  v a 2 s . c  o m*/
    }
    int unixPermissions = entry.getUnixMode();

    Set<PosixFilePermission> perms = new HashSet<>();

    if ((unixPermissions & OWNER_EXECUTE_BITMASK) > 0) {
        perms.add(PosixFilePermission.OWNER_EXECUTE);
    }

    if ((unixPermissions & GROUP_EXECUTE_BITMASK) > 0) {
        perms.add(PosixFilePermission.GROUP_EXECUTE);
    }

    if ((unixPermissions & OTHERS_EXECUTE_BITMASK) > 0) {
        perms.add(PosixFilePermission.OTHERS_EXECUTE);
    }

    if ((unixPermissions & OWNER_READ_BITMASK) > 0) {
        perms.add(PosixFilePermission.OWNER_READ);
    }

    if ((unixPermissions & GROUP_READ_BITMASK) > 0) {
        perms.add(PosixFilePermission.GROUP_READ);
    }

    if ((unixPermissions & OTHERS_READ_BITMASK) > 0) {
        perms.add(PosixFilePermission.OTHERS_READ);
    }

    if ((unixPermissions & OWNER_WRITE_BITMASK) > 0) {
        perms.add(PosixFilePermission.OWNER_WRITE);
    }

    if ((unixPermissions & GROUP_WRITE_BITMASK) > 0) {
        perms.add(PosixFilePermission.GROUP_WRITE);
    }

    if ((unixPermissions & OTHERS_WRITE_BITMASK) > 0) {
        perms.add(PosixFilePermission.OTHERS_WRITE);
    }

    Path path = file.toPath();
    if (path.getFileSystem().supportedFileAttributeViews().contains("posix")) {
        Files.setPosixFilePermissions(path, perms);
    } else {
        setPermissionsOnFileInNonPosixSystem(file, perms);
    }
}

From source file:org.flowerplatform.web.git.GitUtils.java

public void listenForChanges(File file) throws IOException {
    Path path = file.toPath();
    if (file.isDirectory()) {
        WatchService ws = path.getFileSystem().newWatchService();
        path.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY);
        WatchKey watch = null;/*w ww . ja v  a2 s.  co m*/
        while (true) {
            System.out.println("Watching directory: " + file.getPath());
            try {
                watch = ws.take();
            } catch (InterruptedException ex) {
                System.err.println("Interrupted");
            }
            List<WatchEvent<?>> events = watch.pollEvents();
            if (!watch.reset()) {
                break;
            }
            for (WatchEvent<?> event : events) {
                Kind<Path> kind = (Kind<Path>) event.kind();
                Path context = (Path) event.context();
                if (kind.equals(StandardWatchEventKinds.OVERFLOW)) {
                    System.out.println("OVERFLOW");
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) {
                    System.out.println("Created: " + context.getFileName());
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) {
                    System.out.println("Deleted: " + context.getFileName());
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
                    System.out.println("Modified: " + context.getFileName());
                }
            }
        }
    } else {
        System.err.println("Not a directory. Will exit.");
    }
}

From source file:org.mycore.common.MCRUtils.java

/**
 * Extracts files in a tar archive. Currently works only on uncompressed tar files.
 * //from w  w w. j  av a2 s.  c om
 * @param source
 *            the uncompressed tar to extract
 * @param expandToDirectory
 *            the directory to extract the tar file to
 * @throws IOException
 *             if the source file does not exists
 */
public static void untar(Path source, Path expandToDirectory) throws IOException {
    try (TarArchiveInputStream tain = new TarArchiveInputStream(Files.newInputStream(source))) {
        TarArchiveEntry tarEntry;
        FileSystem targetFS = expandToDirectory.getFileSystem();
        HashMap<Path, FileTime> directoryTimes = new HashMap<>();
        while ((tarEntry = tain.getNextTarEntry()) != null) {
            Path target = MCRPathUtils.getPath(targetFS, tarEntry.getName());
            Path absoluteTarget = expandToDirectory.resolve(target).normalize().toAbsolutePath();
            if (tarEntry.isDirectory()) {
                Files.createDirectories(expandToDirectory.resolve(absoluteTarget));
                directoryTimes.put(absoluteTarget,
                        FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            } else {
                if (Files.notExists(absoluteTarget.getParent())) {
                    Files.createDirectories(absoluteTarget.getParent());
                }
                Files.copy(tain, absoluteTarget, StandardCopyOption.REPLACE_EXISTING);
                Files.setLastModifiedTime(absoluteTarget,
                        FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            }
        }
        //restore directory dates
        Files.walkFileTree(expandToDirectory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Path absolutePath = dir.normalize().toAbsolutePath();
                Files.setLastModifiedTime(absolutePath, directoryTimes.get(absolutePath));
                return super.postVisitDirectory(dir, exc);
            }
        });
    }
}

From source file:org.sakuli.AbstractLogAwareTest.java

public static void deleteFile(Path logFile) {
    FileSystemProvider provider = logFile.getFileSystem().provider();
    try {//from  w w  w . j a  v a  2s.com
        provider.deleteIfExists(logFile);
    } catch (IOException e) {
        //do nothing
    }
}

From source file:sf.net.experimaestro.fs.XPMFileSystemProvider.java

@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
    final Path _path = resolvePath(path);
    _path.getFileSystem().provider().checkAccess(_path, modes);
}