Routing to flow via HTTP Relative Path

Packaging multiple Anypoint API proxies into a single deployment package is sometimes required. This can be done by creating a large project that has everything in it already. But what if you really want to have the proxies implemented independently in their own projects and just want to “grab” the finished flow from its project and drop it into a package with several other proxies?

You could create a custom proxy that has a single inbound HTTP endpoint that examines the request and sends each on to an “outbound HTTP endpoint” workflow depending upon the http.relative.path variable. You could use a choice router to examine relative path and invoke the appropriate flow. If you just want to “drop” the outbound flow into the package, you can eliminate the choice router with a custom java class that routes the message to a flow whose flow name closely matches the relative path. For instance:

package org.mule.httprouter;

import org.mule.api.DefaultMuleException;
import org.mule.api.MuleContext;
import org.mule.api.MuleEvent;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.api.interceptor.Interceptor;
import org.mule.config.i18n.MessageFactory;
import org.mule.construct.Flow;
import org.mule.processor.AbstractInterceptingMessageProcessor;

public class HttpRelativePathRouter extends
		AbstractInterceptingMessageProcessor implements Interceptor {
	private MuleContext muleContext;

	public void setMuleContext(MuleContext context) {
		this.muleContext = context;
	}

	public MuleEvent process(MuleEvent event) throws MuleException {
		MuleMessage message = event.getMessage();
		String flowName = message.getInboundProperty("http.relative.path");
		Flow flow = null;
		while (flowName.length() > 0) {
			//System.out.println("checkflowName: " + flowName);
			flow = (Flow) muleContext.getRegistry().lookupFlowConstruct(
					flowName);
			if (flow == null) {
				int idx = flowName.lastIndexOf("/");
				if (idx <= 0) {
					break;
				}
				flowName = flowName.substring(0, idx);
			} else {
				break;
			}
		}
		if (flow == null) {
			flow = (Flow) muleContext.getRegistry().lookupFlowConstruct(
					"DefaultFlow");
		}
		if (flow == null) {
			throw new DefaultMuleException(
					MessageFactory
							.createStaticMessage("DefaultFlow is not defined"));
		}
		return flow.process(event);
	}
}

Use the following xml to include the interceptor in the inbound HTTP workflow:

<custom-interceptor class="org.mule.httprouter.HttpRelativePathRouter" />
Advertisements