001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.processor;
018
019import java.util.Iterator;
020
021import org.apache.camel.CamelContext;
022import org.apache.camel.Exchange;
023import org.apache.camel.Expression;
024import org.apache.camel.util.ObjectHelper;
025
026/**
027 * Implements a <a href="http://camel.apache.org/dynamic-router.html">Dynamic Router</a> pattern
028 * where the destination(s) is computed at runtime.
029 * <p/>
030 * This implementation builds on top of {@link org.apache.camel.processor.RoutingSlip} which contains
031 * the most logic.
032 *
033 * @version 
034 */
035public class DynamicRouter extends RoutingSlip {
036    
037    public DynamicRouter(CamelContext camelContext) {
038        super(camelContext);
039    }
040
041    public DynamicRouter(CamelContext camelContext, Expression expression, String uriDelimiter) {
042        super(camelContext, expression, uriDelimiter);
043    }
044
045    @Override
046    protected RoutingSlipIterator createRoutingSlipIterator(Exchange exchange) throws Exception {
047        return new DynamicRoutingSlipIterator(expression);
048    }
049
050    /**
051     * The dynamic routing slip iterator.
052     */
053    private final class DynamicRoutingSlipIterator implements RoutingSlipIterator {
054
055        private final Expression slip;
056        private Iterator<?> current;
057
058        private DynamicRoutingSlipIterator(Expression slip) {
059            this.slip = slip;
060        }
061
062        public boolean hasNext(Exchange exchange) {
063            if (current != null && current.hasNext()) {
064                return true;
065            }
066            // evaluate next slip
067            Object routingSlip = slip.evaluate(exchange, Object.class);
068            if (routingSlip == null) {
069                return false;
070            }
071            current = ObjectHelper.createIterator(routingSlip, uriDelimiter);
072            return current != null && current.hasNext();
073        }
074
075        public Object next(Exchange exchange) {
076            return current.next();
077        }
078    }
079}