package test.org.mule.routing.outbound;

import org.mule.api.ExceptionPayload;
import org.mule.api.MessagingException;
import org.mule.api.MuleMessage;
import org.mule.module.client.MuleClient;
import org.mule.transport.NullPayload;

import test.org.mule.tck.FunctionalTestCase;

public class ChainingRouterTest extends FunctionalTestCase {

    static final String URL = "vm://ChainingRouter";
    static final String OUTBOUND_URL = "vm://OutOnly";

    static final long TIMEOUT = 3000;
    static final long SHORT_TIMEOUT = 500;

    protected String getConfigResources() {
        return "test/org/mule/routing/outbound/ChainingRouterTest-config.xml";
    }

    public void testSend_OK() throws Exception {
        MuleClient client = new MuleClient();
        MuleMessage message = client.send(URL, "abc", null);
        assertEquals("abc", message.getPayload());
        MuleMessage result = client.request(OUTBOUND_URL, TIMEOUT);
        assertEquals("abc", result.getPayload());
    }

    public void testSend_FailureAtComponent() throws Exception {
        MuleClient client = new MuleClient();
        MuleMessage message = client.send(URL, "failure@component", null);
        assertEquals("FAILURE!! (@component)", message.getPayload());
        assertNull(client.request(OUTBOUND_URL, SHORT_TIMEOUT));
    }

    public void testSend_FailureAtExternal() throws Exception {
        MuleClient client = new MuleClient();
        MuleMessage message = client.send(URL, "failure@external", null);
        assertEquals("failure@external", message.getPayload());
        MuleMessage result = client.request(OUTBOUND_URL, TIMEOUT);
        assertEquals("FAILURE!! (@external)", result.getPayload());
    }

    public void testSend_ExceptionAtComponent() throws Exception {
        MuleClient client = new MuleClient();
        MuleMessage message = client.send(URL, "exception@component", null);
        assertEquals(NullPayload.getInstance(), message.getPayload());
        ExceptionPayload ep = message.getExceptionPayload();
        MessagingException me = (MessagingException) ep.getException();
        RuntimeException re = (RuntimeException) me.getCause();
        assertEquals("EXCEPTION!! (@component)", re.getMessage());
        assertNull(client.request(OUTBOUND_URL, SHORT_TIMEOUT));
    }

    public void testSend_ExceptionAtExternal() throws Exception {
        MuleClient client = new MuleClient();
        MuleMessage message = client.send(URL, "exception@external", null);
        assertEquals(NullPayload.getInstance(), message.getPayload());
        ExceptionPayload ep = message.getExceptionPayload();
        MessagingException me = (MessagingException) ep.getException();
        RuntimeException re = (RuntimeException) me.getCause();
        assertEquals("EXCEPTION!! (@external)", re.getMessage());
        assertNull(client.request(OUTBOUND_URL, SHORT_TIMEOUT));
    }

}
