Merge Sort Result Processor

This result processor implementation sorts the results from the MergeSortProcedure, which returns a single result set.

package examples;

import com.vmware.sqlfire.*;
import java.sql.*;
import java.util.*;

public class MergeSortProcessor implements ProcedureResultProcessor {
  
  private ProcedureProcessorContext context;
      
  public void init(ProcedureProcessorContext context) {
    this.context = context;
  }
  
  public Object[] getOutParameters() {
    throw new AssertionError("this procedure has no out parameters");    
  }
  
  public Object[] getNextResultRow(int resultSetNumber)
  throws InterruptedException {
    // this procedure deals with only result set number 1
    assert resultSetNumber == 1;
    IncomingResultSet[] inSets = context.getIncomingResultSets(1);
    Object[] lesserRow = null;
    Comparator cmp = getComparator();
    
    IncomingResultSet setWithLeastRow = null;
    for (IncomingResultSet inSet : inSets) {
      Object[] nextRow = inSet.waitPeekRow(); // blocks until row is available
      if (nextRow == IncomingResultSet.END_OF_RESULTS) {
        // no more rows in this incoming results
        continue;
      }
      // find the least row so far
      if (lesserRow == null || cmp.compare(nextRow, lesserRow) <= 0) {
        lesserRow = nextRow;
        setWithLeastRow = inSet;
      }
    }
    
    if (setWithLeastRow != null) {
      // consume the lesserRow by removing lesserRow from the incoming result set
      Object[] takeRow = setWithLeastRow.takeRow();
      assert takeRow == lesserRow;
    }
    
    // if lesserRow is null, then there are no more rows in any incoming results
    return lesserRow;
  }
  
  public boolean getMoreResults(int nextResultSetNumber) {
    return false; // only one result set
  }
  
  public void close() {
    this.context = null;
  }
  
  /** Return an appropriate Comparator for sorting the rows */
  private Comparator<Object[]> getComparator() {
    // return an appropriate comparator for the rows
    throw new UnsupportedOperationException("comparator not implemented");
  }
}