Search in sources :

Example 66 with NoSuchFileException

use of java.nio.file.NoSuchFileException in project cryptofs by cryptomator.

the class DirectoryIdLoaderTest method testDirectoryIdsForTwoNonExistingFilesDiffer.

@Test
public void testDirectoryIdsForTwoNonExistingFilesDiffer() throws IOException {
    doThrow(new NoSuchFileException("foo")).when(provider).newFileChannel(eq(dirFilePath), any());
    doThrow(new NoSuchFileException("bar")).when(provider).newFileChannel(eq(otherDirFilePath), any());
    String first = inTest.load(dirFilePath);
    String second = inTest.load(otherDirFilePath);
    assertThat(first, is(not(second)));
}
Also used : NoSuchFileException(java.nio.file.NoSuchFileException) Test(org.junit.Test)

Example 67 with NoSuchFileException

use of java.nio.file.NoSuchFileException in project cryptofs by cryptomator.

the class DirectoryIdLoaderTest method testDirectoryIdForNonExistingFileIsNotEmpty.

@Test
public void testDirectoryIdForNonExistingFileIsNotEmpty() throws IOException {
    doThrow(new NoSuchFileException("foo")).when(provider).newFileChannel(eq(dirFilePath), any());
    String result = inTest.load(dirFilePath);
    assertThat(result, is(notNullValue()));
    assertThat(result, is(not("")));
}
Also used : NoSuchFileException(java.nio.file.NoSuchFileException) Test(org.junit.Test)

Example 68 with NoSuchFileException

use of java.nio.file.NoSuchFileException in project storm by apache.

the class ServerUtils method isAnyPosixProcessPidDirAlive.

/**
 * Find if the process is alive using the existence of /proc/<pid> directory
 * owned by the supplied expectedUser. This is an alternative to "ps -p pid -u uid" command
 * used in {@link #isAnyPosixProcessAlive(Collection, int)}
 *
 * <p>
 * Processes are tracked using the existence of the directory "/proc/&lt;pid&gt;
 * For each of the supplied PIDs, their PID directory is checked for existence and ownership
 * by the specified uid.
 * </p>
 *
 * @param pids Process IDs that need to be monitored for liveness
 * @param expectedUser the userId that is expected to own that process
 * @param mockFileOwnerToUid if true (used for testing), then convert File.owner to UID
 * @return true if any one of the processes is owned by expectedUser and alive, else false
 * @throws IOException on I/O exception
 */
@VisibleForTesting
public static boolean isAnyPosixProcessPidDirAlive(Collection<Long> pids, String expectedUser, boolean mockFileOwnerToUid) throws IOException {
    File procDir = new File("/proc");
    if (!procDir.exists()) {
        throw new IOException("Missing process directory " + procDir.getAbsolutePath() + ": method not supported on " + "os.name=" + System.getProperty("os.name"));
    }
    for (long pid : pids) {
        File pidDir = new File(procDir, String.valueOf(pid));
        if (!pidDir.exists()) {
            continue;
        }
        // check if existing process is owned by the specified expectedUser, if not, the process is dead
        String actualUser;
        try {
            actualUser = Files.getOwner(pidDir.toPath()).getName();
        } catch (NoSuchFileException ex) {
            // process died before the expectedUser can be checked
            continue;
        }
        if (mockFileOwnerToUid) {
            // code activated in testing to simulate Files.getOwner returning UID (which sometimes happens in runtime)
            if (StringUtils.isNumeric(actualUser)) {
                LOG.info("Skip mocking, since owner {} of pidDir {} is already numeric", actualUser, pidDir);
            } else {
                Integer actualUid = cachedUserToUidMap.get(actualUser);
                if (actualUid == null) {
                    actualUid = ServerUtils.getUserId(actualUser);
                    if (actualUid < 0) {
                        String err = String.format("Cannot get UID for %s, while mocking the owner of pidDir %s", actualUser, pidDir.getAbsolutePath());
                        throw new IOException(err);
                    }
                    cachedUserToUidMap.put(actualUser, actualUid);
                    LOG.info("Found UID {} for {}, while mocking the owner of pidDir {}", actualUid, actualUser, pidDir);
                } else {
                    LOG.info("Found cached UID {} for {}, while mocking the owner of pidDir {}", actualUid, actualUser, pidDir);
                }
                actualUser = String.valueOf(actualUid);
            }
        }
        // sometimes uid is returned instead of username - if so, try to convert and compare with uid
        if (StringUtils.isNumeric(actualUser)) {
            // numeric actualUser - this is UID not user
            LOG.debug("Process directory {} owner is uid={}", pidDir, actualUser);
            int actualUid = Integer.parseInt(actualUser);
            Integer expectedUid = cachedUserToUidMap.get(expectedUser);
            if (expectedUid == null) {
                expectedUid = ServerUtils.getUserId(expectedUser);
                if (expectedUid < 0) {
                    String err = String.format("Cannot get uid for %s to compare with owner id=%d of process directory %s", expectedUser, actualUid, pidDir.getAbsolutePath());
                    throw new IOException(err);
                }
                cachedUserToUidMap.put(expectedUser, expectedUid);
            }
            if (expectedUid == actualUid) {
                LOG.debug("Process {} is alive and owned by expectedUser {}/{}", pid, expectedUser, expectedUid);
                return true;
            }
            LOG.info("Prior process is dead, since directory {} owner {} is not same as expectedUser {}/{}, " + "likely pid {} was reused for a new process for uid {}, {}", pidDir, actualUser, expectedUser, expectedUid, pid, actualUid, getProcessDesc(pidDir));
        } else {
            // actualUser is a string
            LOG.debug("Process directory {} owner is {}", pidDir, actualUser);
            if (expectedUser.equals(actualUser)) {
                LOG.debug("Process {} is alive and owned by expectedUser {}", pid, expectedUser);
                return true;
            }
            LOG.info("Prior process is dead, since directory {} owner {} is not same as expectedUser {}, " + "likely pid {} was reused for a new process for actualUser {}, {}}", pidDir, actualUser, expectedUser, pid, actualUser, getProcessDesc(pidDir));
        }
    }
    LOG.info("None of the processes {} are alive AND owned by expectedUser {}", pids, expectedUser);
    return false;
}
Also used : NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) JarFile(java.util.jar.JarFile) ZipFile(java.util.zip.ZipFile) File(java.io.File) VisibleForTesting(org.apache.storm.shade.com.google.common.annotations.VisibleForTesting)

Example 69 with NoSuchFileException

use of java.nio.file.NoSuchFileException in project neo4j by neo4j.

the class ZipUtils method unzipResource.

/**
 * Unzip a zip file located in the resource directly of provided class.
 * The zip file is expected to contain a single file with the same name as target.
 * The content is unpacked into target location.
 *
 * @param klass The class from which to get the zip file resource.
 * @param zipName Name of zip file.
 * @param targetFile Target file to which content will be unzipped, must align with content of zip file.
 * @throws IOException if something goes wrong.
 */
public static void unzipResource(Class<?> klass, String zipName, Path targetFile) throws IOException {
    URL resource = klass.getResource(zipName);
    if (resource == null) {
        throw new NoSuchFileException(zipName);
    }
    String sourceZip = resource.getFile();
    try (ZipFile zipFile = new ZipFile(sourceZip)) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        if (!entries.hasMoreElements()) {
            throw new IllegalStateException("Zip file '" + sourceZip + "' does not contain any elements.");
        }
        ZipEntry entry = entries.nextElement();
        if (!targetFile.getFileName().toString().equals(entry.getName())) {
            throw new IllegalStateException("Zip file '" + sourceZip + "' does not contain target file '" + targetFile.getFileName() + "'.");
        }
        Files.copy(zipFile.getInputStream(entry), targetFile);
    }
}
Also used : ZipFile(java.util.zip.ZipFile) ZipEntry(java.util.zip.ZipEntry) NoSuchFileException(java.nio.file.NoSuchFileException) URL(java.net.URL)

Example 70 with NoSuchFileException

use of java.nio.file.NoSuchFileException in project neo4j by neo4j.

the class FileUtils method tryForceDirectory.

public static void tryForceDirectory(Path directory) throws IOException {
    if (notExists(directory)) {
        throw new NoSuchFileException(format("The directory %s does not exist!", directory.toAbsolutePath()));
    } else if (!isDirectory(directory)) {
        throw new NotDirectoryException(format("The path %s must refer to a directory!", directory.toAbsolutePath()));
    }
    if (SystemUtils.IS_OS_WINDOWS) {
        // Windows doesn't allow us to open a FileChannel against a directory for reading, so we can't attempt to "fsync" there
        return;
    }
    // Attempts to fsync the directory, guaranting e.g. file creation/deletion/rename events are durable
    // See http://mail.openjdk.java.net/pipermail/nio-dev/2015-May/003140.html
    // See also https://github.com/apache/lucene-solr/commit/7bea628bf3961a10581833935e4c1b61ad708c5c
    FileChannel directoryChannel = FileChannel.open(directory, singleton(READ));
    directoryChannel.force(true);
}
Also used : NotDirectoryException(java.nio.file.NotDirectoryException) FileChannel(java.nio.channels.FileChannel) NoSuchFileException(java.nio.file.NoSuchFileException)

Aggregations

NoSuchFileException (java.nio.file.NoSuchFileException)262 IOException (java.io.IOException)107 Path (java.nio.file.Path)104 FileNotFoundException (java.io.FileNotFoundException)41 Test (org.junit.Test)35 InputStream (java.io.InputStream)31 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)25 File (java.io.File)22 NotDirectoryException (java.nio.file.NotDirectoryException)19 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)18 ArrayList (java.util.ArrayList)16 HashSet (java.util.HashSet)16 OutputStream (java.io.OutputStream)15 DirectoryNotEmptyException (java.nio.file.DirectoryNotEmptyException)15 FileChannel (java.nio.channels.FileChannel)14 AccessDeniedException (java.nio.file.AccessDeniedException)14 ByteBuffer (java.nio.ByteBuffer)13 HashMap (java.util.HashMap)13 Map (java.util.Map)12 SeekableByteChannel (java.nio.channels.SeekableByteChannel)11