This topic cost me a few hours. It is basically how to achieve XML transformation when your original XML file contains a DTD reference that cannot be resolved from your system.
My DTD reference looked like this:
<!DOCTYPE root-element SYSTEM "../dtd/core.dtd"> |
<!DOCTYPE root-element SYSTEM "../dtd/core.dtd">
and the route was simply:
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="file:data/inbox"/>
<to uri="xslt://xslt/transformation.xsl"/>
<to uri="file:data/outbox"/>
</route>
</camelContext> |
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="file:data/inbox"/>
<to uri="xslt://xslt/transformation.xsl"/>
<to uri="file:data/outbox"/>
</route>
</camelContext>
The Camel transformation was always complaining about the missing DTD because it was looking for it in the filesystem instead of the bundle.
There exist many hints on the net but none of them really helped (e.g. using a CatalogResolver). So I decided to tamper my Camel route and adding a bean inbetween:
<bean id="dtdTransformer" class="de.example.xslt.DtdTransformer"/>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="file:data/inbox"/>
<bean ref="dtdTransformer"/>
<to uri="xslt://xslt/bundesliga.xsl"/>
<to uri="file:data/outbox"/>
</route>
</camelContext> |
<bean id="dtdTransformer" class="de.example.xslt.DtdTransformer"/>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="file:data/inbox"/>
<bean ref="dtdTransformer"/>
<to uri="xslt://xslt/bundesliga.xsl"/>
<to uri="file:data/outbox"/>
</route>
</camelContext>
This DtdTransformer
is a simple class having one method, transform()
:
public static final String DOCTYPE_LINE = "<!DOCTYPE root PUBLIC \"-//PRIVATE//RS//EN\" \"###URI###\">";
public String transform(String body) throws Exception {
URL url = FileFinder.find(getClass(), "dtd/core.dtd");
if (url != null) {
body = body.replaceAll("<!DOCTYPE[^>]*>", DOCTYPE_LINE).replaceAll("###URI###", url.toURI().toString());
}
return body;
} |
public static final String DOCTYPE_LINE = "<!DOCTYPE root PUBLIC \"-//PRIVATE//RS//EN\" \"###URI###\">";
public String transform(String body) throws Exception {
URL url = FileFinder.find(getClass(), "dtd/core.dtd");
if (url != null) {
body = body.replaceAll("<!DOCTYPE[^>]*>", DOCTYPE_LINE).replaceAll("###URI###", url.toURI().toString());
}
return body;
}
The URI will be replaced by looking up the DTD file at runtime, here by using my FileFinder class. Then it continues with replacing the special marker ###URI###
by the real URI from the file found.
Although the solution sounds so simple, it took me quite a while to find out that the DOCTYPE references needs to be a URI and not a file or URL reference.