java.nio.file.FileAlreadyExistsException Java Examples

The following examples show how to use java.nio.file.FileAlreadyExistsException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileSystemStorage.java    From pravega with Apache License 2.0 6 votes vote down vote up
private <T> T throwException(String segmentName, Exception e) throws StreamSegmentException {
    if (e instanceof NoSuchFileException || e instanceof FileNotFoundException) {
        throw new StreamSegmentNotExistsException(segmentName);
    }

    if (e instanceof FileAlreadyExistsException) {
        throw new StreamSegmentExistsException(segmentName);
    }

    if (e instanceof IndexOutOfBoundsException) {
        throw new IllegalArgumentException(e.getMessage());
    }

    if (e instanceof AccessControlException
            || e instanceof AccessDeniedException
            || e instanceof NonWritableChannelException) {
        throw new StreamSegmentSealedException(segmentName, e);
    }

    throw Exceptions.sneakyThrow(e);
}
 
Example #2
Source File: LocalFileSystem.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private boolean mkdirsInternal(File file) throws IOException {
	if (file.isDirectory()) {
			return true;
	}
	else if (file.exists() && !file.isDirectory()) {
		// Important: The 'exists()' check above must come before the 'isDirectory()' check to
		//            be safe when multiple parallel instances try to create the directory

		// exists and is not a directory -> is a regular file
		throw new FileAlreadyExistsException(file.getAbsolutePath());
	}
	else {
		File parent = file.getParentFile();
		return (parent == null || mkdirsInternal(parent)) && (file.mkdir() || file.isDirectory());
	}
}
 
Example #3
Source File: LocalFileSystem.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
public FSDataOutputStream create(final Path filePath, final WriteMode overwrite) throws IOException {
	checkNotNull(filePath, "filePath");

	if (exists(filePath) && overwrite == WriteMode.NO_OVERWRITE) {
		throw new FileAlreadyExistsException("File already exists: " + filePath);
	}

	final Path parent = filePath.getParent();
	if (parent != null && !mkdirs(parent)) {
		throw new IOException("Mkdirs failed to create " + parent);
	}

	final File file = pathToFile(filePath);
	return new LocalDataOutputStream(file);
}
 
Example #4
Source File: LocalFileSystem.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public FSDataOutputStream create(final Path filePath, final WriteMode overwrite) throws IOException {
	checkNotNull(filePath, "filePath");

	if (exists(filePath) && overwrite == WriteMode.NO_OVERWRITE) {
		throw new FileAlreadyExistsException("File already exists: " + filePath);
	}

	final Path parent = filePath.getParent();
	if (parent != null && !mkdirs(parent)) {
		throw new IOException("Mkdirs failed to create " + parent);
	}

	final File file = pathToFile(filePath);
	return new LocalDataOutputStream(file);
}
 
Example #5
Source File: LocalFileSystem.java    From flink with Apache License 2.0 6 votes vote down vote up
private boolean mkdirsInternal(File file) throws IOException {
	if (file.isDirectory()) {
			return true;
	}
	else if (file.exists() && !file.isDirectory()) {
		// Important: The 'exists()' check above must come before the 'isDirectory()' check to
		//            be safe when multiple parallel instances try to create the directory

		// exists and is not a directory -> is a regular file
		throw new FileAlreadyExistsException(file.getAbsolutePath());
	}
	else {
		File parent = file.getParentFile();
		return (parent == null || mkdirsInternal(parent)) && (file.mkdir() || file.isDirectory());
	}
}
 
Example #6
Source File: FSDirectory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public IndexOutput createTempOutput(String prefix, String suffix, IOContext context) throws IOException {
  ensureOpen();
  maybeDeletePendingFiles();
  while (true) {
    try {
      String name = getTempFileName(prefix, suffix, nextTempFileCounter.getAndIncrement());
      if (pendingDeletes.contains(name)) {
        continue;
      }
      return new FSIndexOutput(name,
                               StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
    } catch (FileAlreadyExistsException faee) {
      // Retry with next incremented name
    }
  }
}
 
Example #7
Source File: FileUtils.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Create directories needed based on configuration.
 *
 * @param configuration
 * @throws IOException
 */
public static void createDirectoriesOnWorker(SubProcessConfiguration configuration)
    throws IOException {

  try {

    Path path = Paths.get(configuration.getWorkerPath());

    if (!path.toFile().exists()) {
      Files.createDirectories(path);
      LOG.info(String.format("Created Folder %s ", path.toFile()));
    }
  } catch (FileAlreadyExistsException ex) {
    LOG.warn(
        String.format(
            " Tried to create folder %s which already existsed, this should not happen!",
            configuration.getWorkerPath()),
        ex);
  }
}
 
Example #8
Source File: ShutdownPid.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
protected void prepare() {
    LOG.debug("在本地写一个pid文件记录当前进程id,提供给stop脚本读取");
    try {
        PlainFileUtil.newFile(PID_FILE_PATH, JavaPIDUtil.getPID() + "");
    } catch (FileAlreadyExistsException e) {
        LOG.warn(e.getMessage() + " 执行删除旧pid文件,然后新建pid文件。");
        PlainFileUtil.deleteFile(PID_FILE_PATH);
        try {
            PlainFileUtil.newFile(PID_FILE_PATH, JavaPIDUtil.getPID() + "");
        } catch (FileAlreadyExistsException ignored) {
            LOG.error(ignored);
        }
    }
    PlainFileUtil.deleteOnExit(PID_FILE_PATH);
}
 
Example #9
Source File: Security.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures configured directory {@code path} exists.
 * @throws IOException if {@code path} exists, but is not a directory, not accessible, or broken symbolic link.
 */
static void ensureDirectoryExists(Path path) throws IOException {
    // this isn't atomic, but neither is createDirectories.
    if (Files.isDirectory(path)) {
        // verify access, following links (throws exception if something is wrong)
        // we only check READ as a sanity test
        path.getFileSystem().provider().checkAccess(path.toRealPath(), AccessMode.READ);
    } else {
        // doesn't exist, or not a directory
        try {
            Files.createDirectories(path);
        } catch (FileAlreadyExistsException e) {
            // convert optional specific exception so the context is clear
            IOException e2 = new NotDirectoryException(path.toString());
            e2.addSuppressed(e);
            throw e2;
        }
    }
}
 
Example #10
Source File: PasswordFileUpdaterWriterTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void passwordFileAlreadyExists() {
    final Config config = mock(Config.class);
    final Path pwdFile = mock(Path.class);
    final String path = "somepath";
    when(pwdFile.toString()).thenReturn(path);

    when(filesDelegate.exists(pwdFile)).thenReturn(true);

    final Throwable ex = catchThrowable(() -> writer.updateAndWrite(null, config, pwdFile));

    assertThat(ex).isExactlyInstanceOf(FileAlreadyExistsException.class);
    assertThat(ex.getMessage()).contains(path);

    verify(filesDelegate).exists(pwdFile);
}
 
Example #11
Source File: ZipUtils.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public static void unzip(Path zipFile, Path targetDir) throws IOException {
    try {
        if (!Files.exists(targetDir)) {
            Files.createDirectories(targetDir);
        }
    } catch (FileAlreadyExistsException fae) {
        throw new IOException("Could not create directory '" + targetDir + "' as a file already exists with the same name");
    }
    try (FileSystem zipfs = newFileSystem(zipFile)) {
        for (Path zipRoot : zipfs.getRootDirectories()) {
            copyFromZip(zipRoot, targetDir);
        }
    } catch (IOException | ZipError ioe) {
        // TODO: (at a later date) Get rid of the ZipError catching (and instead only catch IOException)
        //  since it's a JDK bug which threw the undeclared ZipError instead of an IOException.
        //  Java 9 fixes it https://bugs.openjdk.java.net/browse/JDK-8062754

        throw new IOException("Could not unzip " + zipFile + " to target dir " + targetDir, ioe);
    }
}
 
Example #12
Source File: SimpleFSLockFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
protected Lock obtainFSLock(FSDirectory dir, String lockName) throws IOException {
  Path lockDir = dir.getDirectory();
  
  // Ensure that lockDir exists and is a directory.
  // note: this will fail if lockDir is a symlink
  Files.createDirectories(lockDir);
  
  Path lockFile = lockDir.resolve(lockName);
  
  // create the file: this will fail if it already exists
  try {
    Files.createFile(lockFile);
  } catch (FileAlreadyExistsException | AccessDeniedException e) {
    // convert optional specific exception to our optional specific exception
    throw new LockObtainFailedException("Lock held elsewhere: " + lockFile, e);
  }
  
  // used as a best-effort check, to see if the underlying file has changed
  final FileTime creationTime = Files.readAttributes(lockFile, BasicFileAttributes.class).creationTime();
  
  return new SimpleFSLock(lockFile, creationTime);
}
 
Example #13
Source File: PasswordFile.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Create password file to be written with access permissions to read
 * and write by user only.
 * <p/>
 * @return Value of <code>true</code> if new file was created
 *         or <code>false</code> otherwise
 */
private boolean createFilePosix() {
    final String METHOD = "createFilePosix";
    boolean success = false;
    try {
        if (Files.notExists(file, new LinkOption[0])) {
            Files.createFile(file, PosixFilePermissions
                    .asFileAttribute(CREATE_FILE_PERMISSIONS));
            success = true;
        } else {
            Files.setPosixFilePermissions(file, CREATE_FILE_PERMISSIONS);
            LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
        }
    } catch (UnsupportedOperationException uoe) {
        LOGGER.log(Level.INFO, METHOD, "unsupported", file.toString());
    } catch (FileAlreadyExistsException faee) {
        LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
    } catch (IOException ioe) {
        LOGGER.log(Level.INFO, METHOD, "ioException", ioe);
    }
    return success;
}
 
Example #14
Source File: KeyStoreHandler.java    From robozonky with Apache License 2.0 6 votes vote down vote up
/**
 * Create brand new key store protected by a given password, and store it in a file.
 * 
 * @param keyStoreFile The file where the key store should be.
 * @param password     Password to protect the key store.
 * @return Freshly instantiated key store, in a newly created file.
 * @throws IOException       If file already exists or there is a problem writing the file.
 * @throws KeyStoreException If something's happened to the key store.
 */
public static KeyStoreHandler create(final File keyStoreFile, final char... password)
        throws IOException, KeyStoreException {
    if (keyStoreFile == null) {
        throw new FileNotFoundException(null);
    } else if (keyStoreFile.exists()) {
        throw new FileAlreadyExistsException(keyStoreFile.getAbsolutePath());
    }
    final KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
    // get user password and file input stream
    try {
        ks.load(null, password);
    } catch (final Exception ex) {
        throw new IllegalStateException(ex);
    }
    // store the newly created key store
    final SecretKeyFactory skf = getSecretKeyFactory();
    final KeyStoreHandler ksh = new KeyStoreHandler(ks, password, keyStoreFile, skf);
    LOGGER.debug("Creating keystore {}.", keyStoreFile);
    ksh.save();
    return ksh;
}
 
Example #15
Source File: AppTest.java    From public with Apache License 2.0 6 votes vote down vote up
@Test
void testAddFileAndDirectory() throws FileAlreadyExistsException, DirectoryNotWriteableException, NoSuchPathException, DirectoryNotReadableException, DirectoryAlreadyExistsException {
    sh.changeDirectory("/");
    sh.createDirectory("test");
    assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
            "f_a.txt",
            "f_b.txt",
            "d_a",
            "d_b",
            "test"
    ));

    sh.changeDirectory("test");
    sh.createFile("bingo.txt", 5);
    assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
        "bingo.txt"
    ));
}
 
Example #16
Source File: EmbeddedKdcResource.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void createWorkDirectory(final Path kdcDir) throws IOException
{
    try
    {
        Files.createDirectory(kdcDir);
    }
    catch (FileAlreadyExistsException e)
    {
        delete(kdcDir);
        Files.createDirectory(kdcDir);
    }
}
 
Example #17
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewOutputStreamExistingCreateNew() throws IOException {
    addDirectory("/foo");
    addFile("/foo/bar");

    OpenOption[] options = { StandardOpenOption.CREATE_NEW };
    FileAlreadyExistsException exception = assertThrows(FileAlreadyExistsException.class,
            () -> fileSystem.newOutputStream(createPath("/foo/bar"), options));
    assertEquals("/foo/bar", exception.getFile());

    // verify that the file system can be used after closing the stream
    assertDoesNotThrow(() -> fileSystem.checkAccess(createPath("/foo/bar")));
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/foo/bar")));
}
 
Example #18
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateDirectoryAlreadyExists() throws IOException {
    addDirectory("/foo/bar");

    FileAlreadyExistsException exception = assertThrows(FileAlreadyExistsException.class,
            () -> fileSystem.createDirectory(createPath("/foo/bar")));
    assertEquals("/foo/bar", exception.getFile());

    verify(getExceptionFactory(), never()).createCreateDirectoryException(anyString(), any(SftpException.class));
    assertTrue(Files.exists(getPath("/foo")));
    assertTrue(Files.exists(getPath("/foo/bar")));
}
 
Example #19
Source File: AppTest.java    From public with Apache License 2.0 5 votes vote down vote up
@Test
void testAddFileWithNegativeSize() throws FileAlreadyExistsException, DirectoryNotWriteableException, NoSuchPathException, DirectoryNotReadableException {
    sh.changeDirectory("/");
    sh.createFile("good.txt", 0);
    assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
            "f_a.txt",
            "f_b.txt",
            "good.txt",
            "d_a",
            "d_b"
    ));

    assertThrows(IllegalArgumentException.class, () -> sh.createFile("bad.txt", -17));
}
 
Example #20
Source File: MCRFileSystemProvider.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
    if (attrs.length > 0) {
        throw new UnsupportedOperationException("Setting 'attrs' atomically is unsupported.");
    }
    MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(dir);
    MCRDirectory rootDirectory;
    if (mcrPath.isAbsolute() && mcrPath.getNameCount() == 0) {
        rootDirectory = MCRDirectory.getDirectory(mcrPath.getOwner());
        if (rootDirectory != null) {
            throw new FileAlreadyExistsException(mcrPath.toString());
        }
        rootDirectory = new MCRDirectory(mcrPath.getOwner());
        return;
    }
    rootDirectory = getRootDirectory(mcrPath);
    MCRPath parentPath = mcrPath.getParent();
    MCRPath absolutePath = getAbsolutePathFromRootComponent(parentPath);
    MCRFilesystemNode childByPath = rootDirectory.getChildByPath(absolutePath.toString());
    if (childByPath == null) {
        throw new NoSuchFileException(parentPath.toString(), dir.getFileName().toString(),
            "parent directory does not exist");
    }
    if (childByPath instanceof MCRFile) {
        throw new NotDirectoryException(parentPath.toString());
    }
    MCRDirectory parentDir = (MCRDirectory) childByPath;
    String dirName = mcrPath.getFileName().toString();
    if (parentDir.getChild(dirName) != null) {
        throw new FileAlreadyExistsException(mcrPath.toString());
    }
    new MCRDirectory(dirName, parentDir);
}
 
Example #21
Source File: AppTest.java    From public with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void localSetup() throws FileAlreadyExistsException, DirectoryAlreadyExistsException {
    // The root node has no "name". It is represented by a single slash "/"
    // located at the root of any absolute path.
    FileSystemNode root = new FileSystemNode(null, new Permissions("rw"));

    root.addFile("f_a.txt", 10)
        .addFile("f_b.txt", 13);

    root.addDirectory("d_a")
            .addFile("f_c.txt", 10)
            .addFile("f_d.txt", 4)
            .addDirectory("d_c")
                .addFile("f_g.txt", 8)
                .addFile("f_h.txt", 12);

    root.addDirectory("d_b")
            .addFile("f_e.txt", 1)
            .addFile("f_f.txt", 3)
            .addDirectory("d_d")
                .addFile("f_i.txt", 9)
                .addFile("f_j.txt", 32)
                .addFile(".f_hidden_1.txt", 1)
                .addFile(".f_hidden_2.txt", 2)
                .addDirectory("d_e");

    sh = new SwengShell(root);
}
 
Example #22
Source File: SwengShell.java    From public with Apache License 2.0 5 votes vote down vote up
@Override
public void createFile(String filename, int sizeInBytes) throws FileAlreadyExistsException, DirectoryNotWriteableException {
    if (!isBasename(filename)) {
        throw new IllegalArgumentException();
    }

    if (isCurrentDirectoryWritable()) {
        currentFs.addFile(filename, sizeInBytes);
    } else {
        throw new DirectoryNotWriteableException(currentWorkingDirectory);
    }
}
 
Example #23
Source File: FileSystemNode.java    From public with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the DIRECTORY in which the FILE is located (so we can chain
 * file system manipulations)
 */
public FileSystemNode addFile(String filename, int sizeInBytes) throws FileAlreadyExistsException, IllegalArgumentException {
    if (fileExists(filename));
    if (sizeInBytes < 0) throw new IllegalArgumentException();

    FileSystemNode child = new File(filename, DEFAULT_FILE_PERMISSIONS, sizeInBytes);
    child.setParent(this);
    children.add(child);
    return this;
}
 
Example #24
Source File: AppTest.java    From public with Apache License 2.0 5 votes vote down vote up
@Test
void testAddFileWithNegativeSize() throws FileAlreadyExistsException, DirectoryNotWriteableException, NoSuchPathException, DirectoryNotReadableException {
    sh.changeDirectory("/");
    sh.createFile("good.txt", 0);
    assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
            "f_a.txt",
            "f_b.txt",
            "good.txt",
            "d_a",
            "d_b"
    ));

    assertThrows(IllegalArgumentException.class, () -> sh.createFile("bad.txt", -17));
}
 
Example #25
Source File: SecurityService.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns whether the given file may be uploaded.
 *
 * @return Whether the given file may be uploaded.
 */
public void checkUploadAllowed(Path file, boolean checkFileExists) throws IOException {
    if (!isInMusicFolder(file)) {
        throw new AccessDeniedException(file.toString(), null, "Specified location is not in writable music folder");
    }

    if (checkFileExists && Files.exists(file)) {
        throw new FileAlreadyExistsException(file.toString(), null, "File already exists");
    }
}
 
Example #26
Source File: AppTest.java    From public with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void localSetup() throws FileAlreadyExistsException, DirectoryAlreadyExistsException {
    // The root node has no "name". It is represented by a single slash "/"
    // located at the root of any absolute path.
    FileSystemNode root = new FileSystemNode(null, new Permissions("rw"));

    root.addFile("f_a.txt", 10)
        .addFile("f_b.txt", 13);

    root.addDirectory("d_a")
            .addFile("f_c.txt", 10)
            .addFile("f_d.txt", 4)
            .addDirectory("d_c")
                .addFile("f_g.txt", 8)
                .addFile("f_h.txt", 12);

    root.addDirectory("d_b")
            .addFile("f_e.txt", 1)
            .addFile("f_f.txt", 3)
            .addDirectory("d_d")
                .addFile("f_i.txt", 9)
                .addFile("f_j.txt", 32)
                .addFile(".f_hidden_1.txt", 1)
                .addFile(".f_hidden_2.txt", 2)
                .addDirectory("d_e");

    sh = new SwengShell(root);
}
 
Example #27
Source File: GradedAppTest.java    From public with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void localSetup() throws FileAlreadyExistsException, DirectoryAlreadyExistsException {
    // The root node has no "name". It is represented by a single slash "/"
    // located at the root of any absolute path.
    FileSystemNode root = new FileSystemNode(null, new Permissions("rw"));

    root.addFile("f_a.txt", 10)
            .addFile("f_b.txt", 13);

    root.addDirectory("d_a")
            .addFile("f_c.txt", 10)
            .addFile("f_d.txt", 4)
            .addDirectory("d_c")
            .addFile("f_g.txt", 8)
            .addFile("f_h.txt", 12);

    root.addDirectory("d_b")
            .addFile("f_e.txt", 1)
            .addFile("f_f.txt", 3)
            .addDirectory("d_d")
            .addFile("f_i.txt", 9)
            .addFile("f_j.txt", 32)
            .addFile(".f_hidden_1.txt", 1)
            .addFile(".f_hidden_2.txt", 2)
            .addDirectory("d_e");

    sh = new SwengShell(root);
}
 
Example #28
Source File: SwengShell.java    From public with Apache License 2.0 5 votes vote down vote up
@Override
public void createFile(String filename, int sizeInBytes) throws FileAlreadyExistsException, DirectoryNotWriteableException {
    if (!isBasename(filename)) {
        throw new IllegalArgumentException();
    }

    if (isCurrentDirectoryWritable()) {
        currentFs.addFile(filename, sizeInBytes);
    } else {
        throw new DirectoryNotWriteableException(currentWorkingDirectory);
    }
}
 
Example #29
Source File: FileSystemNode.java    From public with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the DIRECTORY in which the FILE is located (so we can chain
 * file system manipulations)
 */
public FileSystemNode addFile(String filename, int sizeInBytes) throws FileAlreadyExistsException, IllegalArgumentException {
    // Bug 4:
    // bug => if (fileExists(filename));
    // fix => if (fileExists(filename)) throw new FileAlreadyExistsException(filename);
    if (fileExists(filename)) throw new FileAlreadyExistsException(filename);
    if (sizeInBytes < 0) throw new IllegalArgumentException();

    FileSystemNode child = new File(filename, DEFAULT_FILE_PERMISSIONS, sizeInBytes);
    child.setParent(this);
    children.add(child);
    return this;
}
 
Example #30
Source File: FileUtils.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
/**
 * ディレクトリがない場合は作成します。
 *
 * @param location
 */
public static void createDirectory(Path location) {
    try {
        Files.createDirectory(location);
    } catch (FileAlreadyExistsException ignore) {
        // ignore
    } catch (IOException e) {
        throw new IllegalArgumentException("could not create directory. " + location.toString(), e);
    }
}