package com.example.mule.transformer;

import java.io.UnsupportedEncodingException;

import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;

public class ToByteArray extends AbstractTransformer {

    static final String TARGET_ENCODING = "UTF-8";

    static final byte[] EMPTY = new byte[0];

    public ToByteArray() {
        registerSourceType(String.class);
        registerSourceType(byte[].class);
        //setReturnClass(byte[].class);
    }

    protected Object doTransform(Object src, String encoding)
            throws TransformerException {
        if (src == null) {
            return EMPTY;
        }
        try {
            String s;
            if (src instanceof String) {
                s = (String) src;
            } else {
                s = toString((byte[]) src, encoding);
            }
            if (!s.startsWith("<?xml")) {
                return src;
            }
            return toByteArray(s);
        } catch (Exception e) {
            throw new TransformerException(this, e);
        }
    }

    String toString(byte[] bytes, String encoding)
            throws UnsupportedEncodingException {
        return new String(bytes, encoding);
    }

    byte[] toByteArray(String s) {
        try {
            return s.getBytes(TARGET_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }

}
