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.builder;
019
020 import java.util.ArrayList;
021 import java.util.List;
022
023 import org.apache.camel.Exchange;
024 import org.apache.camel.processor.DelegateProcessor;
025 import org.apache.camel.Processor;
026 import org.apache.camel.RuntimeCamelException;
027
028 /**
029 * @version $Revision: 519943 $
030 */
031 public class InterceptorBuilder implements ProcessorFactory {
032 private final List<DelegateProcessor> intercepts = new ArrayList<DelegateProcessor>();
033 private final FromBuilder parent;
034 private FromBuilder target;
035
036 public InterceptorBuilder(FromBuilder parent) {
037 this.parent = parent;
038 }
039
040 @Fluent("interceptor")
041 public InterceptorBuilder add(@FluentArg("ref") DelegateProcessor interceptor) {
042 intercepts.add(interceptor);
043 return this;
044 }
045
046 @Fluent(callOnElementEnd=true)
047 public FromBuilder target() {
048 this.target = new FromBuilder(parent);
049 return target;
050 }
051
052 public Processor createProcessor() throws Exception {
053
054 // The target is required.
055 if( target == null )
056 throw new RuntimeCamelException("target provided.");
057
058 // Interceptors are optional
059 DelegateProcessor first=null;
060 DelegateProcessor last=null;
061 for (DelegateProcessor p : intercepts) {
062 if( first == null ) {
063 first = p;
064 }
065 if( last != null ) {
066 last.setNext(p);
067 }
068 last = p;
069 }
070
071 Processor p = target.createProcessor();
072 if( last != null ) {
073 last.setNext(p);
074 }
075 return first == null ? p : first;
076 }
077 }