    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 *      https://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 */
    017package org.apache.commons.text.translate;
    018
    019import java.io.IOException;
    020import java.io.Writer;
    021import java.util.ArrayList;
    022import java.util.List;
    023import java.util.Objects;
    024import java.util.stream.Stream;
    025
    026/**
    027 * Executes a sequence of translators one after the other. Execution ends whenever
    028 * the first translator consumes code points from the input.
    029 *
    030 * @since 1.0
    031 */
    032public class AggregateTranslator extends CharSequenceTranslator {
    033
    034    /**
    035     * Translator list.
    036     */
    037    private final List<CharSequenceTranslator> translators = new ArrayList<>();
    038
    039    /**
    040     * Specify the translators to be used at creation time.
    041     *
    042     * @param translators CharSequenceTranslator array to aggregate.
    043     */
    044    public AggregateTranslator(final CharSequenceTranslator... translators) {
    045        if (translators != null) {
    046            Stream.of(translators).filter(Objects::nonNull).forEach(this.translators::add);
    047        }
    048    }
    049
    050    /**
    051     * The first translator to consume code points from the input is the 'winner'.
    052     * Execution stops with the number of consumed code points being returned.
    053     * {@inheritDoc}
    054     */
    055    @Override
    056    public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
    057        for (final CharSequenceTranslator translator : translators) {
    058            final int consumed = translator.translate(input, index, writer);
    059            if (consumed != 0) {
    060                return consumed;
    061            }
    062        }
    063        return 0;
    064    }
    065
    066}