ASTParser.java
package edu.udel.cis.vsl.tass.ast.parser;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import edu.udel.cis.vsl.tass.ast.IF.ASTParserIF;
import edu.udel.cis.vsl.tass.ast.IF.AbstractSyntaxTreeIF;
public class ASTParser implements ASTParserIF {
private final File schemaFile;
private final File xmlFile;
private final InputStream xmlFileStream;
private final AbstractSyntaxTreeIF ast;
private SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
public ASTParser(File xmlFile,
File schemaFile,
AbstractSyntaxTreeIF ast) throws FileNotFoundException {
this.schemaFile = schemaFile;
this.xmlFile = xmlFile;
this.xmlFileStream = new FileInputStream(xmlFile);
this.ast = ast;
}
public ASTParser(InputStream xmlFileStream,
File schemaFile,
AbstractSyntaxTreeIF ast) {
this.schemaFile = schemaFile;
this.xmlFile = null;
this.xmlFileStream = xmlFileStream;
this.ast = ast;
}
public AbstractSyntaxTreeIF parseDocument() {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
try {
// spf.setSchema(schemaFactory.newSchema(schemaFile));
SAXParser sp = spf.newSAXParser();
ASTHandler handler = new ASTHandler();
sp.parse(xmlFile, handler);
ast.setRootNode(handler.getRoot());
return ast;
} catch (ParserConfigurationException e) {
throw new ParserException("Could not configure parser", e);
} catch (SAXParseException e) {
String fileName = "the file";
if (xmlFile != null) {
fileName = xmlFile.toString();
}
throw new ParserException(
"An XML parse error occurred while parsing " + fileName
+ " line " + e.getLineNumber() + " column "
+ e.getColumnNumber(), e);
} catch (SAXException e) {
throw new ParserException(
"An error occured while parsing the xml file", e);
} catch (IOException e) {
throw new ParserException("Could not open an xml file", e);
}
}
}