5

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

gurpal2000
  • 1,004
  • 1
  • 17
  • 35

2 Answers2

4

You cannot use the file component for this, as its intended for reading via java.io.File API - eg regular files on file systems. Also many of the options are for file specific tasks such as read locks, moving files around to avoid reading them again after processing, deleting the file(s), and scan into sub folders etc. All kind of tasks needed when exchanging data via files.

To read resources within JAR files, then you Java API or the stream component.

Claus Ibsen
  • 56,060
  • 7
  • 50
  • 65
0

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");
            }
        };
    }
}
sbg
  • 1
  • 2