Example usage for java.nio.file Files move

List of usage examples for java.nio.file Files move

Introduction

In this page you can find the example usage for java.nio.file Files move.

Prototype

public static Path move(Path source, Path target, CopyOption... options) throws IOException 

Source Link

Document

Move or rename a file to a target file.

Usage

From source file:org.codice.ddf.configuration.admin.ConfigurationAdminMigrationTest.java

@Test
public void testNotifyWithFileThatHasAnInvalidType() throws Exception {
    when(configurationFileFactory.createConfigurationFile(CONFIG_PATH1))
            .thenThrow(new ConfigurationFileException(""));

    ConfigurationAdminMigration configurationAdminMigration = createConfigurationAdminMigratorForNotify();

    configurationAdminMigration.notify(CONFIG_PATH1);

    verify(configurationFileFactory).createConfigurationFile(CONFIG_PATH1);
    verify(configFile1, never()).createConfig();

    verifyStatic(times(1));/*from ww  w  . java 2  s .  c  om*/
    Files.move(CONFIG_PATH1, CONFIG_FILE_IN_FAILED_DIRECTORY.resolve(CONFIG_FILE_PATH1), REPLACE_EXISTING);
}

From source file:org.codice.ddf.configuration.admin.ConfigurationAdminMigrationTest.java

@Test
public void testNotifyWithFileThatCannotBeRead() throws Exception {
    when(configurationFileFactory.createConfigurationFile(CONFIG_PATH1)).thenReturn(configFile1);
    doThrow(new ConfigurationFileException("")).when(configFile1).createConfig();

    ConfigurationAdminMigration configurationAdminMigration = createConfigurationAdminMigratorForNotify();

    configurationAdminMigration.notify(CONFIG_PATH1);

    verify(configurationFileFactory).createConfigurationFile(CONFIG_PATH1);
    verify(configFile1).createConfig();//from  ww w  .  j av  a 2 s .c o  m

    verifyStatic(times(1));
    Files.move(CONFIG_PATH1, CONFIG_FILE_IN_FAILED_DIRECTORY.resolve(CONFIG_FILE_PATH1), REPLACE_EXISTING);
}

From source file:org.codice.ddf.configuration.admin.ConfigurationAdminMigrationTest.java

@Test
public void testNotifyWhenFileReadThrowsRuntimeException() throws Exception {
    when(configurationFileFactory.createConfigurationFile(CONFIG_PATH1)).thenReturn(configFile1);
    doThrow(new RuntimeException()).when(configFile1).createConfig();

    ConfigurationAdminMigration configurationAdminMigration = createConfigurationAdminMigratorForNotify();

    configurationAdminMigration.notify(CONFIG_PATH1);

    verify(configurationFileFactory).createConfigurationFile(CONFIG_PATH1);
    verify(configFile1).createConfig();//  w  w  w .  j a va 2 s.com

    verifyStatic(times(1));
    Files.move(CONFIG_PATH1, CONFIG_FILE_IN_FAILED_DIRECTORY.resolve(CONFIG_FILE_PATH1), REPLACE_EXISTING);
}

From source file:com.nartex.RichFileManager.java

@Override
public JSONObject rename() {
    String relativePath = cleanPreview(this.get.get("old"));
    if (relativePath.endsWith("/")) {
        //this.get.put("old", (this.get.get("old")).substring(0, ((this.get.get("old")).length() - 1)));
        relativePath = relativePath.replaceFirst("/$", "");
    }//from w  w w.  j  a  va  2s  . c  o  m
    boolean error = false;
    JSONObject array = null;
    String tmp[] = relativePath.split("/");
    String filename = tmp[tmp.length - 1];
    int pos = relativePath.lastIndexOf("/");
    String path = relativePath.substring(0, pos + 1);
    Path fileFrom = null;
    Path fileTo = null;
    try {
        fileFrom = this.documentRoot.resolve(path).resolve(filename);
        fileTo = this.documentRoot.resolve(path).resolve(cleanPreview(this.get.get("new")));
        if (fileTo.toFile().exists()) {
            if (fileTo.toFile().isDirectory()) {
                this.error(sprintf(lang("DIRECTORY_ALREADY_EXISTS"), this.get.get("new")));
                error = true;
            } else { // fileTo.isFile
                // Files.isSameFile(fileFrom, fileTo);
                this.error(sprintf(lang("FILE_ALREADY_EXISTS"), this.get.get("new")));
                error = true;
            }
        } else {
            //if (fileFrom.equals(fileTo));
            Files.move(fileFrom, fileTo, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (Exception e) {
        if (fileFrom.toFile().isDirectory()) {
            this.error(sprintf(lang("ERROR_RENAMING_DIRECTORY"), filename + "#" + this.get.get("new")), e);
        } else {
            this.error(sprintf(lang("ERROR_RENAMING_FILE"), filename + "#" + this.get.get("new")), e);
        }
        error = true;
    }
    if (!error) {
        array = new JSONObject();
        try {
            array.put("Error", "");
            array.put("Code", 0);
            array.put("Old Path", this.get.get("old"));
            array.put("Old Name", filename);
            array.put("New Path", getPreviewFolder() + path + this.get.get("new"));
            array.put("New Name", this.get.get("new"));
        } catch (Exception e) {
            this.error("JSONObject error");
        }
    }
    return array;
}

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 .  j a  v  a  2 s.co 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:backtype.storm.localizer.Localizer.java

private LocalizedResource downloadBlob(Map conf, String key, File localFile, String user, boolean uncompress,
        boolean isUpdate) throws AuthorizationException, KeyNotFoundException, IOException {
    ClientBlobStore blobstore = null;//from   w  w  w  .j av  a  2  s  .c o m
    try {
        blobstore = getClientBlobStore();
        long nimbusBlobVersion = Utils.nimbusVersionOfBlob(key, blobstore);
        long oldVersion = Utils.localVersionOfBlob(localFile.toString());
        FileOutputStream out = null;
        PrintWriter writer = null;
        int numTries = 0;
        String localizedPath = localFile.toString();
        String localFileWithVersion = Utils.constructBlobWithVersionFileName(localFile.toString(),
                nimbusBlobVersion);
        String localVersionFile = Utils.constructVersionFileName(localFile.toString());
        String downloadFile = localFileWithVersion;
        if (uncompress) {
            // we need to download to temp file and then unpack into the one requested
            downloadFile = new File(localFile.getParent(), TO_UNCOMPRESS + localFile.getName()).toString();
        }
        while (numTries < _blobDownloadRetries) {
            out = new FileOutputStream(downloadFile);
            numTries++;
            try {
                if (!Utils.canUserReadBlob(blobstore.getBlobMeta(key), user)) {
                    throw new AuthorizationException(user + " does not have READ access to " + key);
                }
                InputStreamWithMeta in = blobstore.getBlob(key);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) >= 0) {
                    out.write(buffer, 0, len);
                }
                out.close();
                in.close();
                if (uncompress) {
                    Utils.unpack(new File(downloadFile), new File(localFileWithVersion));
                    LOG.debug("uncompressed " + downloadFile + " to: " + localFileWithVersion);
                }

                // Next write the version.
                LOG.info("Blob: " + key + " updated with new Nimbus-provided version: " + nimbusBlobVersion
                        + " local version was: " + oldVersion);
                // The false parameter ensures overwriting the version file, not appending
                writer = new PrintWriter(new BufferedWriter(new FileWriter(localVersionFile, false)));
                writer.println(nimbusBlobVersion);
                writer.close();

                try {
                    setBlobPermissions(conf, user, localFileWithVersion);
                    setBlobPermissions(conf, user, localVersionFile);

                    // Update the key.current symlink. First create tmp symlink and do
                    // move of tmp to current so that the operation is atomic.
                    String tmp_uuid_local = java.util.UUID.randomUUID().toString();
                    LOG.debug("Creating a symlink @" + localFile + "." + tmp_uuid_local + " , " + "linking to: "
                            + localFile + "." + nimbusBlobVersion);
                    File uuid_symlink = new File(localFile + "." + tmp_uuid_local);

                    Files.createSymbolicLink(uuid_symlink.toPath(), Paths.get(
                            Utils.constructBlobWithVersionFileName(localFile.toString(), nimbusBlobVersion)));
                    File current_symlink = new File(
                            Utils.constructBlobCurrentSymlinkName(localFile.toString()));
                    Files.move(uuid_symlink.toPath(), current_symlink.toPath(), ATOMIC_MOVE);
                } catch (IOException e) {
                    // if we fail after writing the version file but before we move current link we need to
                    // restore the old version to the file
                    try {
                        PrintWriter restoreWriter = new PrintWriter(
                                new BufferedWriter(new FileWriter(localVersionFile, false)));
                        restoreWriter.println(oldVersion);
                        restoreWriter.close();
                    } catch (IOException ignore) {
                    }
                    throw e;
                }

                String oldBlobFile = localFile + "." + oldVersion;
                try {
                    // Remove the old version. Note that if a number of processes have that file open,
                    // the OS will keep the old blob file around until they all close the handle and only
                    // then deletes it. No new process will open the old blob, since the users will open the
                    // blob through the "blob.current" symlink, which always points to the latest version of
                    // a blob. Remove the old version after the current symlink is updated as to not affect
                    // anyone trying to read it.
                    if ((oldVersion != -1) && (oldVersion != nimbusBlobVersion)) {
                        LOG.info("Removing an old blob file:" + oldBlobFile);
                        Files.delete(Paths.get(oldBlobFile));
                    }
                } catch (IOException e) {
                    // At this point we have downloaded everything and moved symlinks.  If the remove of
                    // old fails just log an error
                    LOG.error("Exception removing old blob version: " + oldBlobFile);
                }

                break;
            } catch (AuthorizationException ae) {
                // we consider this non-retriable exceptions
                if (out != null) {
                    out.close();
                }
                new File(downloadFile).delete();
                throw ae;
            } catch (IOException | KeyNotFoundException e) {
                if (out != null) {
                    out.close();
                }
                if (writer != null) {
                    writer.close();
                }
                new File(downloadFile).delete();
                if (uncompress) {
                    try {
                        FileUtils.deleteDirectory(new File(localFileWithVersion));
                    } catch (IOException ignore) {
                    }
                }
                if (!isUpdate) {
                    // don't want to remove existing version file if its an update
                    new File(localVersionFile).delete();
                }

                if (numTries < _blobDownloadRetries) {
                    LOG.error("Failed to download blob, retrying", e);
                } else {
                    throw e;
                }
            }
        }
        return new LocalizedResource(key, localizedPath, uncompress);
    } finally {
        if (blobstore != null) {
            blobstore.shutdown();
        }
    }
}

From source file:net.mozq.picto.core.ProcessCore.java

private static ProcessDataStatus process(ProcessCondition processCondition, ProcessData processData,
        Function<ProcessData, ProcessDataStatus> overwriteConfirm) throws IOException {

    ProcessDataStatus status;/*from   w w  w .ja v  a  2 s .c  o m*/

    Path destParentPath = processData.getDestPath().getParent();
    if (destParentPath != null) {
        Files.createDirectories(destParentPath);
    }

    if (processCondition.isCheckDigest()
            || (processCondition.isChangeExifDate() && processData.getBaseDate() != null)
            || processCondition.isRemveExifTagsGps() || processCondition.isRemveExifTagsAll()) {
        Path destTempPath = null;
        try {
            destTempPath = Files.createTempFile(processData.getDestPath().getParent(),
                    processData.getDestPath().getFileName().toString(), null);

            if (processCondition.isCheckDigest()) {
                String algorithm = FILE_DIGEST_ALGORITHM;

                MessageDigest srcMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(processData.getSrcPath())), srcMD)) {
                    Files.copy(is, destTempPath, OPTIONS_COPY_REPLACE);
                }
                byte[] srcDigest = srcMD.digest();

                MessageDigest destMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(destTempPath)), destMD)) {
                    byte[] b = new byte[1024];
                    while (is.read(b) != -1) {
                    }
                }
                byte[] destDigest = destMD.digest();

                if (!isSame(srcDigest, destDigest)) {
                    throw new PictoFileDigestMismatchException(
                            Messages.getString("message.error.digest.mismatch"));
                }
            } else if (processCondition.isRemveExifTagsAll()) {
                ExifRewriter exifRewriter = new ExifRewriter();
                try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                    exifRewriter.removeExifMetadata(processData.getSrcPath().toFile(), os);
                } catch (ImageReadException | ImageWriteException e) {
                    throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                }
            } else if (processCondition.isChangeExifDate() || processCondition.isRemveExifTagsGps()) {
                ImageMetadata imageMetadata = getImageMetadata(processData.getSrcPath());
                TiffOutputSet outputSet = getOutputSet(imageMetadata);
                if (outputSet == null) {
                    Files.copy(processData.getSrcPath(), destTempPath, OPTIONS_COPY_REPLACE);
                } else {
                    if (processCondition.isChangeExifDate()) {
                        SimpleDateFormat exifDateFormat = new SimpleDateFormat(EXIF_DATE_PATTERN);
                        exifDateFormat.setTimeZone(processCondition.getTimeZone());
                        String exifBaseDate = exifDateFormat.format(processData.getBaseDate());

                        DecimalFormat exifSubsecFormat = new DecimalFormat(EXIF_SUBSEC_PATTERN);
                        String exifBaseSubsec = exifSubsecFormat
                                .format((int) (processData.getBaseDate().getTime() / 10) % 100);

                        try {
                            TiffOutputDirectory rootDirectory = outputSet.getRootDirectory();
                            TiffOutputDirectory exifDirectory = outputSet.getExifDirectory();
                            if (rootDirectory != null) {
                                rootDirectory.removeField(TiffTagConstants.TIFF_TAG_DATE_TIME);
                                rootDirectory.add(TiffTagConstants.TIFF_TAG_DATE_TIME, exifBaseDate);
                            }
                            if (exifDirectory != null) {
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME, exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL,
                                        exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED,
                                        exifBaseSubsec);
                            }
                        } catch (ImageWriteException e) {
                            throw new PictoFileChangeException(Messages.getString("message.error.edit.file"),
                                    e);
                        }
                    }

                    if (processCondition.isRemveExifTagsGps()) {
                        outputSet.removeField(ExifTagConstants.EXIF_TAG_GPSINFO);
                    }

                    ExifRewriter exifRewriter = new ExifRewriter();
                    try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                        exifRewriter.updateExifMetadataLossless(processData.getSrcPath().toFile(), os,
                                outputSet);
                    } catch (ImageReadException | ImageWriteException e) {
                        throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                    }
                }
            }

            Path destPath;
            if (processCondition.getOperationType() == OperationType.Overwrite) {
                destPath = processData.getSrcPath();
            } else {
                destPath = processData.getDestPath();
            }
            try {
                Files.move(destTempPath, destPath, OPTIONS_MOVE);
                if (processCondition.getOperationType() == OperationType.Move) {
                    Files.deleteIfExists(processData.getSrcPath());
                }
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    // Overwrite
                    Files.move(destTempPath, destPath, OPTIONS_MOVE_REPLACE);
                    if (processCondition.getOperationType() == OperationType.Move) {
                        Files.deleteIfExists(processData.getSrcPath());
                    }
                    status = ProcessDataStatus.Success;
                }
            }
        } finally {
            if (destTempPath != null) {
                Files.deleteIfExists(destTempPath);
            }
        }
    } else {
        switch (processCondition.getOperationType()) {
        case Copy:
            try {
                Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Move:
            try {
                Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Overwrite:
            // NOP
            status = ProcessDataStatus.Success;
            break;
        default:
            throw new IllegalStateException(processCondition.getOperationType().toString());
        }
    }

    if (status == ProcessDataStatus.Success) {
        FileTime creationFileTime = processData.getSrcFileAttributes().creationTime();
        FileTime modifiedFileTime = processData.getSrcFileAttributes().lastModifiedTime();
        FileTime accessFileTime = processData.getSrcFileAttributes().lastAccessTime();
        if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate()
                || processCondition.isChangeFileAccessDate()) {
            if (processData.getBaseDate() != null) {
                FileTime baseFileTime = FileTime.fromMillis(processData.getBaseDate().getTime());
                if (processCondition.isChangeFileCreationDate()) {
                    creationFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileModifiedDate()) {
                    modifiedFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileAccessDate()) {
                    accessFileTime = baseFileTime;
                }
            }
        }
        BasicFileAttributeView attributeView = Files.getFileAttributeView(processData.getDestPath(),
                BasicFileAttributeView.class);
        attributeView.setTimes(modifiedFileTime, accessFileTime, creationFileTime);
    }

    return status;
}

From source file:eu.aliada.ckancreation.impl.CKANCreation.java

/**
 * It copies the organisation image file to the dataset web root.
 *
 * @return true if the organisation image has been copied correctly. False otherwise.                 
 * @since 2.0/*w  ww .j a  v a2s . com*/
 */
public boolean copyOrgImageToWebServerPath() {
    boolean success = false;
    try {
        //Move the organization image file from TMP folder to the definitive folder
        File orgImageInitFile = new File(jobConf.getOrgImagePath());
        final String definitiveFileName = dataFolderName + File.separator + "orgLogo.jpeg";
        final File definitiveFile = new File(definitiveFileName);
        Files.move(orgImageInitFile.toPath(), definitiveFile.toPath(),
                java.nio.file.StandardCopyOption.REPLACE_EXISTING);
        jobConf.setOrgImagePath(definitiveFileName);
        String orgImageURL = dataFolderURL + "/" + definitiveFile.getName();
        jobConf.setOrgImageURL(orgImageURL);
        success = true;
    } catch (IOException exception) {
        LOGGER.error(MessageCatalog._00035_FILE_ACCESS_FAILURE, exception, jobConf.getOrgImagePath());
    }
    return success;
}

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 www  .  java 2 s .c  om*/
 * @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:eu.aliada.ckancreation.impl.CKANCreation.java

/**
 * It creates a new Dataset in CKAN Datahub. Removes it first if it already exists.
 * It also updates the organization information in CKAN Datahub.
 *
 * @return the {@link eu.aliada.ckancreation.model.job} created.                 
 * @since 2.0//  w  w  w . j  av a2  s. com
 */
public Job newDataset() {
    LOGGER.debug(MessageCatalog._00030_STARTING);
    //Update job start-date in DDBB
    dbConn.updateJobStartDate(jobConf.getId());

    //Get the number of triples of the dataset
    final int numTriples = calculateDatasetNumTriples(jobConf.getSparqlEndpointUri(), jobConf.getSparqlLogin(),
            jobConf.getSparqlPassword(), jobConf.getSubsets());
    jobConf.setNumTriples(numTriples);
    //ORGANIZATION
    //Copy organisation image file to dataset web root
    copyOrgImageToWebServerPath();
    try {
        //Move the generated dump file from TMP folder to the definitive folder
        File orgImageInitFile = new File(jobConf.getOrgImagePath());
        final String definitiveFileName = dataFolderName + File.separator + orgImageInitFile.getName();
        final File definitiveFile = new File(definitiveFileName);
        Files.move(orgImageInitFile.toPath(), definitiveFile.toPath(),
                java.nio.file.StandardCopyOption.REPLACE_EXISTING);
        jobConf.setOrgImagePath(definitiveFileName);
        String orgImageURL = dataFolderURL + "/" + definitiveFile.getName();
        jobConf.setOrgImageURL(orgImageURL);
    } catch (IOException exception) {
        LOGGER.error(MessageCatalog._00035_FILE_ACCESS_FAILURE, exception, jobConf.getOrgImagePath());
    }

    final CKANOrgResponse cOrgResponse = updateOrganization();
    //DATASET
    if (cOrgResponse.getSuccess() == "true") {
        final CKANDatasetResponse cDataResponse = createDataset(cOrgResponse, numTriples);
        //DATASET RESOURCES
        if (cDataResponse.getSuccess() == "true") {
            createResources(cDataResponse, numTriples);
        }
    }

    //Update job end_date of DDBB
    LOGGER.debug(MessageCatalog._00057_UPDATING_JOB_DDBB, jobConf.getId());
    dbConn.updateJobEndDate(jobConf.getId());
    final Job job = dbConn.getJob(jobConf.getId());
    LOGGER.debug(MessageCatalog._00041_STOPPED);
    return job;
}