Type ConverterIts very common when routing messages from one endpoint to another to need to convert the body payloads from one type to another such as to convert to and from the following common types
The Message interface So in an endpoint you can convert a body to another type via Message message = exchange.getIn(); Document document = message.getBody(Document.class); How Type Conversion worksThe type conversion strategy is defined by the TypeConverter The default implementation, DefaultTypeConverter New in Camel 1.5 The default implementation, DefaultTypeConverter Discovering Type ConvertersThe AnnotationTypeConverterLoader e.g. the following shows how to register a converter from File -> InputStream @Converter public class IOConverter { @Converter public static InputStream toInputStream(File file) throws FileNotFoundException { return new BufferedInputStream(new FileInputStream(file)); } } Static methods are invoked; non-static methods require an instance of the converter object to be created (which is then cached). If a converter requires configuration you can plug in an Injector interface to the DefaultTypeConverter which can construct and inject converter objects via Spring or Guice. We have most of the common converters for common Java types in the org.apache.camel.converter Writing your own Type ConvertersYou are welcome to write your own converters. Remember to use the @Converter annotations on the classes and methods you wish to use. Then add the packages to a file called META-INF/services/org/apache/camel/TypeConverter in your jar. Remember to make sure that :-
Encoding support for byte[] and String ConversionAvailable in Camel 1.5 Since Java provides converting the byte[] to String and String to byte[] with the charset name Exchange parameterAvailable in Camel 1.5 The type converter accepts the Exchange as an optional 2nd parameter. This is usable if the type converter for instance needs information from the current exchange. For instance combined with the encoding support its possible for type converters to convert with the configured encoding. An example from camel-core for the byte[] -> String converter: @Converter
public static String toString(byte[] data, Exchange exchange) {
if (exchange != null) {
String charsetName = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
if (charsetName != null) {
try {
return new String(data, charsetName);
} catch (UnsupportedEncodingException e) {
LOG.warn("Can't convert the byte to String with the charset " + charsetName, e);
}
}
}
return new String(data);
}
|