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 */
017 package org.apache.camel.processor;
018
019 import org.apache.camel.Exchange;
020 import org.apache.camel.Expression;
021 import org.apache.camel.Processor;
022 import org.apache.camel.RuntimeCamelException;
023 import org.apache.camel.util.ExchangeHelper;
024 import org.apache.commons.logging.Log;
025 import org.apache.commons.logging.LogFactory;
026
027 /**
028 * The processor which sends messages in a loop.
029 *
030 * @version $Revision: 747062 $
031 */
032 public class LoopProcessor extends DelegateProcessor {
033 private static final Log LOG = LogFactory.getLog(LoopProcessor.class);
034
035 private Expression expression;
036
037 public LoopProcessor(Expression expression, Processor processor) {
038 super(processor);
039 this.expression = expression;
040 }
041
042 @Override
043 public void process(Exchange exchange) throws Exception {
044 // Intermediate conversion to String is needed when direct conversion to Integer is not available
045 // but evaluation result is a textual representation of a numeric value.
046 String text = expression.evaluate(exchange, String.class);
047 Integer value = ExchangeHelper.convertToType(exchange, Integer.class, text);
048 if (value == null) {
049 // TODO: we should probably catch evaluate/convert exception an set is as fault (after fix for CAMEL-316)
050 throw new RuntimeCamelException("Expression \"" + expression + "\" is not convertable to an Integer.");
051 }
052
053 int count = value;
054 exchange.setProperty(Exchange.LOOP_SIZE, count);
055 for (int i = 0; i < count; i++) {
056 if (LOG.isDebugEnabled()) {
057 LOG.debug("LoopProcessor: iteration #" + i);
058 }
059 exchange.setProperty(Exchange.LOOP_INDEX, i);
060 super.process(exchange);
061 }
062 }
063
064 @Override
065 public String toString() {
066 return "Loop[for: " + expression + " times do: " + getProcessor() + "]";
067 }
068
069 public Expression getExpression() {
070 return expression;
071 }
072 }