Apache Transactions : How to move the files transactionally

58 views Asked by At

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
1

There are 1 answers

0
Sagar On

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.

public static void moveFiles() throws Exception {

            Path source = Paths.get("C:\\sourced\\A.txt");
            Path destination = Paths.get("C:\\destination",source.getFileName().toString());
            Path fileToBeDeleted = source;
            try {
                Files.createFile(destination);
                Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES);
            }catch (Exception e){
                logger.log(Level.WARNING,"Error while copyingFile to destination");
                fileToBeDeleted = destination;
            }finally {
                try {
                    Files.deleteIfExists(fileToBeDeleted);
                }catch (Exception e){
                    logger.log(Level.SEVERE,"File not deleted from source/destination");
                    throw new IllegalStateException("Error while deleting file in source/destination "+fileToBeDeleted);
                }
            }

    }

The above implementation was done using java.nio package.You could use apache utilities for file operations ApacheFileUtil