1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package net.sf.zel.instr.var;
19
20 import net.sf.zel.vm.ParseException;
21 import net.sf.zel.vm.ZExecutionException;
22 import java.util.*;
23 import net.sf.zel.vm.WildCardMatcher;
24 import net.sf.zel.vm.ZCompiler;
25
26
27
28
29
30 public class MatchIterator
31 {
32
33 public static interface DoStuff
34 {
35
36 public void execute(Object obj, List context)
37 throws net.sf.zel.vm.ZExecutionException;
38 }
39
40 public MatchIterator(String matcher) throws ZExecutionException
41 {
42 try
43 {
44 tokens = ZCompiler.getReference(matcher);
45 } catch (ParseException ex)
46 {
47 throw new ZExecutionException("invalid matcher: " + matcher, ex);
48 }
49 }
50 private final transient List tokens;
51 private DoStuff stuffToDo;
52
53
54
55 private final transient java.util.LinkedList currentVar = new LinkedList();
56
57 private void recurse(Object context, Object contextReference, int i)
58 throws ZExecutionException
59 {
60 if (context == null)
61 {
62 return;
63 }
64 if (contextReference != null)
65 currentVar.add(contextReference);
66 if (i >= tokens.size())
67 {
68 stuffToDo.execute(context, currentVar);
69 } else
70 {
71 final Object token = tokens.get(i);
72 if (token.equals("*"))
73 {
74 for (Map.Entry entry : (Set<Map.Entry>) ((Map) context).entrySet())
75 {
76 recurse(entry.getValue(), entry.getKey(), i + 1);
77 }
78 } else if (token instanceof WildCardMatcher)
79 {
80 for (Map.Entry sv : (Set<Map.Entry>) ((Map) context).entrySet())
81 {
82 if (((WildCardMatcher)token).match((String) sv.getKey()))
83 {
84 recurse(sv.getValue(), sv.getKey(), i + 1);
85 }
86 }
87 } else
88 {
89 recurse(((Map) context).get(token),
90 token, i + 1);
91 }
92 }
93 if (contextReference != null)
94 currentVar.removeLast();
95 }
96
97 public void iterate(DoStuff stuff, Map memCTX)
98 throws ZExecutionException
99 {
100 this.stuffToDo = stuff;
101 recurse(memCTX,null, 0);
102 }
103 }