Search in sources :

Example 61 with FileAlreadyExistsException

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

the class LoaderTest method shouldGiveAClearErrorIfTheDestinationAlreadyExists.

@Test
public void shouldGiveAClearErrorIfTheDestinationAlreadyExists() throws IOException, IncorrectFormat {
    Path archive = testDirectory.file("the-archive.dump").toPath();
    Path destination = testDirectory.directory("the-destination").toPath();
    try {
        new Loader().load(archive, destination);
        fail("Expected an exception");
    } catch (FileAlreadyExistsException e) {
        assertEquals(destination.toString(), e.getMessage());
    }
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) Test(org.junit.Test)

Example 62 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project zaproxy by zaproxy.

the class ExtensionAutoUpdate method installLocalAddOn.

private void installLocalAddOn(AddOn ao) {
    File addOnFile;
    try {
        addOnFile = copyAddOnFileToLocalPluginFolder(ao);
    } catch (FileAlreadyExistsException e) {
        showWarningMessageAddOnFileAlreadyExists(e.getFile(), e.getOtherFile());
        logger.warn("Unable to copy add-on, a file with the same name already exists.", e);
        return;
    } catch (IOException e) {
        showWarningMessageUnableToCopyAddOnFile();
        logger.warn("Unable to copy add-on to local plugin folder.", e);
        return;
    }
    ao.setFile(addOnFile);
    install(ao);
}
Also used : FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) IOException(java.io.IOException) File(java.io.File)

Example 63 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project beam by apache.

the class GcsUtil method createBucket.

@VisibleForTesting
void createBucket(String projectId, Bucket bucket, BackOff backoff, Sleeper sleeper) throws IOException {
    Storage.Buckets.Insert insertBucket = storageClient.buckets().insert(projectId, bucket);
    insertBucket.setPredefinedAcl("projectPrivate");
    insertBucket.setPredefinedDefaultObjectAcl("projectPrivate");
    try {
        ResilientOperation.retry(ResilientOperation.getGoogleRequestCallable(insertBucket), backoff, new RetryDeterminer<IOException>() {

            @Override
            public boolean shouldRetry(IOException e) {
                if (errorExtractor.itemAlreadyExists(e) || errorExtractor.accessDenied(e)) {
                    return false;
                }
                return RetryDeterminer.SOCKET_ERRORS.shouldRetry(e);
            }
        }, IOException.class, sleeper);
        return;
    } catch (GoogleJsonResponseException e) {
        if (errorExtractor.accessDenied(e)) {
            throw new AccessDeniedException(bucket.getName(), null, e.getMessage());
        }
        if (errorExtractor.itemAlreadyExists(e)) {
            throw new FileAlreadyExistsException(bucket.getName(), null, e.getMessage());
        }
        throw e;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException(String.format("Error while attempting to create bucket gs://%s for rproject %s", bucket.getName(), projectId), e);
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) AccessDeniedException(java.nio.file.AccessDeniedException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) IOException(java.io.IOException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 64 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project lucene-solr by apache.

the class HardlinkCopyDirectoryWrapper method copyFrom.

@Override
public void copyFrom(Directory from, String srcFile, String destFile, IOContext context) throws IOException {
    final Directory fromUnwrapped = FilterDirectory.unwrap(from);
    final Directory toUnwrapped = FilterDirectory.unwrap(this);
    // try to unwrap to FSDirectory - we might be able to just create hard-links of these files and save copying
    // the entire file.
    Exception suppressedException = null;
    boolean tryCopy = true;
    if (fromUnwrapped instanceof FSDirectory && toUnwrapped instanceof FSDirectory) {
        final Path fromPath = ((FSDirectory) fromUnwrapped).getDirectory();
        final Path toPath = ((FSDirectory) toUnwrapped).getDirectory();
        if (Files.isReadable(fromPath.resolve(srcFile)) && Files.isWritable(toPath)) {
            // only try hardlinks if we have permission to access the files
            // if not super.copyFrom() will give us the right exceptions
            suppressedException = AccessController.doPrivileged((PrivilegedAction<Exception>) () -> {
                try {
                    Files.createLink(toPath.resolve(destFile), fromPath.resolve(srcFile));
                } catch (FileNotFoundException | NoSuchFileException | FileAlreadyExistsException ex) {
                    return ex;
                } catch (IOException | UnsupportedOperationException | SecurityException ex) {
                    return ex;
                }
                return null;
            });
            tryCopy = suppressedException != null;
        }
    }
    if (tryCopy) {
        try {
            super.copyFrom(from, srcFile, destFile, context);
        } catch (Exception ex) {
            if (suppressedException != null) {
                ex.addSuppressed(suppressedException);
            }
            throw ex;
        }
    }
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileNotFoundException(java.io.FileNotFoundException) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileNotFoundException(java.io.FileNotFoundException) PrivilegedAction(java.security.PrivilegedAction)

Example 65 with FileAlreadyExistsException

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

the class FileHandler method openFiles.

/**
     * Open the set of output files, based on the configured
     * instance variables.
     */
private void openFiles() throws IOException {
    LogManager manager = LogManager.getLogManager();
    manager.checkPermission();
    if (count < 1) {
        throw new IllegalArgumentException("file count = " + count);
    }
    if (limit < 0) {
        limit = 0;
    }
    // We register our own ErrorManager during initialization
    // so we can record exceptions.
    InitializationErrorManager em = new InitializationErrorManager();
    setErrorManager(em);
    // Create a lock file.  This grants us exclusive access
    // to our set of output files, as long as we are alive.
    int unique = -1;
    for (; ; ) {
        unique++;
        if (unique > MAX_LOCKS) {
            throw new IOException("Couldn't get lock for " + pattern);
        }
        // Generate a lock file name from the "unique" int.
        lockFileName = generate(pattern, 0, unique).toString() + ".lck";
        // if we ourself already have the file locked.
        synchronized (locks) {
            if (locks.contains(lockFileName)) {
                // object.  Try again.
                continue;
            }
            final Path lockFilePath = Paths.get(lockFileName);
            FileChannel channel = null;
            int retries = -1;
            boolean fileCreated = false;
            while (channel == null && retries++ < 1) {
                try {
                    channel = FileChannel.open(lockFilePath, CREATE_NEW, WRITE);
                    fileCreated = true;
                } catch (FileAlreadyExistsException ix) {
                    // but not too frequently.
                    if (Files.isRegularFile(lockFilePath, LinkOption.NOFOLLOW_LINKS) && isParentWritable(lockFilePath)) {
                        try {
                            channel = FileChannel.open(lockFilePath, WRITE, APPEND);
                        } catch (NoSuchFileException x) {
                            // the sequence.
                            continue;
                        } catch (IOException x) {
                            // try the next name in the sequence
                            break;
                        }
                    } else {
                        // break and try the next name in the sequence.
                        break;
                    }
                }
            }
            // try the next name;
            if (channel == null)
                continue;
            lockFileChannel = channel;
            boolean available;
            try {
                available = lockFileChannel.tryLock() != null;
            // We got the lock OK.
            // At this point we could call File.deleteOnExit().
            // However, this could have undesirable side effects
            // as indicated by JDK-4872014. So we will instead
            // rely on the fact that close() will remove the lock
            // file and that whoever is creating FileHandlers should
            // be responsible for closing them.
            } catch (IOException ix) {
                // We got an IOException while trying to get the lock.
                // This normally indicates that locking is not supported
                // on the target directory.  We have to proceed without
                // getting a lock.   Drop through, but only if we did
                // create the file...
                available = fileCreated;
            } catch (OverlappingFileLockException x) {
                // someone already locked this file in this VM, through
                // some other channel - that is - using something else
                // than new FileHandler(...);
                // continue searching for an available lock.
                available = false;
            }
            if (available) {
                // We got the lock.  Remember it.
                locks.add(lockFileName);
                break;
            }
            // We failed to get the lock.  Try next file.
            lockFileChannel.close();
        }
    }
    files = new File[count];
    for (int i = 0; i < count; i++) {
        files[i] = generate(pattern, i, unique);
    }
    // Create the initial log file.
    if (append) {
        open(files[0], true);
    } else {
        rotate();
    }
    // Did we detect any exceptions during initialization?
    Exception ex = em.lastException;
    if (ex != null) {
        if (ex instanceof IOException) {
            throw (IOException) ex;
        } else if (ex instanceof SecurityException) {
            throw (SecurityException) ex;
        } else {
            throw new IOException("Exception: " + ex);
        }
    }
    // Install the normal default ErrorManager.
    setErrorManager(new ErrorManager());
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileChannel(java.nio.channels.FileChannel) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException)

Aggregations

FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)104 Path (java.nio.file.Path)49 IOException (java.io.IOException)44 File (java.io.File)24 NoSuchFileException (java.nio.file.NoSuchFileException)22 Test (org.junit.Test)15 FileNotFoundException (java.io.FileNotFoundException)10 FileSystemException (java.nio.file.FileSystemException)9 AccessDeniedException (java.nio.file.AccessDeniedException)8 DirectoryNotEmptyException (java.nio.file.DirectoryNotEmptyException)8 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)8 NotDirectoryException (java.nio.file.NotDirectoryException)7 AtomicMoveNotSupportedException (java.nio.file.AtomicMoveNotSupportedException)5 CopyOption (java.nio.file.CopyOption)5 FileSystem (java.nio.file.FileSystem)5 FileVisitResult (java.nio.file.FileVisitResult)5 MCRPath (org.mycore.datamodel.niofs.MCRPath)5 FileOutputStream (java.io.FileOutputStream)4 InputStream (java.io.InputStream)4 FileSystemLoopException (java.nio.file.FileSystemLoopException)4