Contact Us 1-800-596-4880

Creating Transformers

Transformers convert message payloads to formats expected by their destinations. Mule ESB provides many standard transformers, which you configure using predefined elements and attributes in your Mule XML configuration file but sometimes is useful to build custom transformers.

The @Transformer Annotation

Annotating a method with @Transformer signals the Mule DevKit to export this method functionality as a transformer. Transformers need to be declared in classes annotated with @Module or @Connector and many transformers can be declared in the one class. It is possible to declare transformers, message processors and message sources in the same class.

The @Transformer annotated method must follow certain rules:

  • it must be static

  • it must be public

  • it must not return void

  • it must not return java.lang.Object

  • it must receive exactly one argument

  • it must be inside a class annotated with @Module or @Connector

Examples

@Transformer(sourceTypes = {String.class})
    public static Character transformStringToChar(Object payload) {
        if (payload instance of String) {
            return ((String) payload).charAt(0);
        }
        return null;
    }
@Transformer
    public static List<URL> stringsToUrls(String input) throws MalformedURLException {
        List<URL> urls = new ArrayList<URL>();
        StringTokenizer tokenizer = new StringTokenizer(input);
        while (tokenizer.hasMoreTokens()) {
            urls.add(new URL(tokenizer.nextToken()));
        }
        return urls;
    }

More Information