1 16 package org.apache.cocoon.forms.util; 17 18 import java.util.AbstractMap ; 19 import java.util.AbstractSet ; 20 import java.util.ArrayList ; 21 import java.util.Iterator ; 22 import java.util.List ; 23 import java.util.Map ; 24 import java.util.NoSuchElementException ; 25 import java.util.Set ; 26 27 32 public class CombiningMap extends AbstractMap { 33 34 private List maps = new ArrayList (); 35 private boolean locked = false; 36 37 46 public CombiningMap add(Map map) { 47 if (locked) { 48 throw new IllegalStateException ("Cannot add new Maps to a CombiningMap once it has been iterated"); 49 } 50 maps.add(map); 51 52 return this; 53 } 54 55 public Object get(Object key) { 56 for (int i = 0; i < maps.size(); i++) { 58 Map map = (Map )maps.get(i); 59 Object result = map.get(key); 60 61 if (result != null) { 62 return result; 63 } 64 65 if (map.containsKey(key)) { 66 return null; 67 } 68 } 69 70 return null; 71 } 72 73 public boolean containsKey(Object key) { 74 for (int i = 0; i < maps.size(); i++) { 76 Map map = (Map )maps.get(i); 77 if (map.containsKey(key)) { 78 return true; 79 } 80 } 81 return false; 82 } 83 84 public Set entrySet() { 85 locked = true; 86 return new CombiningEntrySet(); 87 } 88 89 private class CombiningEntrySet extends AbstractSet { 90 91 public Iterator iterator() { 92 return new CombiningIterator(); 93 } 94 95 99 public int size() { 100 101 int size = 0; 102 Iterator iter = iterator(); 103 while (iter.hasNext()) { 104 size++; 105 iter.next(); 106 } 107 return size; 108 } 109 } 110 111 private class CombiningIterator implements Iterator { 112 113 private int index; 114 private Iterator delegate; 115 private Map.Entry next; 116 117 public CombiningIterator() { 118 if (!maps.isEmpty()) { 120 delegate = ((Map )maps.get(0)).entrySet().iterator(); 121 if (delegate.hasNext()) { 122 next = (Map.Entry )delegate.next(); 123 } 124 } 125 126 } 127 public boolean hasNext() { 128 return next != null; 129 } 130 131 public Object next() { 132 if (next == null) { 133 throw new NoSuchElementException (); 134 } 135 Object result = next; 136 fetchNext(); 137 return result; 138 } 139 140 public void remove() { 141 throw new UnsupportedOperationException (); 142 } 143 144 private void fetchNext() { 145 boolean skip; 146 do { 147 while (delegate != null && !delegate.hasNext()) { 149 index++; 151 if (index < maps.size()) { 152 delegate = ((Map )maps.get(index)).entrySet().iterator(); 153 } else { 154 next = null; 156 delegate = null; 157 return; 158 } 159 } 160 161 next = (Map.Entry )delegate.next(); 163 164 Object key = next.getKey(); 166 skip = false; 167 for (int i = 0; i < index-1; i++) { 168 if (((Map )maps.get(i)).containsKey(key)) { 169 skip = true; 170 continue; 171 } 172 } 173 } while(skip); 174 } 175 } 176 } 177 | Popular Tags |