Camel Writing a TypeConverter
Using Type Converter Registry and Java DSL
Write your Custom Type Converter by extending the org.apache.camel.support.TypeConverterSupport
The Below Listing provides you a sample of how to do that , this example takes a hypothetical situation where i want to convert a array of objects to a String , nonsensical but nevertheless an example.
package com.sundar.camel.converters; import org.apache.camel.Exchange; import org.apache.camel.TypeConversionException; import org.apache.camel.support.TypeConverterSupport; public class MyConverter extends TypeConverterSupport { @Override public |
context.getTypeConverterRegistry().addTypeConverter(Object[].class, String.class, new TypeConverterSupport()); |
Auto Discovery of Type Converters
Write your Type Converter by using annotations as below
import org.apache.camel.Converter; import com.sundar.camel.db.converter; @Converter public class StringConverter { @Converter public String convertTo(<AnyType> arr){ StringBuffer result = new StringBuffer(); return arr.toString(); } } |
The above type of implementation is dependent on AnnotationTypeConverterLoader which searches the class-path of your project for a file called TypeConverter (META-INF/services/org/apache/camel/
- Create the file and add the FQN of the type converter we just wrote
com.sundar.camel.converters.StringConverter - We can also choose to provide the package name of the class and allow Camel to scan the entire package for the TypeConverters
com.sundar.camel.converters
Now these type Converters can be used as it would like any other converter in Camel The first Converter would be used as below <convertBodyToType type="com.sundar.camel.converters.MyConverter"/> Camel would then invoke the MyConverter to convert the message body The Second Converter would be used as below <convertBodyToType type="java.lang.String"/>Camel would like at the conversions startegies and when the Object Type of the Message
Body matches the Object in the convertTo method , Camel will invoke the StringConverter for the convertsion.