Search in sources :

Example 26 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project vert.x by eclipse.

the class FileResolver method unpackFromJarURL.

private synchronized File unpackFromJarURL(URL url, String fileName, ClassLoader cl) {
    ZipFile zip = null;
    try {
        String path = url.getPath();
        int idx1 = path.lastIndexOf(".jar!");
        if (idx1 == -1) {
            idx1 = path.lastIndexOf(".zip!");
        }
        int idx2 = path.lastIndexOf(".jar!", idx1 - 1);
        if (idx2 == -1) {
            idx2 = path.lastIndexOf(".zip!", idx1 - 1);
        }
        if (idx2 == -1) {
            File file = new File(URLDecoder.decode(path.substring(5, idx1 + 4), "UTF-8"));
            zip = new ZipFile(file);
        } else {
            String s = path.substring(idx2 + 6, idx1 + 4);
            File file = resolveFile(s);
            zip = new ZipFile(file);
        }
        String inJarPath = path.substring(idx1 + 6);
        String[] parts = JAR_URL_SEP_PATTERN.split(inJarPath);
        StringBuilder prefixBuilder = new StringBuilder();
        for (int i = 0; i < parts.length - 1; i++) {
            prefixBuilder.append(parts[i]).append("/");
        }
        String prefix = prefixBuilder.toString();
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String name = entry.getName();
            if (name.startsWith(prefix.isEmpty() ? fileName : prefix + fileName)) {
                File file = new File(cacheDir, prefix.isEmpty() ? name : name.substring(prefix.length()));
                if (name.endsWith("/")) {
                    // Directory
                    file.mkdirs();
                } else {
                    file.getParentFile().mkdirs();
                    try (InputStream is = zip.getInputStream(entry)) {
                        if (ENABLE_CACHING) {
                            Files.copy(is, file.toPath());
                        } else {
                            Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
                        }
                    } catch (FileAlreadyExistsException ignore) {
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new VertxException(e);
    } finally {
        closeQuietly(zip);
    }
    return new File(cacheDir, fileName);
}
Also used : FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) ZipFile(java.util.zip.ZipFile) InputStream(java.io.InputStream) VertxException(io.vertx.core.VertxException) ZipEntry(java.util.zip.ZipEntry) IOException(java.io.IOException) File(java.io.File) ZipFile(java.util.zip.ZipFile)

Example 27 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project vert.x by eclipse.

the class FileSystemImpl method copyInternal.

private BlockingAction<Void> copyInternal(String from, String to, boolean recursive, Handler<AsyncResult<Void>> handler) {
    Objects.requireNonNull(from);
    Objects.requireNonNull(to);
    return new BlockingAction<Void>(handler) {

        public Void perform() {
            try {
                Path source = vertx.resolveFile(from).toPath();
                Path target = vertx.resolveFile(to).toPath();
                if (recursive) {
                    Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {

                        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                            Path targetDir = target.resolve(source.relativize(dir));
                            try {
                                Files.copy(dir, targetDir);
                            } catch (FileAlreadyExistsException e) {
                                if (!Files.isDirectory(targetDir)) {
                                    throw e;
                                }
                            }
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                            Files.copy(file, target.resolve(source.relativize(file)));
                            return FileVisitResult.CONTINUE;
                        }
                    });
                } else {
                    Files.copy(source, target);
                }
            } catch (IOException e) {
                throw new FileSystemException(e);
            }
            return null;
        }
    };
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileSystemException(io.vertx.core.file.FileSystemException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 28 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project elasticsearch by elastic.

the class ExceptionSerializationTests method testFileSystemExceptions.

public void testFileSystemExceptions() throws IOException {
    for (FileSystemException ex : Arrays.asList(new FileSystemException("a", "b", "c"), new NoSuchFileException("a", "b", "c"), new NotDirectoryException("a"), new DirectoryNotEmptyException("a"), new AtomicMoveNotSupportedException("a", "b", "c"), new FileAlreadyExistsException("a", "b", "c"), new AccessDeniedException("a", "b", "c"), new FileSystemLoopException("a"))) {
        FileSystemException serialize = serialize(ex);
        assertEquals(serialize.getClass(), ex.getClass());
        assertEquals("a", serialize.getFile());
        if (serialize.getClass() == NotDirectoryException.class || serialize.getClass() == FileSystemLoopException.class || serialize.getClass() == DirectoryNotEmptyException.class) {
            assertNull(serialize.getOtherFile());
            assertNull(serialize.getReason());
        } else {
            assertEquals(serialize.getClass().toString(), "b", serialize.getOtherFile());
            assertEquals(serialize.getClass().toString(), "c", serialize.getReason());
        }
    }
}
Also used : FileSystemException(java.nio.file.FileSystemException) NotDirectoryException(java.nio.file.NotDirectoryException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) AccessDeniedException(java.nio.file.AccessDeniedException) NoSuchFileException(java.nio.file.NoSuchFileException) DirectoryNotEmptyException(java.nio.file.DirectoryNotEmptyException) AtomicMoveNotSupportedException(java.nio.file.AtomicMoveNotSupportedException) FileSystemLoopException(java.nio.file.FileSystemLoopException)

Example 29 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project elasticsearch by elastic.

the class InstallPluginCommandTests method testConfigConflict.

public void testConfigConflict() throws Exception {
    Tuple<Path, Environment> env = createEnv(fs, temp);
    Path pluginDir = createPluginDir(temp);
    Path configDir = pluginDir.resolve("config");
    Files.createDirectory(configDir);
    Files.createFile(configDir.resolve("myconfig.yml"));
    String pluginZip = createPlugin("elasticsearch.yml", pluginDir);
    FileAlreadyExistsException e = expectThrows(FileAlreadyExistsException.class, () -> installPlugin(pluginZip, env.v1()));
    assertTrue(e.getMessage(), e.getMessage().contains(env.v2().configFile().resolve("elasticsearch.yml").toString()));
    assertInstallCleaned(env.v2());
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) Environment(org.elasticsearch.env.Environment) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 30 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project buck by facebook.

the class ProjectWorkspace method setUp.

/**
   * This will copy the template directory, renaming files named {@code foo.fixture} to {@code foo}
   * in the process. Files whose names end in {@code .expected} will not be copied.
   */
@SuppressWarnings("PMD.EmptyCatchBlock")
public ProjectWorkspace setUp() throws IOException {
    MoreFiles.copyRecursively(templatePath, destPath, BUILD_FILE_RENAME);
    // Stamp the buck-out directory if it exists and isn't stamped already
    try (OutputStream outputStream = new BufferedOutputStream(Channels.newOutputStream(Files.newByteChannel(destPath.resolve(BuckConstant.getBuckOutputPath().resolve(".currentversion")), ImmutableSet.<OpenOption>of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))))) {
        outputStream.write(BuckVersion.getVersion().getBytes(Charsets.UTF_8));
    } catch (FileAlreadyExistsException | NoSuchFileException e) {
    // If the current version file already exists we don't need to create it
    // If buck-out doesn't exist we don't need to stamp it
    }
    if (Platform.detect() == Platform.WINDOWS) {
        // Hack for symlinks on Windows.
        SimpleFileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                // On NTFS length of path must be greater than 0 and less than 4096.
                if (attrs.size() > 0 && attrs.size() <= 4096) {
                    String linkTo = new String(Files.readAllBytes(path), UTF_8);
                    Path linkToFile;
                    try {
                        linkToFile = templatePath.resolve(linkTo);
                    } catch (InvalidPathException e) {
                        // link.
                        return FileVisitResult.CONTINUE;
                    }
                    if (Files.isRegularFile(linkToFile)) {
                        Files.copy(linkToFile, path, StandardCopyOption.REPLACE_EXISTING);
                    } else if (Files.isDirectory(linkToFile)) {
                        Files.delete(path);
                        MoreFiles.copyRecursively(linkToFile, path);
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        };
        Files.walkFileTree(destPath, copyDirVisitor);
    }
    if (!Files.exists(getPath(".buckconfig.local"))) {
        manageLocalConfigs = true;
        // Disable the directory cache by default.  Tests that want to enable it can call
        // `enableDirCache` on this object.  Only do this if a .buckconfig.local file does not already
        // exist, however (we assume the test knows what it is doing at that point).
        addBuckConfigLocalOption("cache", "mode", "");
        // Limit the number of threads by default to prevent multiple integration tests running at the
        // same time from creating a quadratic number of threads. Tests can disable this using
        // `disableThreadLimitOverride`.
        addBuckConfigLocalOption("build", "threads", "2");
    }
    isSetUp = true;
    return this;
}
Also used : Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) NoSuchFileException(java.nio.file.NoSuchFileException) BufferedOutputStream(java.io.BufferedOutputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) InvalidPathException(java.nio.file.InvalidPathException)

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