package examples.xml.http;

import java.util.*;
import java.net.*;
import org.xml.sax.*;
import java.io.*;
import org.xml.sax.helpers.ParserFactory;
import javax.servlet.http.*;

/**
 * This class extends <tt>HandlerBase</tt> and is used to parse XML data using a SAX compliant 
 * parser. After parsing the document, <tt>getData()</tt> can be used to 
 * return a <tt>Hashtable</tt> representing the XML data.
 *
 * @author Copyright (c) 2000 by BEA Systems, Inc. All Rights Reserved.  
 */

public class RequestHandler extends HandlerBase {

  /** stocktrade document model */
  private Hashtable trade;

  /** Default constructor. */
  public RequestHandler() {}

  //
  // DocumentHandler methods
  //

  /** Start document. */
  public void startDocument() throws SAXException {
    trade = new Hashtable();
  } 

  /** Start element. */
  public void startElement(String name, AttributeList attrs) throws SAXException {
      if (attrs != null) {
          int len = attrs.getLength();

          // add attribute values to trade hashtable
          for (int i = 0; i < len; i++) {
            trade.put(attrs.getName(i), attrs.getValue(i));
          }
      }
  } 


  //
  // ErrorHandler methods
  //

  /** Warning. */
  public void warning(SAXParseException ex) {
      System.err.println("[Warning] "+
                         getLocationString(ex)+": "+
                         ex.getMessage());
  }

  /** Error. */
  public void error(SAXParseException ex) {
      System.err.println("[Error] "+
                         getLocationString(ex)+": "+
                         ex.getMessage());
  }

  /** Fatal error. */
  public void fatalError(SAXParseException ex) throws SAXException {
      System.err.println("[Fatal Error] "+
                         getLocationString(ex)+": "+
                         ex.getMessage());
      throw ex;
  }

  private String getLocationString(SAXParseException ex) {
      StringBuffer str = new StringBuffer();

      String systemId = ex.getSystemId();
      if (systemId != null) {
          int index = systemId.lastIndexOf('/');
          if (index != -1) 
              systemId = systemId.substring(index + 1);
          str.append(systemId);
      }
      str.append(':');
      str.append(ex.getLineNumber());
      str.append(':');
      str.append(ex.getColumnNumber());

      return str.toString();

  } 

  // RequestHandler methods 
  /** instantiates a parser, sets the document handler, and parses the BufferedReader */
  public void parseXML(BufferedReader br, String parserClass) 
    throws IOException, SAXException, ClassNotFoundException, IllegalAccessException, InstantiationException, 
           FileNotFoundException {
    Parser parser = ParserFactory.makeParser(parserClass);
    parser.setDocumentHandler(this);
    parser.setErrorHandler(this);
    parser.parse(new InputSource(br));
  }


  /** Returns parsed data as a hashtable */
  public Hashtable getData() {
    return trade;
  }

}
