001package org.unix4j.unix.sort;
002
003import org.unix4j.context.ExecutionContext;
004import org.unix4j.line.Line;
005import org.unix4j.processor.AbstractLineProcessor;
006import org.unix4j.processor.LineProcessor;
007import org.unix4j.util.sort.*;
008
009import java.util.Comparator;
010
011abstract class AbstractSortProcessor extends AbstractLineProcessor<SortArguments> {
012        
013        private final Comparator<? super Line> comparator;
014
015        public AbstractSortProcessor(SortCommand command, ExecutionContext context, LineProcessor output) {
016                super(command, context, output);
017                this.comparator = initComparator();
018        }
019        
020        protected Comparator<? super Line> getComparator() {
021                return comparator;
022        }
023        
024        private Comparator<? super Line> initComparator() {
025                final SortArguments args = getArguments();
026                final Comparator<? super Line> comparator;
027                if (args.isComparatorSet()) {
028                        comparator = args.getComparator();
029                } else {
030                        if (args.isNumericSort()) {
031                                comparator = DecimalNumberStringComparator.getInstance(getContext().getLocale());
032                        } else if (args.isGeneralNumericSort()) {
033                                comparator = ScientificNumberStringComparator.INSTANCE;
034                        } else if (args.isHumanNumericSort()) {
035                                comparator = UnitsNumberStringComparator.getInstance(getContext().getLocale());
036                        } else if (args.isMonthSort()) {
037                                comparator = MonthStringComparator.getInstance(getContext().getLocale());
038                        } else if (args.isVersionSort()) {
039                                comparator = VersionStringComparator.INSTANCE;
040                        } else {
041                                comparator = new LineComparator(args.isIgnoreCase(), args.isIgnoreLeadingBlanks(), args.isDictionaryOrder());
042                        }
043                }
044                if (args.isReverse()) {
045                        return ReverseOrderComparator.reverse(comparator);
046                }
047                return comparator;
048        }
049
050}