Question

I am working on a piece of code where I need to work on the files which are located on a server using Apache camel. I need to achieve the following steps:

1 --> The control should iterate through all the files which are located in a specific folder.

2 --> Then it should check which file is older than 15 days.

3 --> Then delete the files which are older than 15 days.

Now, I am able to implement the first and second step. But I am not able to delete the file. I have created a camel route like this:

<camel:route id="lastModifiedFMFileCheckRoute">
            <camel:from uri="sftp://someUser@someServer/usableFiles?password=secret"/>
            <camel:setProperty propertyName="availableFile">
                <camel:simple>${body}</camel:simple>
            </camel:setProperty>
            <camel:process ref="fileModificationDateProcessor" />
</camel:route>  

and the process method of my processor looks like this, where I am checking whether file is older than 15 days.

  @Override
        public void process(Exchange exchange) throws Exception {
            boolean isFileDeleted = false;
            @SuppressWarnings("rawtypes")
            GenericFile currentFile = (GenericFile)exchange.getProperty("availableFile", RemoteFile.class); 
            Date currentDate = new Date();
            int numberOfDays = (int)( (currentDate.getTime() - availableFile.getLastModified()) / MILLISECONDS_TO_DAY_CONVERTER_VALUE);
            if(numberOfDays > 15){
                String absoluteFilePath = availableFile.getAbsoluteFilePath();
                //TODO  The file (currentFile) needs to be deleted. As it is older than 15 days.

        }
        exchange.getOut().setBody(fileDeleted);

    }

How can I achieve the deletion of the required file here.

Was it helpful?

Solution

On your (s)ftp endpoint you can set delete=true and filter=#ageFilter where ageFilter is a reference to a custom file filter that only accepts files older than 15 days.

public class AgeFilter<T> implements GenericFileFilter<T> {

    @Override
    public boolean accept(final GenericFile<T> file) {
        long now = System.currentTimeMillis();
        long lastModified = file.getLastModified();

        return now-lastModified > CUT_OFF_AGE;
    }
}

At the end of the route the (s)ftp enpoint will then delete all files selected by this filter.

As an alternative to the file filter you could throw a RuntimeException in your processor if the file is NOT older than 15 days. This will make your route fail and and will leave the file on the remote server. However, using exceptions for control flow is really not good practice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top