-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathTraverser.java
300 lines (269 loc) · 10.1 KB
/
Traverser.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package com.cedarsoftware.util;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
/**
* A Java Object Graph traverser that visits all object reference fields and invokes a
* provided callback for each encountered object, including the root. It properly
* detects cycles within the graph to prevent infinite loops. For each visited node,
* complete field information including metadata is provided.
*
* <p>
* <b>Usage Examples:</b>
* </p>
*
* <p><b>Using the Modern API (Recommended):</b></p>
* <pre>{@code
* // Define classes to skip (optional)
* Set<Class<?>> classesToSkip = new HashSet<>();
* classesToSkip.add(String.class);
*
* // Traverse with full node information
* Traverser.traverse(root, classesToSkip, visit -> {
* System.out.println("Node: " + visit.getNode());
* visit.getFields().forEach((field, value) -> {
* System.out.println(" Field: " + field.getName() +
* " (type: " + field.getType().getSimpleName() + ") = " + value);
*
* // Access field metadata if needed
* if (field.isAnnotationPresent(JsonProperty.class)) {
* JsonProperty ann = field.getAnnotation(JsonProperty.class);
* System.out.println(" JSON property: " + ann.value());
* }
* });
* });
* }</pre>
*
* <p><b>Using the Legacy API (Deprecated):</b></p>
* <pre>{@code
* // Define a visitor that processes each object
* Traverser.Visitor visitor = new Traverser.Visitor() {
* @Override
* public void process(Object o) {
* System.out.println("Visited: " + o);
* }
* };
*
* // Create an object graph and traverse it
* SomeClass root = new SomeClass();
* Traverser.traverse(root, visitor);
* }</pre>
*
* <p>
* <b>Thread Safety:</b> This class is <i>not</i> thread-safe. If multiple threads access
* a {@code Traverser} instance concurrently, external synchronization is required.
* </p>
*
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <br><br>
* <a href="http://www.apache.org/licenses/LICENSE-2.0">License</a>
* <br><br>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class Traverser {
/**
* Represents a node visit during traversal, containing the node and its field information.
*/
public static class NodeVisit {
private final Object node;
private final Map<Field, Object> fields;
public NodeVisit(Object node, Map<Field, Object> fields) {
this.node = node;
this.fields = Collections.unmodifiableMap(new HashMap<>(fields));
}
/**
* @return The object (node) being visited
*/
public Object getNode() { return node; }
/**
* @return Unmodifiable map of fields to their values, including metadata about each field
*/
public Map<Field, Object> getFields() { return fields; }
/**
* @return The class of the node being visited
*/
public Class<?> getNodeClass() { return node.getClass(); }
}
/**
* A visitor interface to process each object encountered during traversal.
* <p>
* <b>Note:</b> This interface is deprecated in favor of using {@link Consumer<NodeVisit>}
* with the new {@code traverse} method.
* </p>
*
* @deprecated Use {@link #traverse(Object, Set, Consumer)} instead.
*/
@Deprecated
@FunctionalInterface
public interface Visitor {
/**
* Processes an encountered object.
*
* @param o the object to process
*/
void process(Object o);
}
private final Set<Object> objVisited = Collections.newSetFromMap(new IdentityHashMap<>());
private final Consumer<NodeVisit> nodeVisitor;
private Traverser(Consumer<NodeVisit> nodeVisitor) {
this.nodeVisitor = nodeVisitor;
}
/**
* Traverses the object graph with complete node visiting capabilities.
*
* @param root the root object to start traversal
* @param classesToSkip classes to skip during traversal (can be null)
* @param visitor visitor that receives detailed node information
*/
public static void traverse(Object root, Consumer<NodeVisit> visitor, Set<Class<?>> classesToSkip) {
if (visitor == null) {
throw new IllegalArgumentException("visitor cannot be null");
}
Traverser traverser = new Traverser(visitor);
traverser.walk(root, classesToSkip);
}
private static void traverse(Object root, Set<Class<?>> classesToSkip, Consumer<Object> objectProcessor) {
if (objectProcessor == null) {
throw new IllegalArgumentException("objectProcessor cannot be null");
}
traverse(root, visit -> objectProcessor.accept(visit.getNode()), classesToSkip);
}
/**
* @deprecated Use {@link #traverse(Object, Set, Consumer)} instead.
*/
@Deprecated
public static void traverse(Object root, Visitor visitor) {
if (visitor == null) {
throw new IllegalArgumentException("visitor cannot be null");
}
traverse(root, visit -> visitor.process(visit.getNode()), null);
}
/**
* @deprecated Use {@link #traverse(Object, Set, Consumer)} instead.
*/
@Deprecated
public static void traverse(Object root, Class<?>[] skip, Visitor visitor) {
if (visitor == null) {
throw new IllegalArgumentException("visitor cannot be null");
}
Set<Class<?>> classesToSkip = (skip == null) ? null : new HashSet<>(Arrays.asList(skip));
traverse(root, visit -> visitor.process(visit.getNode()), classesToSkip);
}
private void walk(Object root, Set<Class<?>> classesToSkip) {
if (root == null) {
return;
}
Deque<Object> stack = new LinkedList<>();
stack.add(root);
while (!stack.isEmpty()) {
Object current = stack.pollFirst();
if (current == null || objVisited.contains(current)) {
continue;
}
Class<?> clazz = current.getClass();
if (shouldSkipClass(clazz, classesToSkip)) {
continue;
}
objVisited.add(current);
Map<Field, Object> fields = collectFields(current);
nodeVisitor.accept(new NodeVisit(current, fields));
if (clazz.isArray()) {
processArray(stack, current, classesToSkip);
} else if (current instanceof Collection) {
processCollection(stack, (Collection<?>) current);
} else if (current instanceof Map) {
processMap(stack, (Map<?, ?>) current);
} else {
processFields(stack, current, classesToSkip);
}
}
}
private Map<Field, Object> collectFields(Object obj) {
Map<Field, Object> fields = new HashMap<>();
Collection<Field> allFields = ReflectionUtils.getAllDeclaredFields(obj.getClass());
for (Field field : allFields) {
try {
fields.put(field, field.get(obj));
} catch (IllegalAccessException e) {
fields.put(field, "<inaccessible>");
}
}
return fields;
}
private boolean shouldSkipClass(Class<?> clazz, Set<Class<?>> classesToSkip) {
if (classesToSkip == null) {
return false;
}
for (Class<?> skipClass : classesToSkip) {
if (skipClass.isAssignableFrom(clazz)) {
return true;
}
}
return false;
}
private void processArray(Deque<Object> stack, Object array, Set<Class<?>> classesToSkip) {
int length = Array.getLength(array);
Class<?> componentType = array.getClass().getComponentType();
if (!componentType.isPrimitive()) {
for (int i = 0; i < length; i++) {
Object element = Array.get(array, i);
if (element != null && !shouldSkipClass(element.getClass(), classesToSkip)) {
stack.addFirst(element);
}
}
}
}
private void processCollection(Deque<Object> stack, Collection<?> collection) {
for (Object element : collection) {
if (element != null) {
stack.addFirst(element);
}
}
}
private void processMap(Deque<Object> stack, Map<?, ?> map) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
if (key != null) {
stack.addFirst(key);
}
if (value != null) {
stack.addFirst(value);
}
}
}
private void processFields(Deque<Object> stack, Object object, Set<Class<?>> classesToSkip) {
Collection<Field> fields = ReflectionUtils.getAllDeclaredFields(object.getClass());
for (Field field : fields) {
if (!field.getType().isPrimitive()) {
try {
Object value = field.get(object);
if (value != null && !shouldSkipClass(value.getClass(), classesToSkip)) {
stack.addFirst(value);
}
} catch (IllegalAccessException ignored) {
}
}
}
}
}