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 net.sf.ldaptemplate.support.LdapEncoder;
20  
21  /***
22   * This filter allows the user to specify wildcards.
23   * 
24   * <pre>
25   * LikeFilter filter = new LikeFilter(&quot;cn&quot;, &quot;foo*&quot;);
26   * System.out.println(filter.ecode());
27   * </pre>
28   * 
29   * would resut in: <code>(cn=foo*)</code>
30   * 
31   * @author Anders Henja
32   * @author Mattias Arthursson
33   */
34  public class LikeFilter extends EqualsFilter {
35  
36      public LikeFilter(String attribute, String value) {
37          super(attribute, value);
38      }
39  
40      /***
41       * Encodes a value according to the rules for this filter.
42       * 
43       * @param value
44       *            Value to encode.
45       * @return Encoded value.
46       */
47      protected String encodeValue(String value) {
48          // just return if blank string
49          if (value == null) {
50              return "";
51          }
52  
53          String[] substrings = value.split("//*", -2);
54  
55          if (substrings.length == 1) {
56              return LdapEncoder.filterEncode(substrings[0]);
57          }
58  
59          StringBuffer buff = new StringBuffer();
60          for (int i = 0; i < substrings.length; i++) {
61              buff.append(LdapEncoder.filterEncode(substrings[i]));
62              if (i < substrings.length - 1) {
63                  buff.append("*");
64              } else {
65                  if (substrings[i].equals("")) {
66                      continue;
67                  }
68              }
69          }
70  
71          return buff.toString();
72      }
73  }