001package org.unix4j.unix.grep;
002
003import org.unix4j.context.ExecutionContext;
004import org.unix4j.io.FileInput;
005import org.unix4j.io.Input;
006import org.unix4j.line.Line;
007import org.unix4j.line.SimpleLine;
008import org.unix4j.processor.DefaultInputProcessor;
009import org.unix4j.processor.LineProcessor;
010import org.unix4j.util.Counter;
011
012/**
013 * Counts the matching lines and writes the count and the file name to the
014 * output. The matching operation is delegated to the {@link LineMatcher} passed
015 * to the constructor.
016 */
017final class CountMatchingLinesInputProcessor extends DefaultInputProcessor implements LineProcessor {
018        
019        private final ExecutionContext context;
020        private final LineMatcher matcher;
021        private final Counter counter = new Counter();
022        private final LineProcessor output;
023
024        public CountMatchingLinesInputProcessor(GrepCommand command, ExecutionContext context, LineProcessor output, LineMatcher matcher) {
025                this.context = context;
026                this.matcher = matcher;
027                this.output = output;
028        }
029
030        @Override
031        public void begin(Input input, LineProcessor output) {
032                counter.reset();
033        }
034        
035        @Override
036        public boolean processLine(Line line) {
037                if (matcher.matches(line)) {
038                        counter.increment();
039                }
040                return true;// we want to count all the lines
041        }
042        @Override
043        public boolean processLine(Input input, Line line, LineProcessor output) {
044                return processLine(line);
045        }
046
047        @Override
048        public void finish(Input input, LineProcessor output) {
049                final String fileInfo = input instanceof FileInput ? ((FileInput)input).getFileInfo(context.getCurrentDirectory()) : input.toString();
050                output.processLine(new SimpleLine(counter.getCount() + ": " + fileInfo));
051        }
052        
053        @Override
054        public void finish() {
055                output.processLine(new SimpleLine(String.valueOf(counter.getCount())));
056                output.finish();
057        }
058}