apache-camelspring-camel

Camel read file from classpath resource?


I have a file on the classpath at "resources/file.txt" in a Spring Boot app.

How do i reference this in a Camel route?

I have tried:

from("file:resource:classpath:?fileName=file.txt") and variations on it. Nothing seems to work.

Any workaround here pls?

Thanks


Solution

  • You can use the Simple Language

    However, the file must not contain instructions for the simple language that it cannot execute, e.g. "${foo.bar}".

    In this case, a small Groovy Script will help.

    pom.xml

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-groovy</artifactId>
        <version>${version.camel}</version>
    </dependency>
    

    ReadClasspathResource.groovy

    import java.nio.charset.Charset
    import java.nio.file.Files
    import java.nio.file.Path
    import java.nio.file.Paths
    
    import org.apache.camel.Exchange
    
    if ( ! request.body ) {
        throw new IllegalStateException('ResourcePath in body expected.')
    }
    
    URL url = Exchange.getClass().getResource(request.body)
    Path path = Paths.get(url.toURI())
    result = new String(Files.readAllBytes(path), Charset.forName("UTF-8"))
    

    Save the file in classpath, e.g. /src/main/resources/groovy/ReadClasspathResource.groovy

    CamelReadClasspathResourceTest.java

    /**
     * Read the file /src/main/resources/foobar/Connector.json
     */
    public class CamelReadClasspathResourceTest extends CamelTestSupport
    {
        @Test
        public void run()
            throws Exception
        {
            Exchange exchange = template.send("direct:start", (Processor)null);
    
            Object body = exchange.getMessage().getBody();
            System.out.println("body ("+body.getClass().getName()+"): "+body.toString());
        }
    
        @Override
        protected RouteBuilder createRouteBuilder() {
            return new RouteBuilder() {
                public void configure() {
                    from("direct:start")
                        .setBody().constant("/foobar/Connector.json")
                        .setBody().groovy("resource:classpath:/groovy/ReadClasspathResource.groovy")
                        .to("mock:result");
                }
            };
        }
    }