package com.example.mule.interceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mule.DefaultMuleMessage;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.api.interceptor.Interceptor;
import org.mule.api.interceptor.Invocation;

public class TextChecker implements Interceptor {

    Log log = LogFactory.getLog(TextChecker.class);

    public MuleMessage intercept(Invocation invocation)
            throws MuleException {
        MuleMessage message = invocation.getMessage();
        Object payload = message.getPayload();
        if (payload instanceof Object[]) {
            Object[] args = (Object[]) payload;
            if (args.length > 0) {
                return doIntercept(args[0], invocation);
            }
        }
        return doIntercept(payload, invocation);
    }

    MuleMessage doIntercept(Object payload, Invocation invocation)
            throws MuleException {
        if ("error".equals(payload)) {
            log.warn("ERROR!!");
            return new DefaultMuleMessage("ERROR!!");
        }
        if ("exception".equals(payload)) {
            log.warn("EXCEPTION!!");
            throw new RuntimeException("EXCEPTION!!");
        }
        log.debug("OK!!");
        return invocation.invoke();
    }

}
