001package org.unix4j.io;
002
003import org.unix4j.line.Line;
004
005import java.util.Arrays;
006import java.util.List;
007
008/**
009 * An input composed from multiple other inputs returning all lines of the first
010 * input, then all lines of the of the second input etc.
011 */
012public class CompositeInput extends AbstractInput {
013
014        private int index;
015        private final List<? extends Input> inputs;
016
017        /**
018         * Constructor with inputs to combine.
019         * 
020         * @param inputs
021         *            the inputs to combine
022         */
023        public CompositeInput(Input... inputs) {
024                this(Arrays.asList(inputs));
025        }
026
027        /**
028         * Constructor with inputs to combine.
029         * 
030         * @param inputs
031         *            the inputs to combine
032         */
033        public CompositeInput(List<? extends Input> inputs) {
034                this.inputs = inputs;
035        }
036
037        @Override
038        public boolean hasMoreLines() {
039                while (index < inputs.size()) {
040                        if (inputs.get(index).hasMoreLines()) {
041                                return true;
042                        }
043                        index++;
044                }
045                return false;
046        }
047
048        @Override
049        public Line readLine() {
050                if (hasMoreLines()) {
051                        return inputs.get(index).readLine();
052                }
053                return null;
054        }
055
056        /**
057         * Invokes close of all component input objects.
058         */
059        @Override
060        public void close() {
061                for (final Input input : inputs) {
062                        input.close();
063                }
064        }
065
066        @Override
067        public String toString() {
068                return getClass().getSimpleName() + "(inputs=" + inputs + ")";
069        }
070}