简体   繁体   中英

Generating XML file from an object and saving it to a file on the fly with Apache Camel

As the title says, I want to generate an XML file from a class, then copy it to some path using Apache Camel.

I can create a temp file and copy this temp file using Camel, however I would like to do this on the fly, like giving the object to Camel and let it marshall and copy it to the location I want.

First of all the code of my class looks like this:

@XmlRootElement
@XmlType(propOrder = {"name"})
public class Person
{
   private String name;  
   public Person()
   {

   }

   public Person(String name)
   {
      this.name = name;
   }

   @XmlAttribute
   public String getName()
   {
      return this.name;
   }
}

I tried two approaches:

  • Convert the class into XML string and feed it to Camel.
  • Feed the object directly into camel.

Unfortunately I couldn't find any string endpoint in Camel so the below code didn't work:

Person person = new Person("test name");
String personString;
StringWriter sw = new StringWriter();

JAXBContext personContext = JAXBContext.newInstance(Person.class);
Marshaller personMarshaller = personContext.createMarshaller();
personMarshaller.marshal(person, sw);
personString = sw.toString();

from(personString)
.routeId("TestRoute")
.to("file:/apps/test/test.xml");

So my next test was to feed the object directly into Camel seeing that it has a class endpoint:

Person person = new Person("test name");

from("class:" + person)
.routeId("TestRoute")
.marshal().jaxb(Person.class.getPackage().getName().toString())
.to("file:/apps/test/test.xml");

This code failed with the following exception:

Failed to create route TestRoute: Route(TestRoute)[[From[class:com.test.camel... because of Failed to resolve endpoint: class://com.test.camel.Person@21912909 due to: com.test.camel.Person@21912909: org.apache.camel.FailedToCreateRouteException: Failed to create route TestRoute: Route(TestRoute)[[From[class:com.test.camel... because of Failed to resolve endpoint: class://com.test.camel.Person@21912909 due to: com.test.camel.Person@21912909

So how do I go about doing this? And what does that error mean? Any help would be appreciated.

Use the direct component: http://camel.apache.org/direct . So your route start from direct, and then use ProducerTemplate to call the route from your Java code.

See the getting started guide http://camel.apache.org/getting-started.html http://camel.apache.org/walk-through-an-example.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM