package net.sf.jasperreports.engine.xml;

import java.io.InputStream;
import java.net.URL;
import org.apache.commons.digester.Digester;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

public class JRXmlDigester extends Digester {
  public JRXmlDigester() {}
  
  public JRXmlDigester(XMLReader xmlReader) {
    super(xmlReader);
  }
  
  public InputSource resolveEntity(String pubId, String systemId) {
    InputSource inputSource = null;
    if (systemId != null) {
      InputStream is;
      String dtd = null;
      if ("http://jasperreports.sourceforge.net/dtds/jasperreport.dtd".equals(systemId)) {
        dtd = "net/sf/jasperreports/engine/dtds/jasperreport.dtd";
      } else if ("http://jasperreports.sourceforge.net/dtds/jasperprint.dtd".equals(systemId)) {
        dtd = "net/sf/jasperreports/engine/dtds/jasperprint.dtd";
      } else if ("http://jasperreports.sourceforge.net/dtds/jaspertemplate.dtd".equals(systemId)) {
        dtd = "net/sf/jasperreports/engine/dtds/jaspertemplate.dtd";
      } else {
        return new InputSource(systemId);
      } 
      ClassLoader clsLoader = Thread.currentThread().getContextClassLoader();
      URL url = null;
      if (clsLoader != null)
        url = clsLoader.getResource(dtd); 
      if (url == null)
        clsLoader = JRXmlDigester.class.getClassLoader(); 
      if (clsLoader == null) {
        is = JRXmlDigester.class.getResourceAsStream("/" + dtd);
      } else {
        is = clsLoader.getResourceAsStream(dtd);
      } 
      if (is != null)
        inputSource = new InputSource(is); 
    } 
    return inputSource;
  }
}
