Home | History | Annotate | Download | only in jcommander
      1 package com.beust.jcommander;
      2 
      3 import com.beust.jcommander.internal.Maps;
      4 
      5 import java.util.Map;
      6 
      7 /**
      8  * Helper class to perform fuzzy key look ups: looking up case insensitive or
      9  * abbreviated keys.
     10  */
     11 public class FuzzyMap {
     12   interface IKey {
     13     String getName();
     14   }
     15 
     16   public static <V> V findInMap(Map<? extends IKey, V> map, IKey name,
     17       boolean caseSensitive, boolean allowAbbreviations) {
     18     if (allowAbbreviations) {
     19       return findAbbreviatedValue(map, name, caseSensitive);
     20     } else {
     21       if (caseSensitive) {
     22         return map.get(name);
     23       } else {
     24         for (IKey c : map.keySet()) {
     25           if (c.getName().equalsIgnoreCase(name.getName())) {
     26             return map.get(c);
     27           }
     28         }
     29       }
     30     }
     31     return null;
     32   }
     33 
     34   private static <V> V findAbbreviatedValue(Map<? extends IKey, V> map, IKey name,
     35       boolean caseSensitive) {
     36     String string = name.getName();
     37     Map<String, V> results = Maps.newHashMap();
     38     for (IKey c : map.keySet()) {
     39       String n = c.getName();
     40       boolean match = (caseSensitive && n.startsWith(string))
     41           || ((! caseSensitive) && n.toLowerCase().startsWith(string.toLowerCase()));
     42       if (match) {
     43         results.put(n, map.get(c));
     44       }
     45     }
     46 
     47     V result;
     48     if (results.size() > 1) {
     49       throw new ParameterException("Ambiguous option: " + name
     50           + " matches " + results.keySet());
     51     } else if (results.size() == 1) {
     52       result = results.values().iterator().next();
     53     } else {
     54       result = null;
     55     }
     56 
     57     return result;
     58   }
     59 
     60 
     61 }
     62