Call groovy script dynamically in Apache Camel using doTry-doCatch

Viewed 73

I'm building a route which calls a groovy script whose path is dynamically computed and, if the script can't be found, defaults to a generic, static script:

.doTry()
.toD("language://groovy:resource:classpath:scripts/${exchangeProperty.consumerType}ResponseHandler.groovy")
.doCatch(FileNotFoundException.class)
.script().groovy("resource:classpath:scripts/defaultResponseHandler.groovy")
.end()

The problem is that the exchange property consumerType is not resolved since the uri string parameter of toD is evaluated using groovy and not simple.

    MultipleCompilationErrorsException -> startup failed:
    Script_09b4150584d9e2c979353feee06897b5.groovy: 1: Unexpected input: 'scripts/${exchangeProperty.consumerType}' @ line 1, column 20.
       resource:classpath:scripts/${exchangeProperty.consumerType}ResponseHandler.groovy
                      ^
1 error

How can I obtain the desired behavior?

1 Answers

According to the error shown there, it seems Camel is not able to resolve the string you provided in the toD().

By default, the expression you pass to a dynamic to is evaluated as Simple language but, as described in To Dynamic Camel documentation, you can specify other languages for the dynamic evaluation.

In your case, you are trying to evaluate the endpoint with groovy language but then you're using Simple language to substitute a piece of the name of the script.

One solution I've found (yet not the best) would be to specify the language for the interpretation of the string as simple and then use language:groovy to specify the endpoint that will need to be called.

You could write something like this:

.doTry() 
 .toD("language:simple:language://groovy:resource:classpath:scripts/${exchangeProperty.consumerType}ResponseHandler.groovy")
.doCatch(FileNotFoundException.class)
 .script().groovy("resource:classpath:scripts/defaultResponseHandler.groovy")
.end()

It seems to work, but I hope someone else comes up with a better solution.

Related