package moreservlets;

import javax.servlet.jsp.tagext.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

/** A "validator" that really just prints out an outline
 *  of the JSP page (in its XML representation). The
 *  validate method always returns null, so the page is
 *  always considered valid.
 *  <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 SAXValidator extends TagLibraryValidator {
  /** Print an outline of the XML representation of
   *  the JSP page.
   */
  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 PrintHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
      SAXParser parser = factory.newSAXParser();
      InputSource source =
        new InputSource(page.getInputStream());
      parser.parse(source, handler);
    } catch(Exception e) {
      String errorMessage =
        "SAX parse error: " + e;
      System.err.println(errorMessage);
      e.printStackTrace();
    }
    return(null);
  }
}
