1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.directory.api.ldap.model.filter;
21
22
23 import java.text.ParseException;
24 import java.util.Comparator;
25 import java.util.List;
26 import java.util.Set;
27 import java.util.TreeSet;
28
29 import org.apache.directory.api.ldap.model.schema.SchemaManager;
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 public class BranchNormalizedVisitor implements FilterVisitor
46 {
47 public Object visit( ExprNode node )
48 {
49 if ( !( node instanceof BranchNode ) )
50 {
51 return null;
52 }
53
54 BranchNode branch = ( BranchNode ) node;
55
56 Comparator<ExprNode> nodeComparator = new NodeComparator();
57
58 Set<ExprNode> set = new TreeSet<ExprNode>( nodeComparator );
59
60 List<ExprNode> children = branch.getChildren();
61
62 for ( ExprNode child : branch.getChildren() )
63 {
64 if ( !child.isLeaf() )
65 {
66 ExprNode newChild = ( ExprNode ) visit( child );
67
68 if ( newChild != null )
69 {
70 set.add( newChild );
71 }
72 }
73 else
74 {
75 set.add( child );
76 }
77 }
78
79 children.clear();
80
81 children.addAll( set );
82
83 return branch;
84 }
85
86
87 public boolean canVisit( ExprNode node )
88 {
89 return node instanceof BranchNode;
90 }
91
92
93 public boolean isPrefix()
94 {
95 return false;
96 }
97
98
99 public List<ExprNode> getOrder( BranchNode node, List<ExprNode> children )
100 {
101 return children;
102 }
103
104
105
106
107
108
109
110
111
112
113
114 public static String getNormalizedFilter( SchemaManager schemaManager, String filter ) throws ParseException
115 {
116 ExprNode originalNode = FilterParser.parse( schemaManager, filter );
117
118 return getNormalizedFilter( originalNode );
119 }
120
121
122
123
124
125
126
127
128
129
130 public static String getNormalizedFilter( ExprNode filter )
131 {
132 BranchNormalizedVisitor visitor = new BranchNormalizedVisitor();
133
134 ExprNode result = ( ExprNode ) visitor.visit( filter );
135
136 return result.toString().trim();
137 }
138
139 static class NodeComparator implements Comparator<ExprNode>
140 {
141 public int compare( ExprNode o1, ExprNode o2 )
142 {
143 StringBuilder buf = new StringBuilder();
144
145 buf.setLength( 0 );
146
147 String s1 = null;
148
149 buf.append( o1.toString() );
150
151 s1 = buf.toString();
152
153 buf.setLength( 0 );
154
155 String s2 = null;
156
157 buf.append( o2.toString() );
158
159 s2 = buf.toString();
160
161 return s1.compareTo( s2 );
162 }
163 }
164 }