Search code examples
javaspringapache-camelspring-camel

How to select subfolder using File component of Apache Camel?


I have Camel application based on Spring Boot, there is a defined route that should poll specific folder (e.g. C:/test). In this folder there are sub-folders named by ordinal date of the day: 196, 197, 198 etc. I need to filter these subfolders and pick up the folder with max value in its name. In other words I need dynamically choose the folder for File component, e.g. C:/test/197.

I tried to use parameter filterDirectory, e.g by setting it to "${date:now:yyyy}". I tried other configurations of folder structure and it seems to me that this parameter doesn't work.

Can such selection of sub-folders be implemented using Camel?

Update: Currently there is no an opportunity to scan the root folder for sub-folders from code, so solution should rely only on Camel framework.


Solution

  • If the configurable options to filter files or folders do not work for your case, you can implement a GenericFileFilter class and configure it as filter option.

    The GenericFileFilter class contains just an accept method that returns true (file is imported) or false (file is ignored).

    Notice that you need to configure recursive=true if you want to process subdirectories and their files. Without the recursive option, Camel ignores all subdirectories by default.

    If you activate the recursive option, the accept method of GenericFileFilter is called for files and folders. Don't forget to handle the folders. If you return false for a directory all files in it are ignored.

    So for your case (import all files from a certain subfolder) I see something like this

    @Override
    public boolean accept(GenericFile file) {
        correctSubfolder = ... calculate name
    
        if (file.isDirectory() && file.getFileName().equals(correctSubfolder)) {
            // walk into the correct subdirectory
            return true;
        }
    
        if (!file.isDirectory() && file.getParent().equals(correctSubfolder)) {
            // only process files of the correct subdirectory
            return true;
        }
    
        // ignore everything else
        return false;