Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

camel route: read xml into pojo and write it back into xml file

I was looging for some time now, but since a lot of configuration files are in xml it's hard to find some answers to my question.

What would I like to do? Using a caml route I want to read in an xml file and put it into a POJO. Here I want to analyze it. At the end I want to write a different xml file (POJO) as an answer into an out folder.

My problem is, that I don't know how to tell camel to parse the xml file body into my POJO.

A short example what I did until know:

My camel route:

from("file:data/in")
                    .marshal().xstream()
                    .bean(XmlToBeanAndBackBean.class)
                    .unmarshal().xstream()
                    .to("file:data/out");

My POJO:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class XmlFilePojo {

     @XmlAnyAttribute
     private String name;
     @XmlElement(name = "the_age")
     private int theAge;

     public void setName(String name) {
         this.name = name;
     }
}

And my Bean which is used in the camel route:

@Component
public class XmlToBeanAndBackBean {

    public XmlFilePojo transformXmlObject(XmlFilePojo xmlFilePojo){
        XmlFilePojo returnPojo = xmlFilePojo;
        returnPojo.setName("merkur");
        return returnPojo;
    }
}

I think that my error is in the camel route which camel trys to converting the xml file into the XmlFilePojo Object.

When I try to run it I get the following error:

Caused by: org.apache.camel.InvalidPayloadException: No body available of type: XmlFilePojo but has value: [B@659392cd of type: byte[] on: simple.xml. Caused by: No type converter available to convert from type: byte[] to the required type: XmlFilePojo with value [B@659392cd. Exchange[simple.xml]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: byte[] to the required type: XmlFilePojo with value [B@659392cd]

Since I don't have a byte[] in my file I don't know how to handle this. Hope someone has an answer.

like image 845
David Avatar asked Feb 10 '23 04:02

David


1 Answers

Just add camel-jaxb to the classpath and it can do the automatic xml <--> pojo conversition, when you are using JAXB annotations on your POJOs. Just write your bean code using the POJOs.

Then the route is simple

from("file:data/in")
    .bean(XmlToBeanAndBackBean.class)
    .to("file:data/out");
  • http://camel.apache.org/jaxb
like image 181
Claus Ibsen Avatar answered Feb 13 '23 02:02

Claus Ibsen