1 4 package org.oddjob.designer.factory; 5 6 import java.util.ArrayList ; 7 import java.util.HashMap ; 8 import java.util.Iterator ; 9 import java.util.List ; 10 import java.util.Map ; 11 12 13 14 public class SimpleHierarchy { 15 16 private String name; 17 private final Class of; 18 private final List parts = new ArrayList (); 19 private final Map nodes = new HashMap (); 20 21 public SimpleHierarchy(String name, Class of) { 22 this.name = name; 23 this.of = of; 24 } 25 26 public SimpleHierarchy(Class of) { 27 this.of = of; 28 } 29 30 public int size() { 31 return parts.size(); 32 } 33 34 public String getName() { 35 return this.name; 36 } 37 38 public SimpleHierarchy setName(String name) { 39 this.name = name; 40 return this; 41 } 42 43 public SimpleHierarchy addLeaf(Object child) { 44 if (child == null) { 45 throw new IllegalArgumentException ("Can not add a null child!"); 46 } 47 if (!of.isInstance(child)) { 48 throw new IllegalArgumentException ( 49 "Can not add a child of type " + child.getClass().getName() 50 + " to a hierarchy of type " + of.getName()); 51 } 52 parts.add(child); 53 return this; 54 } 55 56 public SimpleHierarchy addToHierarchy(String named, Object child) { 57 if (named == null) { 58 throw new IllegalArgumentException ("Can not add a null branch!"); 59 } 60 SimpleHierarchy node = (SimpleHierarchy) nodes.get(named); 61 if (node == null) { 62 node = new SimpleHierarchy(named, of); 63 nodes.put(named, node); 64 parts.add(node); 65 } 66 node.addLeaf(child); 67 return this; 68 } 69 70 public SimpleHierarchy addHierarchy(SimpleHierarchy hierarchy) { 71 if (hierarchy == null) { 72 throw new IllegalArgumentException ("Can not add a null branch!"); 73 } 74 SimpleHierarchy node = (SimpleHierarchy) nodes.get(hierarchy.getName()); 75 if (node != null) { 76 throw new IllegalArgumentException ("Hierarchy " + hierarchy.getName() 77 + " already exists!"); 78 } 79 nodes.put(hierarchy.getName(), hierarchy); 80 parts.add(hierarchy); 81 return this; 82 } 83 84 public void iterate(HierarchyVisitor v) { 85 for (Iterator it = parts.iterator(); it.hasNext(); ) { 86 Object o = it.next(); 87 if (o instanceof SimpleHierarchy) { 88 v.onHierarchy((SimpleHierarchy)o); 89 } 90 else { 91 v.onLeaf( o); 92 } 93 } 94 } 95 96 public SimpleHierarchy convert(final HierarchyConversion conversion, final Class of) { 97 98 SimpleHierarchy to = new SimpleHierarchy(name, of); 99 class Converter implements HierarchyVisitor { 100 final SimpleHierarchy current; 101 Converter(SimpleHierarchy current) { 102 this.current = current; 103 } 104 105 public void onLeaf(Object leaf) { 106 Object after = conversion.convert(leaf); 107 current.addLeaf(after); 108 } 109 112 public void onHierarchy(SimpleHierarchy hierarchy) { 113 current.addHierarchy(hierarchy.convert(conversion, of)); 114 } 115 } 116 iterate(new Converter(to)); 117 return to; 118 } 119 } | Popular Tags |