1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.sf.ldaptemplate.support.filter;
18
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
21
22 import net.sf.ldaptemplate.support.LdapEncoder;
23
24 import org.apache.commons.lang.StringUtils;
25
26 /***
27 * This filter takes a automatically converts all whitespace to * wildcards.
28 *
29 * <pre>
30 * WhitespaceWildcardsFilter filter = new WhitespaceWildcardsFilter("cn",
31 * "Some CN");
32 * System.out.println(filter.ecode());
33 * </pre>
34 *
35 * would resut in: <code>(cn=*Some*CN*)</code>
36 *
37 * @author Adam Skogman
38 * @author Mattias Arthursson
39 */
40 public class WhitespaceWildcardsFilter extends EqualsFilter {
41 private static Pattern starReplacePattern = Pattern.compile("//s+");
42
43 public WhitespaceWildcardsFilter(String attribute, String value) {
44 super(attribute, value);
45 }
46
47 /***
48 * Encodes a value according to the rules for this filter.
49 *
50 * @param value
51 * Value to encode.
52 * @return Encoded value.
53 */
54 protected String encodeValue(String value) {
55
56
57 if (StringUtils.isBlank(value)) {
58 return "*";
59 }
60
61
62 value = value.trim();
63
64
65 String filterEncoded = LdapEncoder.filterEncode(value);
66
67
68 Matcher m = starReplacePattern.matcher(filterEncoded);
69
70
71 StringBuffer buff = new StringBuffer(value.length() + 2);
72
73 buff.append('*');
74
75 while (m.find()) {
76 m.appendReplacement(buff, "*");
77 }
78 m.appendTail(buff);
79
80 buff.append('*');
81
82 return buff.toString();
83 }
84 }