001    /*
002     * LAPIS lightweight structured text processing system
003     *
004     * Copyright (C) 1998-2002 Carnegie Mellon University,
005     * Copyright (C) 2003 Massachusetts Institute of Technology.
006     * All rights reserved.
007     *
008     * This library is free software; you can redistribute it
009     * and/or modify it under the terms of the GNU General
010     * Public License as published by the Free Software
011     * Foundation, version 2.
012     *
013     * LAPIS homepage: http://graphics.lcs.mit.edu/lapis/
014     */
015    
016    
017    package lapisx.enum;
018    import java.util.Enumeration;
019    import java.util.NoSuchElementException;
020    import java.util.Vector;
021    
022    /**
023     * Enumeration which transforms the elements of another enumeration.
024     */
025    public abstract class FilteredEnumeration implements Enumeration {
026        Enumeration e;
027        Object o; // first object waiting to be returned, or null if none
028        Vector v; // other objects yielded and waiting to be returned
029        int i;    // next object to return from v
030    
031        public FilteredEnumeration (Enumeration e) {
032            this.e = e;
033        }
034    
035        public boolean hasMoreElements () { 
036            next ();
037            return o != null;
038        }
039    
040        public Object nextElement () { 
041            next ();
042            if (o == null)
043                throw new NoSuchElementException ();
044            Object result = o;
045            o = null;
046            return result;
047        }
048    
049        void next () {
050            // check if yielded element is waiting to be returned 
051            if (o != null)
052                return;
053    
054            // check in v for other yielded elements
055            if (v != null) {
056                if (i < v.size ()) {
057                    o = v.elementAt (i);
058                    v.setElementAt (null, i);
059                    ++i;
060                } else {
061                    v.setSize (0);
062                    i = 0;
063                }
064            }
065    
066            // transform elements until an element is yielded
067            while (o == null && e.hasMoreElements ())
068                transform (e.nextElement ());
069        }
070    
071        public void yield (Object obj) {
072            if (o == null)
073                o = obj;
074            else {
075                if (v == null)
076                    v = new Vector ();
077                v.addElement (obj);
078            }
079        }
080    
081        public abstract void transform (Object o);
082    }