001    package org.hackystat.telemetry.analyzer.reducer.util;
002    
003    import org.hackystat.telemetry.analyzer.reducer.TelemetryReducerException;
004    
005    /**
006     * Provides utility functions for handling reducer options.
007     * 
008     * @author (Cedric) Qin Zhang
009     */
010    public class ReducerOptionUtility {
011    
012      /**
013       * Parses boolean reduction option.
014       * 
015       * @param optionIndex The 0-based option position.
016       * @param optionString The option string to be parsed.
017       * @return True or false.
018       * @throws TelemetryReducerException If the option string does not represent a boolean value.
019       */
020      public static boolean parseBooleanOption(int optionIndex, String optionString) 
021          throws TelemetryReducerException {
022        if ("true".equalsIgnoreCase(optionString) || "yes".equalsIgnoreCase(optionString)) {
023          return true; 
024        }
025        else if ("false".equalsIgnoreCase(optionString) || "no".equalsIgnoreCase(optionString)) {
026          return false;
027        }
028        else {
029          throw new TelemetryReducerException("Parameter " + (optionIndex + 1) 
030                                       + " must indicate a boolean value.");
031        }
032      }
033      
034      /**
035       * Parses mode option.
036       * 
037       * @param optionIndex The 0-based option position.
038       * @param modes An array of acceptable strings.
039       * @param modeString The option string to be parsed.
040       * @return The index into modes where modes[index] == modeString (case insensitive).
041       * @throws TelemetryReducerException If no match can be found.
042       */
043      public static int parseModeOption(int optionIndex, String[] modes, String modeString) 
044          throws TelemetryReducerException {
045        for (int i = 0; i < modes.length; i++) {
046          if (modes[i].equalsIgnoreCase(modeString)) {
047            return i;
048          }
049        }
050        //none matching
051        StringBuffer buffer = new StringBuffer(32);
052        buffer.append("Parameter ").append(optionIndex + 1).append(" must be one of "); //NOPMD
053        for (int i = 0; i < modes.length; i++) {
054          buffer.append("'").append(modes[i]).append("'"); //NOPMD
055          buffer.append(i == modes.length - 1 ? "." : ", ");
056        }
057        throw new TelemetryReducerException(buffer.toString());
058      }
059    }