// private methods
 private synchronized void writeToSAX(ContentHandler handler) {
   // nothing must go wrong with this parse...
   SAXParser parser = fGrammar.getSAXParser();
   StringReader aReader = new StringReader(fData);
   InputSource aSource = new InputSource(aReader);
   parser.setContentHandler(handler);
   try {
     parser.parse(aSource);
   } catch (SAXException e) {
     // this should never happen!
     // REVISIT:  what to do with this?; should really not
     // eat it...
   } catch (IOException i) {
     // ditto with above
   }
 }
  /**
   * Create a IncrementalSAXSource_Xerces, and create a SAXParser to go with it. Xerces2 incremental
   * parsing is only supported if this constructor is used, due to limitations in the Xerces2 API
   * (as of Beta 3). If you don't like that restriction, tell the Xerces folks that there should be
   * a simpler way to request incremental SAX parsing.
   */
  public IncrementalSAXSource_Xerces() throws NoSuchMethodException {
    try {
      // Xerces-2 incremental parsing support (as of Beta 3)
      // ContentHandlers still get set on fIncrementalParser (to get
      // conversion from XNI events to SAX events), but
      // _control_ for incremental parsing must be exercised via the config.
      //
      // At this time there's no way to read the existing config, only
      // to assert a new one... and only when creating a brand-new parser.
      //
      // Reflection is used to allow us to continue to compile against
      // Xerces1. If/when we can abandon the older versions of the parser,
      // this will simplify significantly.
      Class me = this.getClass();

      // If we can't get the magic constructor, no need to look further.
      Class xniConfigClass = me.forName("org.apache.xerces.xni.parser.XMLParserConfiguration");
      Class[] args1 = {xniConfigClass};
      Constructor ctor = SAXParser.class.getConstructor(args1);

      // Build the parser configuration object. StandardParserConfiguration
      // happens to implement XMLPullParserConfiguration, which is the API
      // we're going to want to use.
      Class xniStdConfigClass = me.forName("org.apache.xerces.parsers.StandardParserConfiguration");
      fPullParserConfig = xniStdConfigClass.newInstance();
      Object[] args2 = {fPullParserConfig};
      fIncrementalParser = (SAXParser) ctor.newInstance(args2);

      // Preload all the needed the configuration methods... I want to know they're
      // all here before we commit to trying to use them, just in case the
      // API changes again.
      Class fXniInputSourceClass = me.forName("org.apache.xerces.xni.parser.XMLInputSource");
      Class[] args3 = {fXniInputSourceClass};
      fConfigSetInput = xniStdConfigClass.getMethod("setInputSource", args3);

      Class[] args4 = {String.class, String.class, String.class};
      fConfigInputSourceCtor = fXniInputSourceClass.getConstructor(args4);
      Class[] args5 = {java.io.InputStream.class};
      fConfigSetByteStream = fXniInputSourceClass.getMethod("setByteStream", args5);
      Class[] args6 = {java.io.Reader.class};
      fConfigSetCharStream = fXniInputSourceClass.getMethod("setCharacterStream", args6);
      Class[] args7 = {String.class};
      fConfigSetEncoding = fXniInputSourceClass.getMethod("setEncoding", args7);

      Class[] argsb = {Boolean.TYPE};
      fConfigParse = xniStdConfigClass.getMethod("parse", argsb);
      Class[] noargs = new Class[0];
      fReset = fIncrementalParser.getClass().getMethod("reset", noargs);
    } catch (Exception e) {
      // Fallback if this fails (implemented in createIncrementalSAXSource) is
      // to attempt Xerces-1 incremental setup. Can't do tail-call in
      // constructor, so create new, copy Xerces-1 initialization,
      // then throw it away... Ugh.
      IncrementalSAXSource_Xerces dummy = new IncrementalSAXSource_Xerces(new SAXParser());
      this.fParseSomeSetup = dummy.fParseSomeSetup;
      this.fParseSome = dummy.fParseSome;
      this.fIncrementalParser = dummy.fIncrementalParser;
    }
  }
 /**
  * Create a IncrementalSAXSource_Xerces wrapped around an existing SAXParser. Currently this works
  * only for recent releases of Xerces-1. Xerces-2 incremental is currently possible only if we are
  * allowed to create the parser instance, due to limitations in the API exposed by Xerces-2 Beta
  * 3; see the no-args constructor for that code.
  *
  * @exception if the SAXParser class doesn't support the Xerces incremental parse operations. In
  *     that case, caller should fall back upon the IncrementalSAXSource_Filter approach.
  */
 public IncrementalSAXSource_Xerces(SAXParser parser) throws NoSuchMethodException {
   // Reflection is used to allow us to compile against
   // Xerces2. If/when we can abandon the older versions of the parser,
   // this constructor will simply have to fail until/unless the
   // Xerces2 incremental support is made available on previously
   // constructed SAXParser instances.
   fIncrementalParser = parser;
   Class me = parser.getClass();
   Class[] parms = {InputSource.class};
   fParseSomeSetup = me.getMethod("parseSomeSetup", parms);
   parms = new Class[0];
   fParseSome = me.getMethod("parseSome", parms);
   // Fallback if this fails (implemented in createIncrementalSAXSource) is
   // to use IncrementalSAXSource_Filter rather than Xerces-specific code.
 }
  private void parseDocument(Boolean typeFile, String reportName) {
    final InputStream jasperreportDtd =
        ReportManager.class
            .getClassLoader()
            .getResourceAsStream("net/sf/jasperreports/engine/dtds/jasperreport.dtd");
    InputStream xmlSource = null;

    parsingStart = System.currentTimeMillis();
    log.debug("parseDocument - [start] " + reportName);
    try {
      SAXParser sp = new SAXParser();
      log.debug(
          "parseDocument -   newSAXParser=" + (System.currentTimeMillis() - parsingStart) + " ms.");

      ClassLoader loader = (ReportManager.class).getClassLoader();
      File f = null;
      try {
        if (typeFile == true) f = new File(loader.getResource(reportName).toURI());
        else f = new File(reportName);
      } catch (URISyntaxException e) {
        e.printStackTrace();
      }
      log.debug(
          "parseDocument -   getResource=" + (System.currentTimeMillis() - parsingStart) + " ms.");

      xmlSource = new FileInputStream(f);

      sp.setContentHandler(this);
      sp.setEntityResolver(
          new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                throws SAXException, IOException {
              if (publicId.equals("//JasperReports//DTD Report Design//EN")
                  || systemId.equals(
                      "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd")) {
                return new InputSource(jasperreportDtd);
              } else {
                String msg =
                    "DTD ("
                        + publicId
                        + " "
                        + systemId
                        + ") cannot be resolved by ReportManager: "
                        + "please change TNTConcept to add the new DTD or change your JasperReport's JRXML file "
                        + "to use the standard DTD";
                log.error("parseDocument - " + msg);
                throw new IllegalArgumentException(msg);
              }
            }
          });

      sp.parse(new InputSource(xmlSource));
    } catch (FinalizeParsingException fpe) {
      // ignore this exception as it is thrown as an optimization
    } catch (SAXException se) {
      log.error("parseDocument - exception", se);
    } catch (IOException ie) {
      log.error("parseDocument - exception", ie);
    } finally {
      if (xmlSource != null) {
        try {
          xmlSource.close();
        } catch (IOException e) {
          // ignored
        }
      }
      try {
        jasperreportDtd.close();
      } catch (IOException e) {
        // ignored
      }
      log.info(
          "parseDocument - "
              + reportName
              + " ("
              + (System.currentTimeMillis() - parsingStart)
              + " ms.)");
    }
  }
  public void validate(Source source, Result result) throws SAXException, IOException {
    if (result instanceof StreamResult || result == null) {
      final StreamSource streamSource = (StreamSource) source;
      final StreamResult streamResult = (StreamResult) result;
      XMLInputSource input =
          new XMLInputSource(streamSource.getPublicId(), streamSource.getSystemId(), null);
      input.setByteStream(streamSource.getInputStream());
      input.setCharacterStream(streamSource.getReader());

      // Gets the parser configuration. We'll create and initialize a new one, if we
      // haven't created one before or if the previous one was garbage collected.
      boolean newConfig = false;
      XMLParserConfiguration config = (XMLParserConfiguration) fConfiguration.get();
      if (config == null) {
        config = initialize();
        newConfig = true;
      }
      // If settings have changed on the component manager, refresh the error handler and entity
      // resolver.
      else if (fComponentManager.getFeature(PARSER_SETTINGS)) {
        config.setProperty(ENTITY_RESOLVER, fComponentManager.getProperty(ENTITY_RESOLVER));
        config.setProperty(ERROR_HANDLER, fComponentManager.getProperty(ERROR_HANDLER));
        config.setProperty(SECURITY_MANAGER, fComponentManager.getProperty(SECURITY_MANAGER));
      }

      // prepare for parse
      fComponentManager.reset();

      if (streamResult != null) {
        if (fSerializerFactory == null) {
          fSerializerFactory = SerializerFactory.getSerializerFactory(Method.XML);
        }

        // there doesn't seem to be a way to reset a serializer, so we need to make
        // a new one each time.
        Serializer ser;
        if (streamResult.getWriter() != null) {
          ser = fSerializerFactory.makeSerializer(streamResult.getWriter(), new OutputFormat());
        } else if (streamResult.getOutputStream() != null) {
          ser =
              fSerializerFactory.makeSerializer(streamResult.getOutputStream(), new OutputFormat());
        } else if (streamResult.getSystemId() != null) {
          String uri = streamResult.getSystemId();
          OutputStream out = XMLEntityManager.createOutputStream(uri);
          ser = fSerializerFactory.makeSerializer(out, new OutputFormat());
        } else {
          throw new IllegalArgumentException(
              JAXPValidationMessageFormatter.formatMessage(
                  fComponentManager.getLocale(), "StreamResultNotInitialized", null));
        }

        // we're using the parser only as an XNI-to-SAX converter,
        // so that we can use the SAX-based serializer
        SAXParser parser = (SAXParser) fParser.get();
        if (newConfig || parser == null) {
          parser = new SAXParser(config);
          fParser = new SoftReference(parser);
        } else {
          parser.reset();
        }
        config.setDocumentHandler(fSchemaValidator);
        fSchemaValidator.setDocumentHandler(parser);
        parser.setContentHandler(ser.asContentHandler());
      } else {
        fSchemaValidator.setDocumentHandler(null);
      }

      try {
        config.parse(input);
      } catch (XMLParseException e) {
        throw Util.toSAXParseException(e);
      } catch (XNIException e) {
        throw Util.toSAXException(e);
      } finally {
        // release the references to the SAXParser and Serializer
        fSchemaValidator.setDocumentHandler(null);
      }

      return;
    }
    throw new IllegalArgumentException(
        JAXPValidationMessageFormatter.formatMessage(
            fComponentManager.getLocale(),
            "SourceResultMismatch",
            new Object[] {source.getClass().getName(), result.getClass().getName()}));
  }