简体   繁体   中英

How to check whether file exists while wiretapping in Apache Camel

I have a project written in Apache Camel wherein I get the messages from one route and send it to another route for wiretapping:

from("URI").bean(random1)
.wireTap("direct:wiretap")
.recipientList.method(random2, "random2Method");

from("direct:wiretap").routeId("WireTap")
.setProperty("filename", dynamicValueExpression)
.to("file://log-directory-name?fileName=/${date:now:yyyMMdd}/property[filename]")

This code works absolutely fine and it wiretaps files successfully.

Problem here is this code overwrites the file if there is another file coming with the same filename . What I want to achieve is to check if the file already exists and if it does then rename the current file (not the existing one) and then wiretap it.

I checked Camel documentation and found that there is something like fileExist=Move property and Custom File Strategy that I think I might use (I might be wrong here). But I am not sure how exactly it would work.

So my question is:

  1. Is it really possible to achieve what I am trying to achieve?
  2. If yes then can someone please let me know how?

There are probably a few ways of doing this. One of them is using a processor that computes the file name using your dynamic property:

from("direct:wiretap")
    .routeId("WireTap")
    .process(e -> {
        String fileName = (String) e.getProperty("filename");
        if (new File(fileName).exists()) {
            //Compute alternative name
            e.getIn().setHeader("CamelFileName", 
                                fileName + UUID.randomUUID().toString());
        } else {
            e.getIn().setHeader("CamelFileName", fileName);
        }
    })
    .to("file://log-directory-name");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM