Use case: Need to move a file from one location to another location in a transactional way.If the operation fails,the appropriate operation must be rolled back.
I've chosen Apache Commons Transaction lib.
I tried to use moveResource function from FileResourceManager,below is my code.
Code:
public static void moveFiles() throws ResourceManagerException {
FileResourceManager fileResourceManager=null;
String txId = null;
try {
String workDir = "D:\\source";
String storeDir = "D:\\destination";
fileResourceManager = new FileResourceManager(storeDir, workDir, false, LOGGER_FACADE,true);
fileResourceManager.start();
txId = fileResourceManager.generatedUniqueTxId();
fileResourceManager.startTransaction(txId);
fileResourceManager.moveResource(txId,workDir,storeDir,true);
fileResourceManager.commitTransaction(txId);
//if any exception arises rollback
} catch (ResourceManagerException resourceManagerException) {
fileResourceManager.rollbackTransaction(txId);
resourceManagerException.printStackTrace();
}
}
Is it a right way to move files ? , below is my source directory (where file present) and destination directory (where file needs to be moved)
[![source and destination directories][1]][1]
[1]: https://i.stack.imgur.com/oS6x5.png
To make it happen transactionally,you could copy the entire file and then delete from source location.If we directly try to move the file,its contents could get corrupted in case of failure and hence rollback won't help.
The above implementation was done using
java.niopackage.You could use apache utilities for file operations ApacheFileUtil