Monday, September 8, 2014

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  T convertTo(Class arg0, Exchange arg1, Object arg2)
			throws TypeConversionException {

		StringBuffer result = new StringBuffer();

		Object[] arry = (Object[]) arg2;
		for (Object arr1 : arry) {
			if (arr1 != null) {
				result.append(arr1.toString());
			} else {
				result.append("");
			}
			result.append(",");
		}

		String strResult = result.toString();
		strResult = strResult.substring(0, strResult.length() - 1);
		return (T) (strResult + "\n");

	}
}
  • Add the TypeConverter to the camel context as shown below
  • 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
    You can use the discovery for the Listing one as well instead of the adding the code and the Type Converter will be added at load time instead of runtime

    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.