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.geowebcache.util.FileUtils.java

/**
 * Utility method for renaming Files using Java 7 {@link Files}.move() method
 * which provides an atomical file renaming. If an exception occurred during the
 * renaming, the method will fallback to the old File().renameTo() method and
 * will log a Message. /*from   w w  w.j a  v a2  s. co  m*/
 * 
 * @return a boolean indicating if the rename operation has succeded
 */
public static boolean renameFile(File src, File dst) {
    // Renaming result initialization
    boolean renamed = false;

    // 1) try with Java 7 Files.move
    Path srcPath = Paths.get(src.toURI());
    Path dstPath = Paths.get(dst.toURI());
    Path moved = null;
    try {
        // Execute renaming
        moved = Files.move(srcPath, dstPath, StandardCopyOption.ATOMIC_MOVE);
    } catch (Exception e) {
        // Exception occurred falling back to the old renameTo
        if (log.isDebugEnabled()) {
            log.debug(
                    "An error occurred when executing atomic file renaming. Falling back to the old File.renameTo() method",
                    e);
        }
    }
    // 2) Check if succeeded. If failed, falling back to old renameTo
    if (moved == null || !Files.exists(moved)) {
        renamed = src.renameTo(dst);
    } else {
        renamed = true;
    }

    return renamed;
}

From source file:org.appverse.web.framework.backend.ecm.filesystem.services.integration.impl.live.FileSystemDocumentService.java

@Override
public void move(String pathOrigin, String documentNameOrigin, String pathDestination,
        String documentNameDestination) throws Exception {
    File originFile = new File(pathOrigin + "/" + documentNameOrigin);

    // Create destination structure if necessary
    File destinationFolder = new File(pathDestination);
    if (!destinationFolder.exists()) {
        if (!destinationFolder.mkdirs()) {
            throw new Exception("Error creating folder structure to path: " + destinationFolder.toString());
        }//from   w w w .  j a v  a2s  .c om
    }

    // Move the file
    File targetFile = new File(destinationFolder, documentNameDestination);
    try {
        java.nio.file.Files.move(originFile.toPath(), targetFile.toPath(), StandardCopyOption.ATOMIC_MOVE);
    } catch (Exception e) {
        throw new Exception(
                "Error moving temporary file: " + originFile.toString() + "to: " + targetFile.toString());
    }
}

From source file:azkaban.execapp.FlowPreparer.java

/**
 * Prepare the project directory./*w w w.  ja  va  2s  .  co  m*/
 *
 * @param pv ProjectVersion object
 * @throws ProjectManagerException
 * @throws IOException
 */
@VisibleForTesting
void setupProject(final ProjectVersion pv) throws ProjectManagerException, IOException {
    final int projectId = pv.getProjectId();
    final int version = pv.getVersion();

    final String projectDir = String.valueOf(projectId) + "." + String.valueOf(version);
    if (pv.getInstalledDir() == null) {
        pv.setInstalledDir(new File(projectsDir, projectDir));
    }

    // If directory exists. Assume its prepared and skip.
    if (pv.getInstalledDir().exists()) {
        log.info("Project already cached. Skipping download. " + pv);
        return;
    }

    log.info("Preparing Project: " + pv);

    File tempDir = new File(projectsDir, "_temp." + projectDir + "." + System.currentTimeMillis());

    // TODO Why mkdirs? This path should be already set up.
    tempDir.mkdirs();

    ProjectFileHandler projectFileHandler = null;
    try {
        projectFileHandler = requireNonNull(projectLoader.getUploadedFile(projectId, version));
        checkState("zip".equals(projectFileHandler.getFileType()));

        log.info("Downloading zip file.");
        final File zipFile = requireNonNull(projectFileHandler.getLocalFile());
        final ZipFile zip = new ZipFile(zipFile);
        Utils.unzip(zip, tempDir);

        Files.move(tempDir.toPath(), pv.getInstalledDir().toPath(), StandardCopyOption.ATOMIC_MOVE);

        log.warn(String.format("Project Preparation complete. [%s]", pv));
    } finally {

        if (projectFileHandler != null) {
            projectFileHandler.deleteLocalFile();
        }

        // Clean up: Remove tempDir if exists
        FileUtils.deleteDirectory(tempDir);
    }
}

From source file:com.reactive.hzdfs.dll.JarFileSharingService.java

private void moveToExtLibDir(File file) throws IOException {
    Files.move(file.toPath(), Paths.get(extLib).resolve(file.getName()), StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.ATOMIC_MOVE);

}

From source file:org.obiba.opal.server.UpgradeCommand.java

private void upgradeOrientDb() {
    log.info("Upgrading orientdb");
    File exportFile = null;//  w  ww . ja v  a  2s . c o m
    File tmpFile = null;
    Path configBackup = Paths.get(String.format("%s.bak", opalConfigPath));
    Path config = Paths.get(opalConfigPath);

    try {
        tmpFile = File.createTempFile("opal_orientdb_export", null);
        String exportFilePrefix = tmpFile.getAbsolutePath();
        exportFile = Paths.get(exportFilePrefix + ".gz").toFile();

        exportOpalConfig(opalConfigPath, exportFilePrefix);
        Files.move(config, configBackup, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException e) {
        if (exportFile != null && exportFile.exists())
            exportFile.delete();

        throw Throwables.propagate(e);
    } finally {
        if (tmpFile != null)
            tmpFile.delete();
    }

    try (ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_PATHS)) {
        OrientDbService orientDbService = ctx.getBean("orientDbService", OrientDbService.class);
        orientDbService.importDatabase(exportFile);
        log.info("Upgraded orientdb successfully");

        try {
            FileUtils.deleteDirectory(configBackup.toFile());
        } catch (Exception e) {
            log.error("Error cleaning up orientdb upgrade back up directory. Ignoring.", e);
        }
    } catch (IOException e) {
        //roll back
        try {
            FileUtils.deleteDirectory(config.toFile());
            Files.move(configBackup, config, StandardCopyOption.ATOMIC_MOVE);
        } catch (Exception ex) {
            log.error("Error in orientdb upgrade rollback. Ignoring.", ex);
        }

        throw Throwables.propagate(e);
    } finally {
        if (exportFile != null && exportFile.exists())
            exportFile.delete();
    }
}

From source file:org.apache.zeppelin.storage.LocalConfigStorage.java

private void atomicWriteToFile(String content, File file) throws IOException {
    File directory = file.getParentFile();
    File tempFile = File.createTempFile(file.getName(), null, directory);
    FileOutputStream out = new FileOutputStream(tempFile);
    try {/*w ww . j  a  va2  s  . c  om*/
        IOUtils.write(content, out);
    } catch (IOException iox) {
        if (!tempFile.delete()) {
            tempFile.deleteOnExit();
        }
        throw iox;
    }
    out.close();
    FileSystem defaultFileSystem = FileSystems.getDefault();
    Path tempFilePath = defaultFileSystem.getPath(tempFile.getCanonicalPath());
    Path destinationFilePath = defaultFileSystem.getPath(file.getCanonicalPath());
    try {
        Files.move(tempFilePath, destinationFilePath, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException iox) {
        if (!tempFile.delete()) {
            tempFile.deleteOnExit();
        }
        throw iox;
    }
}

From source file:org.apache.solr.core.StandardDirectoryFactory.java

/**
 * Override for more efficient moves./*from   w  w w. jav  a  2  s  .c om*/
 * 
 * Intended for use with replication - use
 * carefully - some Directory wrappers will
 * cache files for example.
 * 
 * You should first {@link Directory#sync(java.util.Collection)} any file that will be 
 * moved or avoid cached files through settings.
 * 
 * @throws IOException
 *           If there is a low-level I/O error.
 */
@Override
public void move(Directory fromDir, Directory toDir, String fileName, IOContext ioContext) throws IOException {

    Directory baseFromDir = getBaseDir(fromDir);
    Directory baseToDir = getBaseDir(toDir);

    if (baseFromDir instanceof FSDirectory && baseToDir instanceof FSDirectory) {

        Path path1 = ((FSDirectory) baseFromDir).getDirectory().toAbsolutePath();
        Path path2 = ((FSDirectory) baseToDir).getDirectory().toAbsolutePath();

        try {
            Files.move(path1.resolve(fileName), path2.resolve(fileName), StandardCopyOption.ATOMIC_MOVE);
        } catch (AtomicMoveNotSupportedException e) {
            Files.move(path1.resolve(fileName), path2.resolve(fileName));
        }
        return;
    }

    super.move(fromDir, toDir, fileName, ioContext);
}

From source file:org.apache.taverna.download.impl.DownloadManagerImpl.java

@Override
public void download(URI source, Path destination, String digestAlgorithm, URI digestSource)
        throws DownloadException {

    MessageDigest md = null;// w  ww .  j a  v a 2  s  .  co m
    if (digestAlgorithm != null) {
        try {
            md = MessageDigest.getInstance(digestAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Unsupported digestAlgorithm: " + digestAlgorithm, e);
        }
    }

    // download the file
    Path tempFile;
    try {
        tempFile = Files.createTempFile(destination.getParent(), "." + destination.getFileName(), ".tmp");
    } catch (IOException e1) {
        // perhaps a permission problem?
        throw new DownloadException("Can't create temporary file in folder " + destination.getParent(), e1);
    }
    logger.info(String.format("Downloading %1$s to %2$s", source, tempFile));
    downloadToFile(source, tempFile);

    if (digestSource != null) {
        // download the digest file
        String expectedDigest;
        expectedDigest = downloadHash(digestSource).trim().toLowerCase(Locale.ROOT);
        // check if the digest matches
        try {
            try (InputStream s = Files.newInputStream(tempFile)) {
                DigestUtils.updateDigest(md, s);
                String actualDigest = Hex.encodeHexString(md.digest());
                if (!actualDigest.equals(expectedDigest)) {
                    throw new DownloadException(
                            String.format("Error downloading file: checksum mismatch (%1$s != %2$s)",
                                    actualDigest, expectedDigest));
                }
            }
        } catch (IOException e) {
            throw new DownloadException(String.format("Error checking digest for %1$s", destination), e);
        }
    }
    // All fine, move to destination
    try {
        logger.info(String.format("Copying %1$s to %2$s", tempFile, destination));
        Files.move(tempFile, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new DownloadException(String.format("Error downloading %1$s to %2$s.", source, destination), e);
    }

}

From source file:net.daboross.bukkitdev.skywars.score.JSONScoreStorage.java

@Override
public void save() throws IOException {
    if (!Files.exists(saveFileBuffer)) {
        Files.createFile(saveFileBuffer);
    }// w ww .  jav  a2s  .c  o m
    try (FileOutputStream fos = new FileOutputStream(saveFileBuffer.toFile())) {
        try (OutputStreamWriter writer = new OutputStreamWriter(fos, Charset.forName("UTF-8"))) {
            baseJson.write(writer);
        }
    } catch (IOException | JSONException ex) {
        throw new IOException("Couldn't write to " + saveFileBuffer.toAbsolutePath(), ex);
    }
    try {
        Files.move(saveFileBuffer, saveFile, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException ex) {
        throw new IOException("Failed to move buffer file '" + saveFileBuffer.toAbsolutePath()
                + "' to actual save location '" + saveFile + "'", ex);
    }
}

From source file:org.commonjava.maven.ext.cli.CliTest.java

@Test
public void checkLocalRepositoryWithDefaultsAndModifiedUserSettings() throws Exception {
    boolean restore = false;
    Path source = Paths.get(
            System.getProperty("user.home") + File.separatorChar + ".m2" + File.separatorChar + "settings.xml");
    Path backup = Paths.get(source.toString() + '.' + UUID.randomUUID().toString());
    Path tmpSettings = Paths.get(getClass().getResource("/settings-test.xml").getFile());

    try {/* ww  w .j  ava  2s .c o m*/
        if (source.toFile().exists()) {
            System.out.println("Backing up settings.xml to " + backup);
            restore = true;
            Files.move(source, backup, StandardCopyOption.ATOMIC_MOVE);
        }
        Files.copy(tmpSettings, source);

        Cli c = new Cli();
        executeMethod(c, "run", new Object[] { new String[] {} });

        ManipulationSession session = (ManipulationSession) FieldUtils.readField(c, "session", true);
        MavenSession ms = (MavenSession) FieldUtils.readField(session, "mavenSession", true);

        assertTrue(ms.getRequest().getLocalRepository().getBasedir()
                .equals(ms.getRequest().getLocalRepositoryPath().toString()));
        assertTrue(ms.getLocalRepository().getBasedir()
                .equals(System.getProperty("user.home") + File.separatorChar + ".m2-mead-test"));

    } finally {
        if (restore) {
            Files.move(backup, source, StandardCopyOption.ATOMIC_MOVE);
        } else {
            Files.delete(source);
        }
    }
}