1 33 34 package bsh; 35 36 import java.util.Enumeration ; 37 import java.util.Vector ; 38 import java.util.Hashtable ; 39 import java.lang.reflect.Array ; 40 41 50 public class CollectionManager 51 { 52 private static CollectionManager manager; 53 54 public synchronized static CollectionManager getCollectionManager() 55 { 56 if ( manager == null 57 && Capabilities.classExists("java.util.Collection") ) 58 { 59 Class clas; 60 try { 61 clas = Class.forName( "bsh.collection.CollectionManagerImpl" ); 62 manager = (CollectionManager)clas.newInstance(); 63 } catch ( Exception e ) { 64 Interpreter.debug("unable to load CollectionManagerImpl: "+e); 65 } 66 } 67 68 if ( manager == null ) 69 manager = new CollectionManager(); 71 return manager; 72 } 73 74 76 public boolean isBshIterable( Object obj ) 77 { 78 try { 80 getBshIterator( obj ); 81 return true; 82 } catch( IllegalArgumentException e ) { 83 return false; 84 } 85 } 86 87 public BshIterator getBshIterator( Object obj ) 88 throws IllegalArgumentException 89 { 90 return new BasicBshIterator( obj ); 91 } 92 93 public boolean isMap( Object obj ) { 94 return obj instanceof Hashtable ; 95 } 96 97 public Object getFromMap( Object map, Object key ) { 98 return ((Hashtable )map).get(key); 99 } 100 101 public Object putInMap( Object map, Object key, Object value ) 102 { 103 return ((Hashtable )map).put(key, value); 104 } 105 106 111 112 115 public static class BasicBshIterator implements BshIterator 116 { 117 Enumeration enumeration; 118 119 129 public BasicBshIterator(Object iterateOverMe) { 130 enumeration = createEnumeration(iterateOverMe); 131 } 132 133 146 protected Enumeration createEnumeration( Object iterateOverMe ) 147 { 148 if(iterateOverMe==null) 149 throw new NullPointerException ("Object arguments passed to " + 150 "the BasicBshIterator constructor cannot be null."); 151 152 if (iterateOverMe instanceof Enumeration ) 153 return (Enumeration )iterateOverMe; 154 155 if (iterateOverMe instanceof Vector ) 156 return ((Vector )iterateOverMe).elements(); 157 158 if (iterateOverMe.getClass().isArray()) { 159 final Object array = iterateOverMe; 160 return new Enumeration () { 161 int index = 0, length = Array.getLength(array); 162 public Object nextElement() { 163 return Array.get(array, index++); 164 } 165 public boolean hasMoreElements() { return index<length; } 166 }; 167 } 168 169 if (iterateOverMe instanceof String ) 170 return createEnumeration(((String )iterateOverMe).toCharArray()); 171 172 if (iterateOverMe instanceof StringBuffer ) 173 return createEnumeration( 174 iterateOverMe.toString().toCharArray()); 175 176 throw new IllegalArgumentException ( 177 "Cannot enumerate object of type "+iterateOverMe.getClass()); 178 } 179 180 185 public Object next() { 186 return enumeration.nextElement(); 187 } 188 189 195 public boolean hasNext() { 196 return enumeration.hasMoreElements(); 197 } 198 } 199 } 200 | Popular Tags |