1 package net.sourceforge.jenesis4java.impl.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 import java.util.List;
26
27 import net.sourceforge.jenesis4java.Codeable;
28 import net.sourceforge.jenesis4java.ReplacingVisitor;
29
30 public class VisitorUtils {
31
32 public static <T extends Codeable> void visit(List<T> vs, Codeable parent, ReplacingVisitor visitor) {
33 visitList(vs, parent, visitor);
34 }
35
36 private static <T extends Codeable> void visitList(List<T> listOfCodeables, Codeable parent, ReplacingVisitor visitor) {
37 for (int index = 0; listOfCodeables != null && index < listOfCodeables.size();) {
38 T element = visit(listOfCodeables.get(index), parent, visitor);
39 if (element == null) {
40 listOfCodeables.remove(index);
41 } else {
42 listOfCodeables.set(index, element);
43 ++index;
44 }
45 }
46 }
47
48 public static Object visit(Object o, Codeable parent, ReplacingVisitor visitor) {
49 if (o != null) {
50 if (o.getClass().isArray()) {
51 visitArray((Codeable[]) o, parent, visitor);
52 } else if (o instanceof List) {
53 visitList((List<? extends Codeable>) o, parent, visitor);
54 } else {
55 o = visitSingle((Codeable) o, parent, visitor);
56 }
57 }
58 return o;
59 }
60
61 public static <T extends Codeable> T visit(T codeable, Codeable parent, ReplacingVisitor visitor) {
62 return visitSingle(codeable, parent, visitor);
63 }
64
65 private static <T extends Codeable> T visitSingle(T current, Codeable parent, ReplacingVisitor visitor) {
66 return (T) visitor.visitReplace(current, parent);
67 }
68
69 public static <T extends Codeable> void visit(T[] vs, Codeable parent, ReplacingVisitor visitor) {
70 visitArray(vs, parent, visitor);
71 }
72
73 private static <T extends Codeable> void visitArray(T[] vs, Codeable parent, ReplacingVisitor visitor) {
74 for (int index = 0; vs != null && index < vs.length; index++) {
75 T element = visitSingle(vs[index], parent, visitor);
76 vs[index] = element;
77 }
78 }
79 }