01: /*
02: * GeoTools - OpenSource mapping toolkit
03: * http://geotools.org
04: * (C) 2002-2006, GeoTools Project Managment Committee (PMC)
05: *
06: * This library is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU Lesser General Public
08: * License as published by the Free Software Foundation;
09: * version 2.1 of the License.
10: *
11: * This library is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14: * Lesser General Public License for more details.
15: */
16: package org.geotools.xml.impl;
17:
18: import java.util.ArrayList;
19: import java.util.HashMap;
20: import java.util.List;
21:
22: import org.eclipse.xsd.XSDTypeDefinition;
23:
24: public class TypeWalker {
25:
26: /**
27: * Cached type hieracty
28: */
29: HashMap/*<XSDTypeDefinition,List>*/cache = new HashMap();
30:
31: /**
32: * Walks from the bottom of the type hierachy to the top.
33: */
34: public void walk(XSDTypeDefinition base, Visitor visitor) {
35: List types = types(base);
36: for (int i = 0; i < types.size(); i++) {
37: XSDTypeDefinition type = (XSDTypeDefinition) types.get(i);
38: //do the visit, if visitor returns false, break out
39: if (!visitor.visit(type)) {
40: break;
41: }
42: }
43: }
44:
45: /**
46: * Walks from the top of the type hierachy to the bottom.
47: *
48: */
49: public void rwalk(XSDTypeDefinition base, Visitor visitor) {
50:
51: List types = types(base);
52: for (int i = types.size() - 1; i > -1; i--) {
53: XSDTypeDefinition type = (XSDTypeDefinition) types.get(i);
54: //do the visit, if visitor returns false, break out
55: if (!visitor.visit(type)) {
56: break;
57: }
58: }
59:
60: }
61:
62: private List types(XSDTypeDefinition base) {
63:
64: List types = (List) cache.get(base);
65: if (types == null) {
66: types = new ArrayList();
67: XSDTypeDefinition type = base;
68: while (type != null) {
69: types.add(type);
70:
71: //get the next type
72: if (type.equals(type.getBaseType())) {
73: break;
74: }
75:
76: type = type.getBaseType();
77: }
78:
79: cache.put(base, types);
80: }
81:
82: return types;
83:
84: }
85:
86: public static interface Visitor {
87: /**
88: * Supplies the current type to the visitor.
89: *
90: * @param type The current type.
91: *
92: * @return True to signal that the walk should continue, false to
93: * signal the walk should stop.
94: */
95: boolean visit(XSDTypeDefinition type);
96: }
97: }
|