View Javadoc

1   /*
2    * Copyright 2002-2005 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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(&quot;cn&quot;,
31   *         &quot;Some CN&quot;);
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          // blank string means just ONE star
57          if (StringUtils.isBlank(value)) {
58              return "*";
59          }
60  
61          // trim value, we will add in stars first and last anywhay
62          value = value.trim();
63  
64          // filter encode so that any stars etc. are preserved
65          String filterEncoded = LdapEncoder.filterEncode(value);
66  
67          // Now replace all whitespace with stars
68          Matcher m = starReplacePattern.matcher(filterEncoded);
69  
70          // possibly 2 longer (stars at ends)
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  }