package moreservlets;

import javax.servlet.jsp.tagext.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

/** A validator that verifies that tags follow
 *  proper nesting order.
 *  <P>
 *  Taken from More Servlets and JavaServer Pages
 *  from Prentice Hall and Sun Microsystems Press,
 *  http://www.moreservlets.com/.
 *  &copy; 2002 Marty Hall; may be freely used or adapted.
 */

public class NestingValidator extends TagLibraryValidator {
  
  public ValidationMessage[] validate(String prefix,
                                      String uri,
                                      PageData page) {
    String jaxpPropertyName =
      "javax.xml.parsers.SAXParserFactory";
    // Pass the parser factory in on the command line with
    // -D to override the use of the Apache parser.
    if (System.getProperty(jaxpPropertyName) == null) {
      String apacheXercesPropertyValue =
        "org.apache.xerces.jaxp.SAXParserFactoryImpl";
      System.setProperty(jaxpPropertyName,
                         apacheXercesPropertyValue);
    }
    DefaultHandler handler = new NestingHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
      SAXParser parser = factory.newSAXParser();
      InputSource source =
        new InputSource(page.getInputStream());
      parser.parse(source, handler);
      return(null);
    } catch(Exception e) {
      String errorMessage = e.getMessage();
      // The first argument to the ValidationMessage
      // constructor can be a tag ID. Since tag IDs
      // are not universally supported, use null for
      // portability. The important part is the second
      // argument: the error message.
      ValidationMessage[] messages =
        { new ValidationMessage(null, errorMessage) };
      return(messages);
    }
  }
}
