JAL-2069 update spike branch 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   final private String key;
23
24   final private MatcherI matcher;
25
26   /**
27    * Constructor given a key, a test condition and a match pattern
28    * 
29    * @param theKey
30    * @param cond
31    * @param pattern
32    */
33   public KeyedMatcher(String theKey, Condition cond, String pattern)
34   {
35     key = theKey;
36     matcher = new Matcher(cond, pattern);
37   }
38
39   /**
40    * Constructor given a key, a test condition and a numerical value to compare
41    * to. Note that if a non-numerical condition is specified, the float will be
42    * converted to a string.
43    * 
44    * @param theKey
45    * @param cond
46    * @param value
47    */
48   public KeyedMatcher(String theKey, Condition cond, float value)
49   {
50     key = theKey;
51     matcher = new Matcher(cond, value);
52   }
53
54   @Override
55   public boolean matches(Function<String, String> valueProvider)
56   {
57     String value = valueProvider.apply(key);
58     return matcher.matches(value);
59   }
60
61   @Override
62   public String getKey()
63   {
64     return key;
65   }
66
67   @Override
68   public MatcherI getMatcher()
69   {
70     return matcher;
71   }
72
73   /**
74    * Answers a string description of this matcher, suitable for debugging or
75    * logging. The format may change in future.
76    */
77   @Override
78   public String toString()
79   {
80     StringBuilder sb = new StringBuilder();
81     sb.append(key).append(" ").append(matcher.getCondition().toString())
82             .append(" ");
83     if (matcher.getCondition().isNumeric())
84     {
85       sb.append(matcher.getPattern());
86     }
87     else
88     {
89       sb.append("'").append(matcher.getPattern()).append("'");
90     }
91
92     return sb.toString();
93   }
94 }