package com.ACME;

import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

// This is a general-purpose conditional tag which checks whether
// a given parameter is a legal quantity (that is, an integer > 0).
// If it is, the tag body is skipped and the rest of the page is
// executed. If it is not, the body (presumably an error message)
// is executed, and the rest of the page is skipped.

public class ValidateQuantity implements Tag {

  private PageContext page;  // Use to access properties of JSP
  private String parameterName;  // what parameter am I checking?
  private boolean legal = true;  // is the value a legal quantity?

  // This is called when the tag is started up (like init), and is
  // used to store the PageContext link to the page properties.
  public void setPageContext(PageContext p) {
    page = p;
    }

  // This gets the value of the parameterName attribute, passed as
  // a parameter by the server page in the tag. This is required for
  // each possible attribute, and has the same basic form as a
  // set_____ method in a JavaBean.
  public void setQuantityParameter(String qp) {
    parameterName = qp;
    }

  // This is called when the tag is started. Its return value determines
  // whether the HTML in the tag body is executed or skipped.
  public int doStartTag() throws JspException {

    // Get the request object from the JSP page
    ServletRequest request = page.getRequest();

    // Get the parameter (whose name was passed as an attribute)
    // from the request.
    String value = request.getParameter(parameterName);
    legal = true;

    // If the value is a number > 0, it is legal.
    try {
      int quantity = Integer.parseInt(value);
      if (quantity <= 0) legal = false;
      }
    catch (Exception ex) {legal = false;}

    // If the number is legal, skip the HTML in the tag.
    // Otherwise, execute it.
    if (legal) return SKIP_BODY;
    else return EVAL_BODY_INCLUDE;
    }

  // This is called at the closing tag. It's return value determines
  // whether the rest of the page is executed.
  public int doEndTag() throws JspException {

    // If the number is a legal quantity, run the rest of the page.
    // Otherwise, skip the rest of the page.
    if (legal) return EVAL_PAGE;
    else return SKIP_PAGE;
    }

  public void setParent(Tag t) {}
  public Tag getParent() {return null;}
  public void release() {}

  }

