View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.util.filter;
5   
6   import java.util.ArrayList;
7   import java.util.Arrays;
8   import java.util.List;
9   
10  /**
11   * A base class for Filters which implements behavior using a List of other
12   * Filters.
13   * 
14   * @param <T>
15   *            The underlying type on which the filter applies.
16   */
17  public abstract class AbstractCompoundFilter<T> implements Filter<T> {
18  
19  	protected List<Filter<T>> filters;
20  
21  	public AbstractCompoundFilter() {
22  		filters = new ArrayList<>(2);
23  	}
24  
25  	public AbstractCompoundFilter(Filter<T>... filters) {
26  	    this.filters = Arrays.asList(filters);
27  	}
28  
29  	public List<Filter<T>> getFilters() {
30  		return filters;
31  	}
32  
33  	public void setFilters(List<Filter<T>> filters) {
34  		this.filters = filters;
35  	}
36  
37  	public void addFilter(Filter<T> filter) {
38  		filters.add(filter);
39  	}
40  
41  	protected abstract String getOperator();
42  
43  	public String toString() {
44  		
45  		if (filters.isEmpty()) { return "()"; }
46  		
47  		StringBuilder builder = new StringBuilder();
48  		builder.append('(').append(filters.get(0));
49  		
50  		for (int i = 1; i < filters.size(); i++) {
51  			builder.append(' ').append(getOperator()).append(' ');
52  			builder.append(filters.get(i));
53  		}
54  		builder.append(')');
55  		return builder.toString();
56  	}
57  }