In spring-boot-integration app, wrote a custom locker to rename the original file before locking (fileToLock.getAbsolutePath() + ".lock") and expected lock on file so that any other instance will not be able to process the same file .
When file is renaming, its coping the contents from original file and additional file is created with filename.lock with contents and original file also existing with size 0 kb without content.
Outbound-gateway taking the original file as input which is without content and routing it to target path.
Would like to know how to rename the original file, or how to pass the renamed file filename.lock as input to Outbound gateway/adapter.
<integration:chain id="filesOutChain" input-channel="filesOutChain">
<file:outbound-gateway id="fileMover"
auto-create-directory="true"
directory-expression="headers.TARGET_PATH"
mode="REPLACE">
<file:request-handler-advice-chain>
<ref bean="retryAdvice" />
</file:request-handler-advice-chain>
</file:outbound-gateway>
<integration:gateway request-channel="filesOutchainChannel" error-channel="errorChannel"/>
</integration:chain>
CustomFileLocker:
public class CustomFileLocker extends AbstractFileLockerFilter{
private final ConcurrentMap<File, FileLock> lockCache = new ConcurrentHashMap<File, FileLock>();
private final ConcurrentMap<File, FileChannel> channelCache = new ConcurrentHashMap<File, FileChannel>();
@Override
public boolean lock(File fileToLock) {
FileChannel channel;
FileLock lock;
try {
boolean fileRename =fileToLock.renameTo(new File(fileToLock.getAbsolutePath() + ".lock"));
if(fileRename)
{
channel = new RandomAccessFile(fileToLock, "rw").getChannel();
lock = channel.tryLock();
if (lock == null || !lock.isValid()) {
System.out.println(" Problem in acquiring lock!!" + fileToLock.getName());
return false;
}
lockCache.put(fileToLock, lock);
channelCache.put(fileToLock, channel);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
@Override
public boolean isLockable(File file) {
return file.canWrite();
}
@Override
public void unlock(File fileToUnlock) {
FileLock lock = lockCache.get(fileToUnlock);
try {
if(lock!=null){
lock.release();
channelCache.get(fileToUnlock).close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}