JAL-2835 spike updated with latest
[jalview.git] / src / jalview / util / matcher / KeyedMatcher.java
1 package jalview.util.matcher;
2
3 import java.util.function.Function;
4
5 /**
6  * An immutable class that models one or more match conditions, each of which is
7  * applied to the value obtained by lookup given the match key.
8  * <p>
9  * For example, the value provider could be a SequenceFeature's attributes map,
10  * and the conditions might be
11  * <ul>
12  * <li>CSQ contains "pathological"</li>
13  * <li>AND</li>
14  * <li>AF <= 1.0e-5</li>
15  * </ul>
16  * 
17  * @author gmcarstairs
18  *
19  */
20 public class KeyedMatcher implements KeyedMatcherI
21 {
22   private static final String COLON = ":";
23
24   final private String[] key;
25
26   final private MatcherI matcher;
27
28   /**
29    * Constructor given a key, a test condition and a match pattern
30    * 
31    * @param cond
32    * @param pattern
33    * @param theKey
34    */
35   public KeyedMatcher(Condition cond, String pattern, String... theKey)
36   {
37     key = theKey;
38     matcher = new Matcher(cond, pattern);
39   }
40
41   /**
42    * Constructor given a key, a test condition and a numerical value to compare
43    * to. Note that if a non-numerical condition is specified, the float will be
44    * converted to a string.
45    * 
46    * @param cond
47    * @param value
48    * @param theKey
49    */
50   public KeyedMatcher(Condition cond, float value, String... theKey)
51   {
52     key = theKey;
53     matcher = new Matcher(cond, value);
54   }
55
56   @Override
57   public boolean matches(Function<String[], String> valueProvider)
58   {
59     String value = valueProvider.apply(key);
60     return matcher.matches(value);
61   }
62
63   @Override
64   public String[] getKey()
65   {
66     return key;
67   }
68
69   @Override
70   public MatcherI getMatcher()
71   {
72     return matcher;
73   }
74
75   /**
76    * Answers a string description of this matcher, suitable for debugging or
77    * logging. The format may change in future.
78    */
79   @Override
80   public String toString()
81   {
82     StringBuilder sb = new StringBuilder();
83     sb.append(String.join(COLON, key)).append(" ")
84             .append(matcher.getCondition().toString()).append(" ");
85     if (matcher.getCondition().isNumeric())
86     {
87       sb.append(matcher.getPattern());
88     }
89     else
90     {
91       sb.append("'").append(matcher.getPattern()).append("'");
92     }
93
94     return sb.toString();
95   }
96 }