DayIterator.java

/*
  Copyright 2001, Pajato Systems Group
  Copyright 2001, Allaire Corporation
*/

package allaire.samples.invoice.taglib;

import allaire.samples.invoice.InvoiceDataModel;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.ServletRequest;

/**
 * An <inv:foreachDay> tag iterates through the days of the week.  On
 * each iteration it will provide a value for the <inv:getDayHours>
 * and <inv:getDayName> custom tags.
 */

public class DayIterator extends BodyTagSupport {

    // Map a day index to a name.
    String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

    // Iterator.
    private int index;

    // Hours property.
    private String dayHours;

    /**
     * Hours accessor.
     */
    public String getDayHours() {
	return dayHours;
    }

    // Day name property.
    private String dayName;

    /**
     * Day name accessor.
     */
    public String getDayName() {
	return dayName;
    }

    /**
     * Determine if the operation matches.
     */
    public int doStartTag() throws JspException {

	// Initialize the iteration.
	index = 0;

	return getNext();
    }

    /**
     * Output any accumulating content.
     */
    public int doAfterBody () throws JspException {

	BodyContent body = getBodyContent();
	try {
	    body.writeOut( getPreviousOut() );
	} catch (IOException exc) {
	    throw new JspTagException( "unexpected IO error" );
	}
	body.clearBody();

	return getNext();
    }

    // Generate data for the next iteration.
    private int getNext() throws JspException {

	// Predispose the result to skip processing the tag body.
	int result = SKIP_BODY;

	int SCOPE = PageContext.APPLICATION_SCOPE;

	try {
	    // Test that all seven days have been processed.
	    if ( index < 7 ) {
		// Get the data model in order to access the hours worked
		// on a given day.
		InvoiceDataModel dataModel = (InvoiceDataModel)
		    pageContext.getAttribute( "invoiceDataModel", SCOPE );
		String[] hours = dataModel.getHours();
		dayHours = hours[index];
		
		// Set the day name, bump the index and insure that the
		// body content will be processed at least one more time.
		dayName = days[index];
		index++;
		result = EVAL_BODY_TAG;
	    }
	} catch ( Exception exc ) {
	    exc.printStackTrace();
	    throw new JspException( exc.getMessage() );
	}

	return result;
    }

}