Search in sources :

Example 36 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)

Example 37 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 38 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)

Aggregations

FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)38 IOException (java.io.IOException)15 Path (java.nio.file.Path)14 NoSuchFileException (java.nio.file.NoSuchFileException)9 Test (org.junit.Test)9 File (java.io.File)8 FileNotFoundException (java.io.FileNotFoundException)5 AccessDeniedException (java.nio.file.AccessDeniedException)5 FileSystem (java.nio.file.FileSystem)4 FileSystemException (java.nio.file.FileSystemException)4 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)4 VertxException (io.vertx.core.VertxException)3 EOFException (java.io.EOFException)3 InputStream (java.io.InputStream)3 AtomicMoveNotSupportedException (java.nio.file.AtomicMoveNotSupportedException)3 DirectoryNotEmptyException (java.nio.file.DirectoryNotEmptyException)3 FileSystemLoopException (java.nio.file.FileSystemLoopException)3 NotDirectoryException (java.nio.file.NotDirectoryException)3 ZipFile (java.util.zip.ZipFile)3 StorageException (com.google.cloud.storage.StorageException)2