InvoiceThen.java

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

package allaire.samples.invoice.taglib;

import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * The <inv:then> tag will execute the body content if the associated
 * condition is false.  The condition is stored by the parent which
 * must be an <inv:if> tag.
 */

public class InvoiceThen extends BodyTagSupport {

    /**
     * Validate the tag structure and order.
     */
    public int doStartTag() throws JspTagException {

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

	// Determine if the parent is an if tag and that the condition
	// has already been setup.
	String message;
	InvoiceIf parent = (InvoiceIf)
	    findAncestorWithClass( this, InvoiceIf.class );
        if ( parent == null ) {

	    // The structure is invalid.  Throw an exception.
	    message = "The then tag must be inside an if tag.";
	    throw new JspTagException( message );
	} else if ( !parent.hasCondition() ) {

	    // The order is wrong. Throw an exception.
	    message = "The then tag must FOLLOW a condition tag.";
	    throw new JspTagException( message );
	}

	// Test the condition maintained inside the parent if tag to
	// determine if the body content is going to be evaluated.
	if ( parent.getCondition() ) {

	    result = EVAL_BODY_TAG;
	}

	return result;
    }

    /**
     * Conditionally output the body content.
     */
    public int doAfterBody() throws JspException {

	// Test the condition maintained inside the parent if tag.
	InvoiceIf parent = (InvoiceIf)
	    findAncestorWithClass( this, InvoiceIf.class );
	if ( parent.getCondition() ) {

	    // The condition is true, so output the body content.
	    try {
		BodyContent body = getBodyContent();
		JspWriter out = body.getEnclosingWriter();
		out.print( body.getString() );
	    } catch (IOException exc) {
		throw new JspException( exc.getMessage() );
	    }
	}

	return SKIP_BODY;
    }

}