Search code examples
zipapache-camel

Zipping files with apache camel


i am saving files on path C:\Cdr\core\year\month\date\fileName and i want to zip all the files created on previous day and before that.I am unable to find a way to provide dynamic file path and file name to file Consumer for zipping files. Even when using filename=${beans:utility.generateFileName}, i am only able to provide file name not the file path.Is there a way to do this using apache Zip file data format.


Solution

  • I found the way for same by using filter

    <routeContext id="zipFileRoute" xmlns="http://camel.apache.org/schema/spring">
      <route id="zipFile">
        <from uri="file://C:/CdrJson?recursive=true&amp;delete=true&amp;filter=#myFilter/>
        <log message="reading from ${in.header.CamelFileName} and file path is ${file:path}"/>
        <setHeader headerName="CamelFileName">
          <simple>${bean:utility?method=processFileName}</simple>
        </setHeader>
        <marshal>
          <zipFile/>
        </marshal>
        <to uri="file://C:/CdrJson"/>
        <log message="This route finished zipping files"/>
      </route>
    </routeContext>
    

    Code for myFilter:

    public class MyFileFilter<T> implements GenericFileFilter<T> {
      public boolean accept(GenericFile<T> file) { 
        // we want all directories
        if (file.isDirectory()) {
          return true;
        }
        Calendar date = new GregorianCalendar();
        String fileName = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        if(file.getFileNameOnly().startsWith(fileName)){
          return false;
        }
        return !file.getFileName().endsWith(".zip");
      }
    }