Spring Integration, delete file in outbound channel adapter

kwh picture kwh · Oct 3, 2012 · Viewed 7.6k times · Source

I am using Spring Integration to poll a directory for a File, process this file in a service class, write this file to an output directory and then delete the original file.

I have the following XML configuration:

  <int-file:inbound-channel-adapter id="filesInChannel"
                                    directory="file:${java.io.tmpdir}/input" 
                                    auto-create-directory="true"  >
      <int:poller id="poller" fixed-delay="1000" />
  </int-file:inbound-channel-adapter>

  <int:service-activator id="servicActivator"
                         input-channel="filesInChannel"
                         output-channel="filesOut"
                         ref="my_file_processing_service">
  </int:service-activator>

  <int-file:outbound-channel-adapter  id="filesOut" auto-create-directory="true" delete-source-files="true" directory="file:${java.io.tmpdir}/output"/>

This polls the file, passes it to my processing_service and copies it to the outbound directory. However the original file is not being deleted. Does anyone have any idea as to why not?

Answer

Jonas Kongslund picture Jonas Kongslund · Nov 18, 2013

I know that the question was asked a long time ago but maybe the answer will be useful to someone else.

The reason why the input file is not deleted is provided in the Spring Integration Reference:

The delete-source-files attribute will only have an effect if the inbound Message has a File payload or if the FileHeaders.ORIGINAL_FILE header value contains either the source File instance or a String representing the original file path.

Your message does not contain this particular header. If you use one of the standard file transformers (FileToStringTransformer and FileToByteArrayTransformer) it will be set automatically. Alternatively you can set it manually using a header enricher.

Behind the scenes something like this is happening in the file transformers:

...
Message<?> transformedMessage = MessageBuilder.withPayload(result)
        .copyHeaders(message.getHeaders())
        .setHeaderIfAbsent(FileHeaders.ORIGINAL_FILE, file)
        .setHeaderIfAbsent(FileHeaders.FILENAME, file.getName())
        .build();
...