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.util.ExchangeHelper; 023 import org.apache.commons.logging.Log; 024 import org.apache.commons.logging.LogFactory; 025 026 /** 027 * The processor which sends messages in a loop. 028 * 029 * @version $Revision: 769303 $ 030 */ 031 public class LoopProcessor extends DelegateProcessor { 032 private static final Log LOG = LogFactory.getLog(LoopProcessor.class); 033 034 private final Expression expression; 035 036 public LoopProcessor(Expression expression, Processor processor) { 037 super(processor); 038 this.expression = expression; 039 } 040 041 @Override 042 public void process(Exchange exchange) throws Exception { 043 // Intermediate conversion to String is needed when direct conversion to Integer is not available 044 // but evaluation result is a textual representation of a numeric value. 045 String text = expression.evaluate(exchange, String.class); 046 int count = ExchangeHelper.convertToMandatoryType(exchange, Integer.class, text); 047 048 exchange.setProperty(Exchange.LOOP_SIZE, count); 049 for (int i = 0; i < count; i++) { 050 if (LOG.isDebugEnabled()) { 051 LOG.debug("LoopProcessor: iteration #" + i); 052 } 053 exchange.setProperty(Exchange.LOOP_INDEX, i); 054 super.process(exchange); 055 } 056 } 057 058 @Override 059 public String toString() { 060 return "Loop[for: " + expression + " times do: " + getProcessor() + "]"; 061 } 062 063 public Expression getExpression() { 064 return expression; 065 } 066 }