JAL- 2835 support filter on nested attribute keys
[jalview.git] / src / jalview / util / matcher / KeyedMatcherSet.java
1 package jalview.util.matcher;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.function.Function;
6
7 public class KeyedMatcherSet implements KeyedMatcherSetI
8 {
9   List<KeyedMatcherI> matchConditions;
10
11   boolean andConditions;
12
13   /**
14    * Constructor
15    */
16   public KeyedMatcherSet()
17   {
18     matchConditions = new ArrayList<>();
19   }
20
21   @Override
22   public boolean matches(Function<String[], String> valueProvider)
23   {
24     /*
25      * no conditions matches anything
26      */
27     if (matchConditions.isEmpty())
28     {
29       return true;
30     }
31
32     /*
33      * AND until failure
34      */
35     if (andConditions)
36     {
37       for (KeyedMatcherI m : matchConditions)
38       {
39         if (!m.matches(valueProvider))
40         {
41           return false;
42         }
43       }
44       return true;
45     }
46
47     /*
48      * OR until match
49      */
50     for (KeyedMatcherI m : matchConditions)
51     {
52       if (m.matches(valueProvider))
53       {
54         return true;
55       }
56     }
57     return false;
58   }
59
60   @Override
61   public KeyedMatcherSetI and(KeyedMatcherI m)
62   {
63     if (!andConditions && matchConditions.size() > 1)
64     {
65       throw new IllegalStateException("Can't add an AND to OR conditions");
66     }
67     matchConditions.add(m);
68     andConditions = true;
69
70     return this;
71   }
72
73   @Override
74   public KeyedMatcherSetI or(KeyedMatcherI m)
75   {
76     if (andConditions && matchConditions.size() > 1)
77     {
78       throw new IllegalStateException("Can't add an OR to AND conditions");
79     }
80     matchConditions.add(m);
81     andConditions = false;
82
83     return this;
84   }
85
86   @Override
87   public boolean isAnded()
88   {
89     return andConditions;
90   }
91
92   @Override
93   public Iterable<KeyedMatcherI> getMatchers()
94   {
95     return matchConditions;
96   }
97
98   @Override
99   public String toString()
100   {
101     StringBuilder sb = new StringBuilder();
102     boolean first = true;
103     for (KeyedMatcherI matcher : matchConditions)
104     {
105       if (!first)
106       {
107         sb.append(andConditions ? " AND " : " OR ");
108       }
109       first = false;
110       sb.append("(").append(matcher.toString()).append(")");
111     }
112     return sb.toString();
113   }
114
115   @Override
116   public boolean isEmpty()
117   {
118     return matchConditions == null || matchConditions.isEmpty();
119   }
120
121 }