001package edu.pdx.cs410J; 002 003import org.xml.sax.*; 004 005import java.io.IOException; 006import java.io.InputStream; 007import java.net.URL; 008 009public abstract class ProjectXmlHelper implements ErrorHandler, EntityResolver { 010 private final String publicId; 011 private final String systemId; 012 private final String dtdFileName; 013 014 protected ProjectXmlHelper(String publicId, String systemId, String dtdFileName) { 015 this.publicId = publicId; 016 this.systemId = systemId; 017 this.dtdFileName = dtdFileName; 018 } 019 020 @Override 021 public void warning(SAXParseException exception) throws SAXException { 022 throw exception; 023 } 024 025 @Override 026 public void error(SAXParseException exception) throws SAXException { 027 throw exception; 028 } 029 030 @Override 031 public void fatalError(SAXParseException exception) throws SAXException { 032 throw exception; 033 } 034 035 @Override 036 public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { 037 if (this.publicId.equals(publicId) || this.systemId.equals(systemId)) { 038 // We're resolving the external entity for the DTD 039 // Check to see if it's in the jar file. This way we don't 040 // need to go all the way to the website to find the DTD. 041 InputStream stream = 042 ProjectXmlHelper.class.getResourceAsStream(this.dtdFileName); 043 if (stream != null) { 044 return new InputSource(stream); 045 } 046 } 047 048 // Try to access the DTD using the URL 049 try { 050 URL url = new URL(systemId); 051 InputStream stream = url.openStream(); 052 return new InputSource(stream); 053 054 } catch (Exception ex) { 055 return null; 056 } 057 } 058}