001package org.unix4j.unix.sort;
002
003import org.unix4j.context.ExecutionContext;
004import org.unix4j.line.Line;
005import org.unix4j.processor.LineProcessor;
006
007import java.util.ArrayList;
008import java.util.Collections;
009
010/**
011 * Line processor for normal in-memory sort using an {@link ArrayList} to cache
012 * and sort the lines.
013 */
014class SortProcessor extends AbstractSortProcessor {
015        
016        private final ArrayList<Line> lineBuffer = new ArrayList<Line>();
017
018        public SortProcessor(SortCommand command, ExecutionContext context, LineProcessor output) {
019                super(command, context, output);
020        }
021
022        @Override
023        public boolean processLine(Line line) {
024                lineBuffer.add(line);
025                return true;//we want all the lines
026        }
027
028        @Override
029        public void finish() {
030                final LineProcessor output = getOutput();
031                Collections.sort(lineBuffer, getComparator());
032                final int size = lineBuffer.size();
033                for (int i = 0; i < size; i++) {
034                        final Line line = lineBuffer.set(i, null);//clear the line in the buffer
035                        if (!output.processLine(line)) {
036                                break;//they want no more lines
037                        }
038                }
039                lineBuffer.clear();
040                output.finish();
041        }
042
043}