(Quick Reference)

6 Message Converters - Reference Documentation

Authors: Bud Byrd

Version: 3.1.3

Table of Contents

6 Message Converters

Message converters are classes that are responsible for converting objects to and from byte arrays. The plugin provides 4 built-in converters that cover basic types:
  • Integer
  • Map
  • List
  • GString
  • String

These converters allow message handlers to consume and return data without having to convert that data themselves. They are also used with the RabbitMessagePublisher class.

6.1 Custom Message Converters

The plugin provides a way for authors to create their own message converters. A custom message converter must be placed in the grails-app/rabbit-converters path, and must end with Converter.groovy.

Message converters should extend the MessageConverter abstract class. MessageConverter is a generic class, meaning when extending it, you need to pass it the object class type the message converter will be responsible for converting.

A message converter can notify the plugin just what abilities it has. Specifically, there are methods that return whether it can convert an object to or from a byte array. A message converter need not provide two-way conversion.

Message converters may also provide the plugin with a MIME-type that is typically indicative of the object type it is responsible for. It does not make sense for all object types to have a MIME-type associated with it, but this is useful to give the plugin hints if the conversion mode is set to attempt conversion only based on the content-type property a message contains.

Below is an example converter for the String object type. Custom converters should follow the same format.

import com.budjb.rabbitmq.converter.MessageConverter

class StringMessageConverter extends MessageConverter<String> { /** * Returns whether the message converter can convert a value from a String to a byte array. * * @return boolean */ @Override public boolean canConvertFrom() { return true }

/** * Returns whether the message converter can convert a value from a byte array to a String. * * @return boolean */ @Override public boolean canConvertTo() { return true }

/** * Converts a value from a byte array to a String. * * @param input Value to convert. * @return Value converted to a String, or null if the conversion failed. */ @Override public String convertTo(byte[] input) { return new String(input) }

/** * Converts a value from a String to a byte array. * * @param input Value to convert. * @return Value converted to a byte array, or null if the conversion failed.. */ @Override public byte[] convertFrom(String input) { return input.getBytes() }

/** * The MIME-type typically associated with the object type, if one exists. * * @return MIME-type typically associated with this object type, or null if one does not exist. */ @Override public String getContentType() { return 'text/plain' }

}