Home > Net >  Springboot Integration - Accessing headers within a MessageHandler
Springboot Integration - Accessing headers within a MessageHandler

Time:09-28

I'm trying to move a file to a specific location based on a header that is present in the flow

@Bean
public IntegrationFlow configureFileFlow(
        @Value("${fileSource}") String sourcePath,
        @Value("${fileTarget}") String targetPath
) {
    return IntegrationFlows.from(
            getDataSource(sourcePath),
            conf -> conf.poller(Pollers.fixedDelay(pollerDelay))
    )
            .enrichHeaders(eh -> eh.header("targetPath", targetPath)) //<-- this is the target
            .enrichHeaders(eh -> eh.headerExpression("originalFileName", "payload.getName"))
            .channel("processFile.input")
            .get();
}

when processing the file, after all necessary procedures are done, I call a bean the following way

.handle(backupFile())

which calls

@Bean
public MessageHandler backupFile() {
    FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(targetPath));
    handler.setAutoCreateDirectory(true);
    handler.setFileExistsMode(FileExistsMode.REPLACE_IF_MODIFIED);
    handler.setExpectReply(false);
    handler.setDeleteSourceFiles(true);
    return handler;
}

How would one go about setting the targetPath dynamically based on what's set in the headers, please? I cannot simply pass it along as a parameter since it's a bean and I'd like to avoid creating more beans just for the sake of retrieving a String. Also using a @Value again in the second part of the flow feels redundant, since it is already a part of the message itself, in the headers.

There are multiple types of files that are being processed, each has it's own IntegrationFlow source, but this part where it gets "backed up" should be shared among all of them. The backupFile bean basically needs to have two informations - the file itself as payload and the information from headers on where to store it.

Thanks!

CodePudding user response:

See different constructor:

/**
 * Constructor which sets the {@link #destinationDirectoryExpression}.
 * @param destinationDirectoryExpression Must not be null
 * @see #FileWritingMessageHandler(File)
 */
public FileWritingMessageHandler(Expression destinationDirectoryExpression) {

So, using similar SpEL expression you have above, you can do something like:

new FileWritingMessageHandler(new SpelExpressionParser().parseExpression("headers.targetPath"));

Also see org.springframework.integration.file.dsl.Files.outboundAdapter() for more high-level Java DSL API over that FileWritingMessageHandler.

  • Related