如何在 Camel Restlet 中设置请求主体?

How to set request body in Camel Restlet?

我有一个简单的 Camel get 方法,我想做的就是将正文设置为 XSL 转换的结果。我该怎么做呢? 以下代码无法编译,但它显示了我想要实现的目标:

rest("/api")
    .get("/booksByAuthor/{author}")
    .route()
    .setBody(
        from("file:/conf.xml")
        .setHeader("author",simple("${header.author}"))
        .to("xslt:/transformers/booksByAuthor.xsl")
    );

您可以使用处理器将 body 设置为 xml 文件,然后将其传递给您的 xslt。您不需要在消息 body 中包含文件内容,对于 "xslt:",只需一个文件句柄就足够了。像

    rest("/api")
        .get("/booksByAuthor/{author}")
        .route()
        .process(exchange -> exchange.getIn().setBody(new File("/conf.xml")))
        .to("xslt:/transformers/booksByAuthor.xsl");

作者已经在消息 header 中,因此您无需设置它,您将能够在您的 xslt 中使用

访问它
    <xsl:param name="author"/>
    <xsl:value-of select="$author"/>

我刚刚将处理器编写为 Java 8 lambda,但如果您愿意,您始终可以使用单独的 class。

如果您想将 xml 文件的来源放入消息中,而不是使用文件句柄,您可以使用 pollEnrich 来读取文件。然后,您需要使用聚合策略来确保保留原始消息中的 header。最简单的方法可能只是将带有 xml 的消息中的 body 复制到原始消息中。下面是如何执行此操作的示例。

    rest("/api")
        .get("/booksByAuthor/{author}")
        .route()
        .pollEnrich("file:/?fileName=conf.xml&noop=true", (original, xml) -> {
                original.getIn().setBody(xml.getIn().getBody());
                return original;})
        .to("xslt:/transformers/booksByAuthor.xsl");