Example usage for java.nio.file StandardCopyOption ATOMIC_MOVE

List of usage examples for java.nio.file StandardCopyOption ATOMIC_MOVE

Introduction

In this page you can find the example usage for java.nio.file StandardCopyOption ATOMIC_MOVE.

Prototype

StandardCopyOption ATOMIC_MOVE

To view the source code for java.nio.file StandardCopyOption ATOMIC_MOVE.

Click Source Link

Document

Move the file as an atomic file system operation.

Usage

From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImplTestUtils.java

@Override
public void changeStoredGenerationStamp(ExtendedBlock block, long newGenStamp) throws IOException {
    File blockFile = dataset.getBlockFile(block.getBlockPoolId(), block.getBlockId());
    File metaFile = FsDatasetUtil.findMetaFile(blockFile);
    File newMetaFile = new File(DatanodeUtil.getMetaName(blockFile.getAbsolutePath(), newGenStamp));
    Files.move(metaFile.toPath(), newMetaFile.toPath(), StandardCopyOption.ATOMIC_MOVE);
}

From source file:org.apache.storm.daemon.supervisor.SyncSupervisorEvent.java

/**
 * Downloading to permanent location is atomic
 * // w  w  w.  j a  v a  2  s. com
 * @param conf
 * @param stormId
 * @param masterCodeDir
 * @param localizer
 * @throws Exception
 */
private void downloadDistributeStormCode(Map conf, String stormId, String masterCodeDir, Localizer localizer)
        throws Exception {

    String tmproot = ConfigUtils.supervisorTmpDir(conf) + Utils.FILE_PATH_SEPARATOR + Utils.uuid();
    String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    ClientBlobStore blobStore = Utils.getClientBlobStoreForSupervisor(conf);
    FileUtils.forceMkdir(new File(tmproot));
    if (Utils.isOnWindows()) {
        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
            throw new RuntimeException("ERROR: Windows doesn't implement setting the correct permissions");
        }
    } else {
        Utils.restrictPermissions(tmproot);
    }
    String stormJarKey = ConfigUtils.masterStormJarKey(stormId);
    String stormCodeKey = ConfigUtils.masterStormCodeKey(stormId);
    String stormConfKey = ConfigUtils.masterStormConfKey(stormId);
    String jarPath = ConfigUtils.supervisorStormJarPath(tmproot);
    String codePath = ConfigUtils.supervisorStormCodePath(tmproot);
    String confPath = ConfigUtils.supervisorStormConfPath(tmproot);
    Utils.downloadResourcesAsSupervisor(stormJarKey, jarPath, blobStore);
    Utils.downloadResourcesAsSupervisor(stormCodeKey, codePath, blobStore);
    Utils.downloadResourcesAsSupervisor(stormConfKey, confPath, blobStore);
    blobStore.shutdown();
    Utils.extractDirFromJar(jarPath, ConfigUtils.RESOURCES_SUBDIR, tmproot);
    downloadBlobsForTopology(conf, confPath, localizer, tmproot);
    if (didDownloadBlobsForTopologySucceed(confPath, tmproot)) {
        LOG.info("Successfully downloaded blob resources for storm-id {}", stormId);
        if (Utils.isOnWindows()) {
            // Files/move with non-empty directory doesn't work well on Windows
            FileUtils.moveDirectory(new File(tmproot), new File(stormroot));
        } else {
            FileUtils.forceMkdir(new File(stormroot));
            Files.move(new File(tmproot).toPath(), new File(stormroot).toPath(),
                    StandardCopyOption.ATOMIC_MOVE);
        }
    } else {
        LOG.info("Failed to download blob resources for storm-id ", stormId);
        Utils.forceDelete(tmproot);
    }
}

From source file:org.perfcake.util.Utils.java

/**
 * Atomically writes given content to a file.
 *
 * @param path/*from   www.  jav a 2  s.c  om*/
 *       The target file path.
 * @param content
 *       The content to be written.
 * @throws org.perfcake.PerfCakeException
 *       In the case of file operations failure.
 */
public static void writeFileContent(final Path path, final String content) throws PerfCakeException {
    try {
        final Path workFile = Paths.get(path.toString() + ".work");
        Files.write(workFile, content.getBytes(Utils.getDefaultEncoding()));
        Files.move(workFile, path, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
    } catch (final IOException e) {
        final String message = String.format("Could not write content to the file %s:", path.toString());
        throw new PerfCakeException(message, e);
    }
}

From source file:org.artifactory.repo.db.importexport.DbRepoImportHandler.java

private void moveFileToExternalFileStore(File sourceFile, String expectedSha1) throws IOException {
    // If exclude content and file exists use it for the external filestore if it exists
    StorageProperties storageProperties = StorageContextHelper.get().beanForType(StorageProperties.class);
    String extFilestoreDir = storageProperties.getBinaryProviderExternalDir();
    if (StringUtils.isNotBlank(extFilestoreDir)) {
        Path filePath = Paths.get(extFilestoreDir, expectedSha1.substring(0, 2), expectedSha1);
        if (!Files.exists(filePath)) {
            Files.move(sourceFile.toPath(), filePath, StandardCopyOption.ATOMIC_MOVE);
        }/*from   www  . j av a2  s .com*/
    }
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemImpl.java

void move(CryptoPath cleartextSource, CryptoPath cleartextTarget, CopyOption... options) throws IOException {
    if (cleartextSource.equals(cleartextTarget)) {
        return;//from ww w  .  java2  s.  co m
    }
    Path ciphertextSourceFile = cryptoPathMapper.getCiphertextFilePath(cleartextSource,
            CiphertextFileType.FILE);
    Path ciphertextSourceDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextSource,
            CiphertextFileType.DIRECTORY);
    if (Files.exists(ciphertextSourceFile)) {
        // FILE:
        Path ciphertextTargetFile = cryptoPathMapper.getCiphertextFilePath(cleartextTarget,
                CiphertextFileType.FILE);
        Files.move(ciphertextSourceFile, ciphertextTargetFile, options);
    } else if (Files.exists(ciphertextSourceDirFile)) {
        // DIRECTORY:
        Path ciphertextTargetDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextTarget,
                CiphertextFileType.DIRECTORY);
        if (!ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING)) {
            // try to move, don't replace:
            Files.move(ciphertextSourceDirFile, ciphertextTargetDirFile, options);
        } else if (ArrayUtils.contains(options, StandardCopyOption.ATOMIC_MOVE)) {
            // replace atomically (impossible):
            assert ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING);
            throw new AtomicMoveNotSupportedException(cleartextSource.toString(), cleartextTarget.toString(),
                    "Replacing directories during move requires non-atomic status checks.");
        } else {
            // move and replace (if dir is empty):
            assert ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING);
            assert !ArrayUtils.contains(options, StandardCopyOption.ATOMIC_MOVE);
            if (Files.exists(ciphertextTargetDirFile)) {
                Path ciphertextTargetDir = cryptoPathMapper.getCiphertextDirPath(cleartextTarget);
                try (DirectoryStream<Path> ds = Files.newDirectoryStream(ciphertextTargetDir)) {
                    if (ds.iterator().hasNext()) {
                        throw new DirectoryNotEmptyException(cleartextTarget.toString());
                    }
                }
                Files.delete(ciphertextTargetDir);
            }
            Files.move(ciphertextSourceDirFile, ciphertextTargetDirFile, options);
        }
        dirIdProvider.move(ciphertextSourceDirFile, ciphertextTargetDirFile);
    } else {
        throw new NoSuchFileException(cleartextSource.toString());
    }
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * modified version of commons-io FileUtils.moveDirectory(); adapted to Java 7 NIO<br>
 * since renameTo() might not work in first place, retry it up to 5 times.<br>
 * (better wait 5 sec for success, than always copying a 50gig directory ;)<br>
 * <b>And NO, we're NOT doing a copy+delete as fallback!</b>
 * /*from  w w w.ja  v  a2 s.c  o  m*/
 * @param srcDir
 *          the directory to be moved
 * @param destDir
 *          the destination directory
 * @return true, if successful
 * @throws IOException
 *           if an IO error occurs moving the file
 */
public static boolean moveDirectorySafe(Path srcDir, Path destDir) throws IOException {
    // rip-off from
    // http://svn.apache.org/repos/asf/commons/proper/io/trunk/src/main/java/org/apache/commons/io/FileUtils.java
    if (srcDir == null) {
        throw new NullPointerException("Source must not be null");
    }
    if (destDir == null) {
        throw new NullPointerException("Destination must not be null");
    }
    if (!srcDir.toAbsolutePath().toString().equals(destDir.toAbsolutePath().toString())) {
        LOGGER.debug("try to move folder " + srcDir + " to " + destDir);
        if (!Files.isDirectory(srcDir)) {
            throw new FileNotFoundException("Source '" + srcDir + "' does not exist, or is not a directory");
        }
        if (Files.exists(destDir) && !Files.isSameFile(destDir, srcDir)) {
            // extra check for Windows/OSX, where the File.equals is case insensitive
            // so we know now, that the Dir is the same, but the absolute name does not match
            throw new FileExistsException("Destination '" + destDir + "' already exists");
        }
        if (!Files.exists(destDir.getParent())) {
            // create parent folder structure, else renameTo does not work
            try {
                Files.createDirectories(destDir.getParent());
            } catch (Exception e) {
                LOGGER.error("could not create directory structure " + destDir.getParent());
                // but we try a move anyway...
            }
        }

        // rename folder; try 5 times and wait a sec
        boolean rename = false;
        for (int i = 0; i < 5; i++) {
            try {
                // need atomic fs move for changing cASE
                Files.move(srcDir, destDir, StandardCopyOption.ATOMIC_MOVE);
                rename = true;// no exception
            } catch (AtomicMoveNotSupportedException a) {
                // if it fails (b/c not on same file system) use that
                try {
                    Files.move(srcDir, destDir, StandardCopyOption.REPLACE_EXISTING);
                    rename = true; // no exception
                } catch (IOException e) {
                }
            } catch (IOException e) {
            }
            if (rename) {
                break; // ok it worked, step out
            }
            try {
                LOGGER.debug("rename did not work - sleep a while and try again...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                LOGGER.warn("I'm so excited - could not sleep");
            }
        }

        // ok, we tried it 5 times - it still seems to be locked somehow. Continue
        // with copying as fallback
        // NOOO - we don't like to have some files copied and some not.

        if (!rename) {
            LOGGER.error("Failed to rename directory '" + srcDir + " to " + destDir);
            LOGGER.error("Movie renaming aborted.");
            MessageManager.instance
                    .pushMessage(new Message(MessageLevel.ERROR, srcDir, "message.renamer.failedrename"));
            return false;
        } else {
            LOGGER.info("Successfully moved folder " + srcDir + " to " + destDir);
            return true;
        }
    }
    return true; // dir are equal
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

private static void atomicMoveIfPossible(Path source, Path target) throws IOException {
    try {// w ww  . j  a va2s .c  o m
        Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
    } catch (AtomicMoveNotSupportedException e) {
        Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
    }
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * modified version of commons-io FileUtils.moveFile(); adapted to Java 7 NIO<br>
 * since renameTo() might not work in first place, retry it up to 5 times.<br>
 * (better wait 5 sec for success, than always copying a 50gig directory ;)<br>
 * <b>And NO, we're NOT doing a copy+delete as fallback!</b>
 * //from ww w.j a v a  2s .c  o m
 * @param srcFile
 *          the file to be moved
 * @param destFile
 *          the destination file
 * @throws NullPointerException
 *           if source or destination is {@code null}
 * @throws FileExistsException
 *           if the destination file exists
 * @throws IOException
 *           if source or destination is invalid
 * @throws IOException
 *           if an IO error occurs moving the file
 */
public static boolean moveFileSafe(final Path srcFile, final Path destFile) throws IOException {
    if (srcFile == null) {
        throw new NullPointerException("Source must not be null");
    }
    if (destFile == null) {
        throw new NullPointerException("Destination must not be null");
    }
    // if (!srcFile.equals(destFile)) {
    if (!srcFile.toAbsolutePath().toString().equals(destFile.toAbsolutePath().toString())) {
        LOGGER.debug("try to move file " + srcFile + " to " + destFile);
        if (!Files.exists(srcFile)) {
            throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
        }
        if (Files.isDirectory(srcFile)) {
            throw new IOException("Source '" + srcFile + "' is a directory");
        }
        if (Files.exists(destFile) && !Files.isSameFile(destFile, srcFile)) {
            // extra check for windows, where the File.equals is case insensitive
            // so we know now, that the File is the same, but the absolute name does not match
            throw new FileExistsException("Destination '" + destFile + "' already exists");
        }
        if (Files.isDirectory(destFile)) {
            throw new IOException("Destination '" + destFile + "' is a directory");
        }

        // rename folder; try 5 times and wait a sec
        boolean rename = false;
        for (int i = 0; i < 5; i++) {
            try {
                // need atomic fs move for changing cASE
                Files.move(srcFile, destFile, StandardCopyOption.ATOMIC_MOVE);
                rename = true;// no exception
            } catch (AtomicMoveNotSupportedException a) {
                // if it fails (b/c not on same file system) use that
                try {
                    Files.move(srcFile, destFile, StandardCopyOption.REPLACE_EXISTING);
                    rename = true; // no exception
                } catch (IOException e) {
                    LOGGER.warn("rename problem: " + e.getMessage());
                }
            } catch (IOException e) {
                LOGGER.warn("rename problem: " + e.getMessage());
            }
            if (rename) {
                break; // ok it worked, step out
            }
            try {
                LOGGER.debug("rename did not work - sleep a while and try again...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                LOGGER.warn("I'm so excited - could not sleep");
            }
        }

        if (!rename) {
            LOGGER.error("Failed to rename file '" + srcFile + " to " + destFile);
            MessageManager.instance
                    .pushMessage(new Message(MessageLevel.ERROR, srcFile, "message.renamer.failedrename"));
            return false;
        } else {
            LOGGER.info("Successfully moved file from " + srcFile + " to " + destFile);
            return true;
        }
    }
    return true; // files are equal
}

From source file:org.tellervo.desktop.bulkdataentry.command.PopulateFromODKCommand.java

/**
 * Rename a file, ensuring the new file is unique.  If a file with the suggested new name already exists then an index is added to the end of the filename.
 * /*from  w w  w.ja  v  a2 s  .co  m*/
 * @param fileToRename
 * @param newname
 * @return
 * @throws IOException
 */
private Path renameFile(File fileToRename, String newname) throws IOException {
    File newFile = getUniqueFilename(new File(fileToRename.getParent(), newname));
    log.debug("Renaming file from '" + fileToRename.toString() + "' to '" + newFile + "'");

    return Files.move(fileToRename.toPath(), newFile.toPath(), StandardCopyOption.ATOMIC_MOVE);

}

From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java

protected void saveSecure(final PropertiesConfiguration conf) throws ConfigurationException {
    final File file = conf.getFile();
    try {/*www  .  j a  va2 s  . co m*/
        if (file == null) {
            throw new ConfigurationException("No file name has been set!");
        } else if ((file.createNewFile() || true) && !file.canWrite()) {
            throw new IOException("Cannot write to file " + file.getAbsolutePath() + ". Is it read-only?");
        }
    } catch (IOException e) {
        throw new ConfigurationException(e.getMessage(), e);
    }
    log.debug("Saving {}", file.getAbsolutePath());

    final String fName = file.getName();
    try {
        int lastDot = fName.lastIndexOf('.');
        lastDot = lastDot > 0 ? lastDot : fName.length();

        final Path configPath = file.toPath();
        // Create a tmp file next to the original
        final Path tmp = Files.createTempFile(configPath.getParent(), fName.substring(0, lastDot) + ".",
                fName.substring(lastDot));
        try {
            Files.copy(configPath, tmp, StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException iox) {
            log.error("Could not create temp-file {}: {}", tmp, iox.getMessage());
            throw iox;
        }
        log.trace("using temporary file: {}", tmp);
        // Save the config to the tmp file
        conf.save(tmp.toFile());

        log.trace("tmp saved, now replacing the original file: {}", configPath);
        // Replace the original with the tmp file
        try {
            try {
                Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException amnx) {
                log.trace("atomic move not available: {}, trying without", amnx.getMessage());
                Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException iox) {
            log.error("Could not write to {}, a backup was created in {}", configPath, tmp);
            throw iox;
        }
        log.info("configuration successfully saved to {}", configPath);
    } catch (final Throwable t) {
        throw new ConfigurationException("Unable to save the configuration to the file " + fName, t);
    }
}