com.crabshue.commons.xml.sax.SaxParsingExecutor Maven / Gradle / Ivy
package com.crabshue.commons.xml.sax;
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import com.crabshue.commons.exceptions.ApplicationException;
import com.crabshue.commons.exceptions.SystemException;
import com.crabshue.commons.xml.exceptions.XmlErrorContext;
import com.crabshue.commons.xml.exceptions.XmlErrorType;
import com.crabshue.commons.xml.inputsource.InputSourceBuilder;
import lombok.NonNull;
/**
* Utility class for executing XML SAX parsing.
*/
public class SaxParsingExecutor {
/**
* Parse an XML file using a SAX parser, with a given SAX handler.
*
* @param xmlFile the XML file.
* @param saxHandler the SAX handler.
*/
public static void parseXmlFile(@NonNull final File xmlFile,
@NonNull final DefaultHandler saxHandler) {
parseXmlFile(InputSourceBuilder.newInputSource(xmlFile), saxHandler);
}
/**
* Parse an XML file using a SAX parser, with a given SAX handler.
*
* @param xmlInputSource the XML file.
* @param saxHandler the SAX handler.
*/
public static void parseXmlFile(@NonNull final InputSource xmlInputSource,
@NonNull final DefaultHandler saxHandler) {
try {
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
saxParser.parse(xmlInputSource, saxHandler);
} catch (ApplicationException e) {
throw e;
} catch (Exception e) {
throw new SystemException(XmlErrorType.ERROR_PARSING_XML, "Cannot parse xml file with sax parser", e)
.addContextValue(XmlErrorContext.XML_FILE, xmlInputSource.getSystemId())
.addContextValue("saxHandler", saxHandler);
}
}
}