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.commons.lang3.text.translate;
018    
019    import java.io.IOException;
020    import java.io.Writer;
021    
022    import org.apache.commons.lang3.ArrayUtils;
023    
024    /**
025     * Executes a sequence of translators one after the other. Execution ends whenever 
026     * the first translator consumes codepoints from the input.
027     * 
028     * @since 3.0
029     * @version $Id: AggregateTranslator.java 1088899 2011-04-05 05:31:27Z bayard $
030     */
031    public class AggregateTranslator extends CharSequenceTranslator {
032    
033        private final CharSequenceTranslator[] translators;
034    
035        /**
036         * Specify the translators to be used at creation time. 
037         *
038         * @param translators CharSequenceTranslator array to aggregate
039         */
040        public AggregateTranslator(CharSequenceTranslator... translators) {
041            this.translators = ArrayUtils.clone(translators);
042        }
043    
044        /**
045         * The first translator to consume codepoints from the input is the 'winner'. 
046         * Execution stops with the number of consumed codepoints being returned. 
047         * {@inheritDoc}
048         */
049        @Override
050        public int translate(CharSequence input, int index, Writer out) throws IOException {
051            for (CharSequenceTranslator translator : translators) {
052                int consumed = translator.translate(input, index, out);
053                if(consumed != 0) {
054                    return consumed;
055                }
056            }
057            return 0;
058        }
059    
060    }