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