
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

/** A sample tag for implementing efficient
  * switch statements in JSP custom tags. 
  * This class does some iteration
  */
public abstract class LoopTag extends TagSupport {

    /** A Map of values -> CaseTag instances */
    private Map values = new HashMap();
    
    public LoopTag() {
    }

    
    // Registration API for CaseTag objects
    public void addCase( Object value, CaseTag caseTag ) {
        values.put( value, caseTag );
    }
    
    // Tag interface    
    public int doStart() throws JspException {
        values.clear();
        return EVAL_BODY_INCLUDE;
    }
 
    public int doEndTag() throws JspException {
        Iterator iter = getLoopIterator();
        while ( iter.hasNext() ) {
            Object value = iter.next();
            
            // loop up the case to execute
            CaseTag caseTag = (CaseTag) values.get( value );
            if ( caseTag != null ) {
                // execute the body 
                caseTag.run();
            }
            else {
                // we might want to do a default
                // body here?
            }
        }
        return EVAL_PAGE;
    }
    
    public void release() {
        values = null;
    }
    
    /** This abstract method should be implemented
      * to iterate over collection of values
      */
    protected abstract Iterator getLoopIterator();
    
}


