//Model class
MyClass{
String name;
//getters and setters
}
ProcessorClass implements Processor{
process(Exchange exchange){
MyClass myClass = exchange.getIn().getBody(MyClass.class);
print(myClass.getName());
}}
//Inside xyzClass extends RouteBuilder{ configure() {
from()
.unmarshal(new JacksonDataFormat(MyClass.class))
.process(processorClass)
.to()
.end();
I am using camel route for the first time and was unable to understand few things
Where the data (MyClass object and its values) gets stored once unmarshalling (of json payload) happens ?
It gets stored to the message body of the ongoing exchange. Instead of exchange.getIn()
you might want to use exchange.getMessage()
instead.
why is it required to initialize myClass variable inside ProcessorClass to map json data to our model class (MyClass) ?
Mapping has already been done during .unmarshal(new JacksonDataFormat(MyClass.class))
step. The type of message body is of type java.lang.Object so in order to access getName
method of your MyClass
you need to cast the body to MyClass.
You don't really need extra variable for this but it's often cleaner to store the result of cast to a separate variable and do whatever with the variable after.
Otherwise you'd have to do something like this every time you want access public methods and variables of the object:
// Using getBody(Class)
(exchange.getMessage().getBody(MyClass.class)).getName();
// Using basic Java syntax for casting
((MyClass)exchange.getMessage().getBody()).getName();
to access the value present in MyClass.name, we have to do myClass.getName() inside ProcessorClass. Is this the only way to access model class data after unmarshalling ?
No, you could also use bean with method with MyClass as parameter and camel will do the casting automatically when the method gets called.
from("timer:timerName?period=3000")
.setBody(constant(new MyClass("Bob")))
.bean(new MyBean());
class MyBean {
public void someMethod(MyClass myClass) {
if(myClass != null) {
System.out.println(myClass.getName());
} else {
System.out.println("Given MyClass instance was null..");
}
}
}
class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
You could also access it using simple-language.
Alternatively you could also access it with lamda + casting
.setHeader("name").exchange(ex -> {
return ex.getMessage().getBody(MyClass.class).getName();
})
Casting is pretty basic stuff when it comes to Object oriented programming so you might want to do a refresher on that before continuing with Apache Camel.
Since message body of an exchange can hold pretty much anything you'll always need to cast it to actually use it. Either you do it in processor or camel does it automatically in background as with many of the examples above. Same goes for headers and exchange properties.