package com.dbxml.xml.sax;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: SAXTableGenerator.java,v 1.5 2004/08/22 04:18:44 bradford Exp $
 */

import java.io.*;

import com.dbxml.xml.dtsm.DTSMException;
import com.dbxml.xml.dtsm.DocumentTable;
import com.dbxml.xml.dtsm.TableBuilder;
import com.dbxml.xml.dtsm.TableGenerator;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * SAXTableGenerator
 */

public class SAXTableGenerator extends TableGenerator {
   private TableBuilder builder;
   private DTSMContentHandler handler;
   private InputSource source;

   public SAXTableGenerator() {
   }

   public SAXTableGenerator(InputStream is) {
      source = new InputSource(is);
   }

   public SAXTableGenerator(Reader reader) {
      source = new InputSource(reader);
   }

   public SAXTableGenerator(File file) throws IOException {
      FileInputStream fis = new FileInputStream(file);
      BufferedInputStream bis = new BufferedInputStream(fis, 4096);
      InputStreamReader isr = new InputStreamReader(bis, "UTF8");
      source = new InputSource(isr);
   }

   public SAXTableGenerator(String uri) {
      source = new InputSource(uri);
   }

   public final DocumentTable process() throws DTSMException {
      try {
         if ( symbols != null )
            builder = new TableBuilder(symbols);
         else
            builder = new TableBuilder();
         handler = new DTSMContentHandler(builder);
         SAXHelper.parse(source, handler);

         SAXException e = handler.getException();
         if ( e != null )
            throw new DTSMException("Error parsing document", e);
         else
            return builder.buildDocumentTable();
      }
      catch ( SAXException e ) {
         throw new DTSMException(e);
      }
      catch ( IOException e ) {
         throw new DTSMException(e);
      }
   }
}
