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 net.sf.ldaptemplate.support.LdapEncoder;
20
21 import org.apache.commons.lang.builder.EqualsBuilder;
22 import org.apache.commons.lang.builder.HashCodeBuilder;
23
24 /***
25 * Abstract superclass for filters to compare values, e.g. EqualsFilter.
26 *
27 * @author Mattias Arthursson
28 */
29 public abstract class CompareFilter extends AbstractFilter {
30
31 private final String attribute;
32
33 private final String value;
34
35 private final String encodedValue;
36
37 public CompareFilter(String attribute, String value) {
38 this.attribute = attribute;
39 this.value = value;
40 this.encodedValue = encodeValue(value);
41 }
42
43 /***
44 * For testing purposes.
45 *
46 * @return the encoded value.
47 */
48 String getEncodedValue() {
49 return encodedValue;
50 }
51
52 /***
53 * Override to perform special encoding in subclass.
54 *
55 * @param value
56 * the value to encode.
57 * @return properly escaped value.
58 */
59 protected String encodeValue(String value) {
60 return LdapEncoder.filterEncode(value);
61 }
62
63 /***
64 * Convenience constructor for int values.
65 *
66 * @param attribute
67 * @param value
68 */
69 public CompareFilter(String attribute, int value) {
70 this.attribute = attribute;
71 this.value = String.valueOf(value);
72 this.encodedValue = LdapEncoder.filterEncode(this.value);
73 }
74
75 /***
76 * @see net.sf.ldaptemplate.support.filter.Filter#encode(java.lang.StringBuffer)
77 */
78 public StringBuffer encode(StringBuffer buff) {
79 buff.append('(');
80 buff.append(attribute).append(getCompareString()).append(encodedValue);
81 buff.append(')');
82
83 return buff;
84 }
85
86 /***
87 * Compares key and value before encoding
88 *
89 * @see net.sf.ldaptemplate.support.filter.Filter#equals(java.lang.Object)
90 */
91 public boolean equals(Object o) {
92 if (o instanceof CompareFilter && o.getClass() == this.getClass()) {
93 CompareFilter that = (CompareFilter) o;
94 EqualsBuilder builder = new EqualsBuilder();
95 builder.append(this.attribute, that.attribute);
96 builder.append(this.value, that.value);
97 return builder.isEquals();
98 } else {
99 return false;
100 }
101 }
102
103 /***
104 * hash attribute and value
105 *
106 * @see net.sf.ldaptemplate.support.filter.Filter#hashCode()
107 */
108 public int hashCode() {
109 HashCodeBuilder builder = new HashCodeBuilder();
110 builder.append(attribute);
111 builder.append(value);
112 return builder.toHashCode();
113 }
114
115 /***
116 * Implement this method in subclass to return a String representing the
117 * operator, e.g. the Equals sign, "=".
118 *
119 * @return the String to use as operator in the comparison for the specific
120 * subclass.
121 */
122 protected abstract String getCompareString();
123
124 }