1 package org.esigate.util; 2 3 import java.util.Set; 4 import java.util.TreeSet; 5 6 /** 7 * A list that contains some String tokens and is intended to be used as a black list or white list. Methods "add" and 8 * "remove" support single String tokens, comma-separated lists and "*" wildcard expression. The list is 9 * case-insensitive. 10 * 11 * @author Francois-Xavier Bonnet 12 * 13 */ 14 public class FilterList { 15 private Set<String> set = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); 16 private boolean defaultContains = false; 17 18 /** 19 * Add some tokens to the list. By default the list is empty. If the list already contains the added tokens or 20 * everything, this method will have no effect. 21 * 22 * @param toAdd 23 * String token to add to the list. This argument can be: 24 * <ul> 25 * <li>A single String token</li> 26 * <li>* (in this case the list will then act as if it contained any token but you will be able to make 27 * except some tokens using the remove method)</li> 28 * </ul> 29 */ 30 public void add(String toAdd) { 31 if (toAdd.contains("*")) { 32 set.clear(); 33 defaultContains = true; 34 } else { 35 if (!defaultContains) { 36 set.add(toAdd); 37 } else { 38 set.remove(toAdd); 39 } 40 } 41 } 42 43 /** 44 * Remove some tokens from the list. If the list is already empty or does not contains the tokens, this method will 45 * have no effect. 46 * 47 * @param toRemove 48 * String tokens to add to the list. This argument can be: 49 * <ul> 50 * <li>A single String token</li> 51 * <li>* (in this case the list will then be empty again)</li> 52 * </ul> 53 */ 54 public void remove(String toRemove) { 55 if (toRemove.contains("*")) { 56 set.clear(); 57 defaultContains = false; 58 } else { 59 if (defaultContains) { 60 set.add(toRemove); 61 } else { 62 set.remove(toRemove); 63 } 64 } 65 } 66 67 /** 68 * @param token 69 * @return true if the list contains the token 70 */ 71 public boolean contains(String token) { 72 if (defaultContains) { 73 return !set.contains(token); 74 } else { 75 return set.contains(token); 76 } 77 } 78 }