MariuszS MariuszS - 24 days ago 6
Java Question

Howto pass XStream reference into camel for marshalling

Sample code from http://camel.apache.org/xstream.html


If you would like to configure the XStream instance used by the Camel for the message transformation, you can simply pass a reference to that instance on the DSL level.


XStream xStream = new XStream();
xStream.aliasField("money", PurchaseOrder.class, "cash");
// new Added setModel option since Camel 2.14
xStream.setModel("NO_REFERENCES");
...

from("direct:marshal").
marshal(new XStreamDataFormat(xStream)).
to("mock:marshaled");


But this code is wrong, because
org.apache.camel.model.dataformat.XStreamDataFormat
constructor accept only String. How to configure custom
com.thoughtworks.xstream.XStream
in camel?

I dont want to use XML, my application is using Spring.

Answer

If you want to have it done fast, instead of going through "marshal" you can redirect to a marshalling "bean" that will do the marhsalling in the way you need.

from(...).bean('marshallingBean').to(...)

Complete code

@Autowired
FooDeserializer fooDeserializer;

@Bean
public RouteBuilder route() {
    return new RouteBuilder() {
        public void configure() {
            from("direct:marshal")
                    .bean(fooDeserializer)
                    .to("mock:marshaled");
        }
    };
}

FooDeserializer.java

@Component
public class FooDeserializer {

    private final XStream xStream;

    public FooDeserializer() {
        xStream = new XStream();
        xStream.aliasField("money", PurchaseOrder.class, "cash");
    }

    public Foo xmlToFoo(String xml) {
        return (Foo) xStream.fromXML(xml);
    }

}