How to invoke a Groovy script stored in Resources

The following route embeds some groovy code. One would like to externalize this code.

<?xml version="1.0" encoding="UTF-8"?>
<routes xmlns:u="http://www.systar.com/aluminium/camel-util" xmlns="http://camel.apache.org/schema/spring">
    
    <route>
        <from uri="timer:test"/>
        <setHeader headerName="tomorrow">
            <groovy>
now = System.currentTimeMillis()
now += 1000*60*60*24
new Date(now).toString()
            </groovy>
        </setHeader>
        <to uri="log:test?showHeaders=true"/>
    </route>
    
</routes>

In order to do that:

Step 1: Create a resource that contains the Groovy code (in this exemple the name of the resource is myScript.groovy)

now = System.currentTimeMillis()
now += 1000*60*60*24
new Date(now).toString()

Step 2: change the route to use the groovy code in the resource with the syntax <groovy>resource:tnd-resource:resourceName</groovy>

<?xml version="1.0" encoding="UTF-8"?>
<routes xmlns:u="http://www.systar.com/aluminium/camel-util" xmlns="http://camel.apache.org/schema/spring">
    
    <route>
        <from uri="timer:test"/>
        <setHeader headerName="tomorrow">
            <groovy>resource:tnd-resource:myScript.groovy</groovy>
        </setHeader>
        <to uri="log:test?showHeaders=true"/>
    </route>
    
</routes>

Many route can use the same groovy code.

In case of resource update during the route execution, the route must be restarted to take into account the code change.

 

 

Related Links