001package org.unix4j.unix.sort;
002
003import org.unix4j.command.ExitValueException;
004import org.unix4j.context.ExecutionContext;
005import org.unix4j.line.Line;
006import org.unix4j.processor.LineProcessor;
007
008/**
009 * Checks whether a file is sorted or not, throws an {@link ExitValueException}
010 * if the file is not sorted.
011 */
012class CheckProcessor extends AbstractSortProcessor {
013
014        private Line lastLine = null;
015        
016        public CheckProcessor(SortCommand command, ExecutionContext context, LineProcessor output) {
017                super(command, context, output);
018        }
019
020        @Override
021        public boolean processLine(Line line) {
022                if (lastLine != null) {
023                        if (getComparator().compare(lastLine, line) > 0) {
024                                throw new ExitValueException("file is not sorted, line: " + line, 1);
025                        }
026                }
027                lastLine = line;
028                return true;//we want all lines
029        }
030
031        @Override
032        public void finish() {
033                getOutput().finish();
034        }
035        
036        /**
037         * Resets the last line, for instance when a new file should be checked.
038         */
039        public void reset() {
040                lastLine = null;
041        }
042
043}