List of usage examples for java.nio.file StandardCopyOption ATOMIC_MOVE
StandardCopyOption ATOMIC_MOVE
To view the source code for java.nio.file StandardCopyOption ATOMIC_MOVE.
Click Source Link
From source file:ch.bender.evacuate.Helper.java
/** * If the given target is already present, the method retains this older version in a kind of * FIFO buffer (but persistent on disk). The given MaxBackups number indicates how many such * backups are kept./*from ww w . jav a 2 s.c o m*/ * <p> * This routine is valid for files and directories. With files, the numbering suffix is done * before the last dot in the file name, with directories the number suffix is appended at the * end. * <p> * Example: target is "Target.txt" and there are already present: * <pre> * Target.txt * Target_01.txt * Target_02.txt * <pre> * Target_02.txt is renamed to Target_03.txt, Target_01.txt to Target_02.txt and Target.txt Target_01.txt. * <p> * If MaxBackup would be 3, then Target_02.txt would have been deleted instead renamed. * <p> * * @param aTarget * @param aMaxBackups * @param aFailedPreparations * @throws IOException */ public static void prepareTrashChain(Path aTarget, int aMaxBackups, Map<Path, Throwable> aFailedPreparations) { myLog.debug("preparing trash chain for " + aTarget.toString()); try { int i = aMaxBackups - 1; while (i > 0) { Path targetUpper = appendNumberSuffix(aTarget, i); Path targetLower = (i > 1) ? appendNumberSuffix(aTarget, i - 1) : aTarget; i--; if (Files.notExists(targetUpper) && Files.notExists(targetLower)) { continue; } if (Files.exists(targetUpper)) { myLog.info("There are already " + (i + 2) + " trashed versions of " + aTarget.toString() + ". Deleting the oldest one"); if (Files.exists(targetUpper)) { if (Files.isDirectory(targetUpper)) { Helper.deleteDirRecursive(targetUpper); } else { Files.delete(targetUpper); } } } if (Files.notExists(targetLower)) { continue; } myLog.debug("Renaming " + targetLower.toString() + " to " + targetUpper.toString()); Files.move(targetLower, targetUpper, StandardCopyOption.ATOMIC_MOVE); } } catch (Throwable e) { aFailedPreparations.put(aTarget, e); } }
From source file:ee.ria.xroad.confproxy.util.OutputBuilder.java
/** * Moves the signed global configuration to the location where it is * accessible to clients and cleans up any remaining temporary files. * @throws Exception in case of unsuccessful file operations *///from ww w. j ava2 s . c om public final void moveAndCleanup() throws Exception { String path = conf.getConfigurationTargetPath(); Path targetPath = Paths.get(path, timestamp); Path targetConf = Paths.get(path, String.format("%s-v%d", SIGNED_DIRECTORY_NAME, version)); Files.createDirectories(targetPath.getParent()); log.debug("Moving '{}' to '{}'", tempDirPath, targetPath); Files.move(tempDirPath, targetPath); log.debug("Moving '{}' to '{}'", tempConfPath, targetConf); Files.move(tempConfPath, targetConf, StandardCopyOption.ATOMIC_MOVE); FileUtils.deleteDirectory(tempDirPath.toFile()); }
From source file:org.apache.solr.core.StandardDirectoryFactory.java
public void renameWithOverwrite(Directory dir, String fileName, String toName) throws IOException { Directory baseDir = getBaseDir(dir); if (baseDir instanceof FSDirectory) { Path path = ((FSDirectory) baseDir).getDirectory().toAbsolutePath(); try {//w w w. j a v a 2s. c o m Files.move(path.resolve(fileName), path.resolve(toName), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (AtomicMoveNotSupportedException e) { Files.move(FileSystems.getDefault().getPath(path.toString(), fileName), FileSystems.getDefault().getPath(path.toString(), toName), StandardCopyOption.REPLACE_EXISTING); } } else { super.renameWithOverwrite(dir, fileName, toName); } }
From source file:org.artifactory.storage.binstore.service.providers.DoubleFileBinaryProviderImpl.java
private void copyShaBetweenProviders(DynamicFileBinaryProviderImpl myProvider, DynamicFileBinaryProviderImpl otherProvider, String sha1) { log.info("Copying missing checksum file " + sha1 + " from '" + otherProvider.getBinariesDir().getAbsolutePath() + "' to '" + myProvider.getBinariesDir().getAbsolutePath() + "'"); File src = otherProvider.getFile(sha1); File destFile = myProvider.getFile(sha1); if (destFile.exists()) { log.info("Checksum file '" + destFile.getAbsolutePath() + "' already exists"); return;// www. j a v a 2 s . co m } File tempBinFile = null; try { tempBinFile = BinaryProviderHelper.createTempBinFile(myProvider.tempBinariesDir); FileUtils.copyFile(src, tempBinFile); Path target = destFile.toPath(); if (!java.nio.file.Files.exists(target)) { // move the file from the pre-filestore to the filestore java.nio.file.Files.createDirectories(target.getParent()); try { log.trace("Moving {} to {}", tempBinFile.getAbsolutePath(), target); java.nio.file.Files.move(tempBinFile.toPath(), target, StandardCopyOption.ATOMIC_MOVE); log.trace("Moved {} to {}", tempBinFile.getAbsolutePath(), target); } catch (FileAlreadyExistsException ignore) { // May happen in heavy concurrency cases log.trace("Failed moving {} to {}. File already exist", tempBinFile.getAbsolutePath(), target); } tempBinFile = null; } else { log.trace("File {} already exist in the file store. Deleting temp file: {}", target, tempBinFile.getAbsolutePath()); } } catch (IOException e) { String msg = "Error copying file " + src.getAbsolutePath() + " into " + destFile.getAbsolutePath(); if (log.isDebugEnabled()) { log.warn(msg, e); } else { log.warn(msg + " due to: " + e.getMessage()); } } finally { if (tempBinFile != null && tempBinFile.exists()) { if (!tempBinFile.delete()) { log.error("Could not delete temp file {}", tempBinFile.getAbsolutePath()); } } } }
From source file:ch.bender.evacuate.Runner.java
/** * run/* w w w .j a v a 2 s . c om*/ * <p> * @throws Exception */ public void run() throws Exception { checkDirectories(); initExcludeMatchers(); myEvacuateCandidates = new TreeMap<>(); myFailedChainPreparations = Collections.synchronizedMap(new HashMap<>()); myFutures = new HashSet<>(); myExclusionDirCount = 0; myEvacuationDirCount = 0; myExclusionFileCount = 0; myEvacuationFileCount = 0; Files.walkFileTree(myBackupDir, new SimpleFileVisitor<Path>() { /** * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException) */ @Override public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException { if ("System Volume Information".equals((aFile.getFileName().toString()))) { return FileVisitResult.SKIP_SUBTREE; } throw aExc; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { return Runner.this.visitFile(file, attrs); } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if ("System Volume Information".equals((dir.getFileName()))) { return FileVisitResult.SKIP_SUBTREE; } return Runner.this.preVisitDirectory(dir, attrs); } }); if (myEvacuateCandidates.size() == 0) { myLog.info("No candidates for evacuation found"); } else { StringBuilder sb = new StringBuilder("\nFound candidates for evacuation:"); myEvacuateCandidates.keySet().forEach(p -> sb.append("\n " + p.toString())); myLog.info(sb.toString()); } if (myDryRun) { myLog.debug("DryRun flag is set. Doing nothing"); return; } if (myFutures.size() > 0) { myLog.debug("Waiting for all async tasks to complete"); CompletableFuture.allOf(myFutures.toArray(new CompletableFuture[myFutures.size()])).get(); } if (myFailedChainPreparations.size() > 0) { for (Path path : myFailedChainPreparations.keySet()) { myLog.error("exception occured", myFailedChainPreparations.get(path)); } throw new Exception("chain preparation failed. See above error messages"); } for (Path src : myEvacuateCandidates.keySet()) { Path dst = myEvacuateCandidates.get(src); Path dstParent = dst.getParent(); if (Files.notExists(dstParent)) { Files.createDirectories(dstParent); // FUTURE: overtake file attributes from src } if (myMove) { try { myLog.debug( "Moving file system object \"" + src.toString() + "\" to \"" + dst.toString() + "\""); Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { myLog.warn("Atomic move not supported. Try copy and then delete"); if (Files.isDirectory(src)) { myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\""); FileUtils.copyDirectory(src.toFile(), dst.toFile()); myLog.debug("Delete folder \"" + src.toString() + "\""); FileUtils.deleteDirectory(src.toFile()); } else { myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\""); FileUtils.copyFile(src.toFile(), dst.toFile()); myLog.debug("Delete file \"" + src.toString() + "\""); Files.delete(src); } } } else { if (Files.isDirectory(src)) { myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\""); FileUtils.copyDirectory(src.toFile(), dst.toFile()); } else { myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\""); FileUtils.copyFile(src.toFile(), dst.toFile()); } } } myLog.info("\nSuccessfully terminated." + "\n Evacuated Skipped" + "\n Files : " + StringUtils.leftPad("" + myEvacuationDirCount, 9) + StringUtils.leftPad("" + myExclusionDirCount, 9) + "\n Folders: " + StringUtils.leftPad("" + myEvacuationFileCount, 9) + StringUtils.leftPad("" + myExclusionFileCount, 9)); }
From source file:de.digiway.rapidbreeze.server.model.download.Download.java
private int handleRunning() throws IOException { long position = targetChannel.position(); long transferred = targetChannel.transferFrom(sourceChannel, position, BLOCK_SIZE); targetChannel.position(position + transferred); if (targetChannel.size() == getUrlStatus().getFileSize()) { closeChannels();//from w w w .ja v a 2 s . c o m Files.move(tempFile, targetFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); done = true; statusHandler.newStatus(DownloadStatus.FINISHED_SUCCESSFUL); } return throttledInputStream.nextTransfer(BLOCK_SIZE); }
From source file:org.apache.beam.sdk.io.LocalFileSystem.java
@Override protected void rename(List<LocalResourceId> srcResourceIds, List<LocalResourceId> destResourceIds) throws IOException { checkArgument(srcResourceIds.size() == destResourceIds.size(), "Number of source files %s must equal number of destination files %s", srcResourceIds.size(), destResourceIds.size());/* ww w. j a va 2 s . c o m*/ int numFiles = srcResourceIds.size(); for (int i = 0; i < numFiles; i++) { LocalResourceId src = srcResourceIds.get(i); LocalResourceId dst = destResourceIds.get(i); LOG.debug("Renaming {} to {}", src, dst); File parent = dst.getCurrentDirectory().getPath().toFile(); if (!parent.exists()) { checkArgument(parent.mkdirs() || parent.exists(), "Unable to make output directory %s in order to move into file %s", parent, dst.getPath()); } // Rename the source file, replacing the existing destination. Files.move(src.getPath(), dst.getPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } }
From source file:org.apache.storm.daemon.supervisor.AdvancedFSOps.java
/** * Move fromDir to toDir, and try to make it an atomic move if possible * @param fromDir what to move// ww w. j a v a 2 s . com * @param toDir where to move it from * @throws IOException on any error */ public void moveDirectoryPreferAtomic(File fromDir, File toDir) throws IOException { FileUtils.forceMkdir(toDir); Files.move(fromDir.toPath(), toDir.toPath(), StandardCopyOption.ATOMIC_MOVE); }
From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java
private void moveOrCopyFile(File originNodeFile, File targetNodeFile) throws IOException { try {/* w ww . jav a 2s . c o m*/ Files.move(originNodeFile.toPath(), targetNodeFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException amnse) { logger.warn( "Could not perform atomic move: " + amnse.getMessage() + ". Trying regular copy and delete..."); Files.copy(originNodeFile.toPath(), targetNodeFile.toPath(), StandardCopyOption.REPLACE_EXISTING); deleteFile(originNodeFile); } }
From source file:com.liferay.sync.engine.document.library.handler.DownloadFileHandler.java
protected void copyFile(final SyncFile syncFile, Path filePath, InputStream inputStream, boolean append) throws Exception { OutputStream outputStream = null; Watcher watcher = WatcherManager.getWatcher(getSyncAccountId()); try {//from w w w .jav a2s. co m Path tempFilePath = FileUtil.getTempFilePath(syncFile); boolean exists = FileUtil.exists(filePath); if (append) { outputStream = Files.newOutputStream(tempFilePath, StandardOpenOption.APPEND); IOUtils.copyLarge(inputStream, outputStream); } else { if (exists && (boolean) getParameterValue("patch")) { if (_logger.isDebugEnabled()) { _logger.debug("Patching {}", syncFile.getFilePathName()); } Files.copy(filePath, tempFilePath, StandardCopyOption.REPLACE_EXISTING); IODeltaUtil.patch(tempFilePath, inputStream); } else { Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING); } } watcher.addDownloadedFilePathName(filePath.toString()); if (GetterUtil.getBoolean(syncFile.getLocalExtraSettingValue("restoreEvent"))) { syncFile.unsetLocalExtraSetting("restoreEvent"); syncFile.setUiEvent(SyncFile.UI_EVENT_RESTORED_REMOTE); } else if (exists) { syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_UPDATE); } else { syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_NEW); } FileKeyUtil.writeFileKey(tempFilePath, String.valueOf(syncFile.getSyncFileId()), false); FileUtil.setModifiedTime(tempFilePath, syncFile.getModifiedTime()); if (MSOfficeFileUtil.isLegacyExcelFile(filePath)) { syncFile.setLocalExtraSetting("lastSavedDate", MSOfficeFileUtil.getLastSavedDate(tempFilePath)); } Files.move(tempFilePath, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); ExecutorService executorService = SyncEngine.getExecutorService(); Runnable runnable = new Runnable() { @Override public void run() { IODeltaUtil.checksums(syncFile); syncFile.setState(SyncFile.STATE_SYNCED); SyncFileService.update(syncFile); } }; executorService.execute(runnable); } catch (FileSystemException fse) { if (fse instanceof AccessDeniedException) { _logger.error(fse.getMessage(), fse); syncFile.setState(SyncFile.STATE_ERROR); syncFile.setUiEvent(SyncFile.UI_EVENT_ACCESS_DENIED_LOCAL); SyncFileService.update(syncFile); return; } else if (fse instanceof NoSuchFileException) { if (isEventCancelled()) { SyncFileService.deleteSyncFile(syncFile); return; } } watcher.removeDownloadedFilePathName(filePath.toString()); String message = fse.getMessage(); _logger.error(message, fse); syncFile.setState(SyncFile.STATE_ERROR); if (message.contains("File name too long")) { syncFile.setUiEvent(SyncFile.UI_EVENT_FILE_NAME_TOO_LONG); } SyncFileService.update(syncFile); } finally { StreamUtil.cleanUp(outputStream); } }