001 /** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one or more 004 * contributor license agreements. See the NOTICE file distributed with 005 * this work for additional information regarding copyright ownership. 006 * The ASF licenses this file to You under the Apache License, Version 2.0 007 * (the "License"); you may not use this file except in compliance with 008 * the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 package org.apache.camel; 019 020 import java.util.ArrayList; 021 import java.util.List; 022 023 /** 024 * Implements a Choice structure where one or more predicates are used which if they are true their processors 025 * are used, with a default otherwise clause used if none match. 026 * 027 * @version $Revision: 519941 $ 028 */ 029 public class ChoiceProcessor<E> implements Processor<E> { 030 private List<FilterProcessor<E>> filters = new ArrayList<FilterProcessor<E>>(); 031 private Processor<E> otherwise; 032 033 public ChoiceProcessor(List<FilterProcessor<E>> filters, Processor<E> otherwise) { 034 this.filters = filters; 035 this.otherwise = otherwise; 036 } 037 038 public void onExchange(E exchange) { 039 for (FilterProcessor<E> filterProcessor : filters) { 040 Predicate<E> predicate = filterProcessor.getPredicate(); 041 if (predicate != null) { 042 filterProcessor.getProcessor().onExchange(exchange); 043 return; 044 } 045 } 046 if (otherwise != null) { 047 otherwise.onExchange(exchange); 048 } 049 } 050 051 @Override 052 public String toString() { 053 StringBuilder builder = new StringBuilder("choice{"); 054 boolean first = true; 055 for (FilterProcessor<E> processor : filters) { 056 if (first) { 057 first = false; 058 } 059 else { 060 builder.append(", "); 061 } 062 builder.append("when "); 063 builder.append(processor.getPredicate().toString()); 064 builder.append(": "); 065 builder.append(processor.getProcessor()); 066 } 067 if (otherwise != null) { 068 builder.append(", otherwise: "); 069 builder.append(otherwise); 070 } 071 builder.append("}"); 072 return builder.toString(); 073 } 074 075 public List<FilterProcessor<E>> getFilters() { 076 return filters; 077 } 078 079 public Processor<E> getOtherwise() { 080 return otherwise; 081 } 082 }