예제 #1
0
  /**
   * Sets the XSLT transformer from a Source
   *
   * @param source the source
   * @throws TransformerConfigurationException is thrown if creating a XSLT transformer failed.
   */
  public void setTransformerSource(Source source) throws TransformerConfigurationException {
    TransformerFactory factory = converter.getTransformerFactory();
    if (errorListener != null) {
      factory.setErrorListener(errorListener);
    } else {
      // use a logger error listener so users can see from the logs what the error may be
      factory.setErrorListener(new XsltErrorListener());
    }
    if (getUriResolver() != null) {
      factory.setURIResolver(getUriResolver());
    }

    // Check that the call to newTemplates() returns a valid template instance.
    // In case of an xslt parse error, it will return null and we should stop the
    // deployment and raise an exception as the route will not be setup properly.
    Templates templates = factory.newTemplates(source);
    if (templates != null) {
      setTemplate(templates);
    } else {
      throw new TransformerConfigurationException(
          "Error creating XSLT template. "
              + "This is most likely be caused by a XML parse error. "
              + "Please verify your XSLT file configured.");
    }
  }
예제 #2
0
    @Override
    public Object makeObject() throws Exception {
      StreamSource source = XsltTransformer.this.getStreamSource();
      String factoryClassName = XsltTransformer.this.getXslTransformerFactory();
      TransformerFactory factory;

      if (PREFERRED_TRANSFORMER_FACTORY.equals(factoryClassName)
          && !ClassUtils.isClassOnPath(factoryClassName, getClass())) {
        logger.warn(
            "Preferred Transfomer Factory "
                + PREFERRED_TRANSFORMER_FACTORY
                + " not on classpath and no default is set, defaulting to JDK");
        factoryClassName = null;
      }

      if (StringUtils.isNotEmpty(factoryClassName)) {

        factory =
            (TransformerFactory)
                ClassUtils.instanciateClass(factoryClassName, ClassUtils.NO_ARGS, this.getClass());
      } else {
        // fall back to JDK default
        try {
          factory = TransformerFactory.newInstance();
        } catch (TransformerFactoryConfigurationError e) {
          System.setProperty(
              "javax.xml.transform.TransformerFactory", XMLUtils.TRANSFORMER_FACTORY_JDK5);
          factory = TransformerFactory.newInstance();
        }
      }

      factory.setURIResolver(getUriResolver());

      return factory.newTransformer(source);
    }
예제 #3
0
  /**
   * Returns a transformer for the given XSLT file. If one already exists, it will be returned and
   * no new one will be created.
   *
   * @param xsltFileName the name of the XSLT file to use
   * @return The transformer that uses the given XSLT file or null, if none could be created.
   */
  private static Transformer getTransformer(String xsltFileName) {
    String key = xsltFileName + "-" + Thread.currentThread().getId();
    if (transformers.containsKey(key)) {
      return transformers.get(key);
    }
    InputStream xsltFile = XsltRunner.class.getResourceAsStream("/" + xsltFileName);
    if (xsltFile == null) {
      Log.error(TAG, "Error could not find: " + xsltFileName);
      return null;
    }
    try {
      Source xsltSource = new StreamSource(xsltFile);
      TransformerFactory transFactory = TransformerFactory.newInstance();

      // Add a URI resolver so that the XSL docs may import other XSL docs
      // using relative paths
      transFactory.setURIResolver(
          new URIResolver() {

            public Source resolve(String href, String base) throws TransformerException {
              InputStream is = XsltRunner.class.getResourceAsStream("/" + href);
              return new StreamSource(is);
            }
          });

      Transformer transformer = transFactory.newTransformer(xsltSource);
      transformers.put(key, transformer);
      return transformer;
    } catch (TransformerConfigurationException e) {
      Log.error(TAG, "Could not create transformer for " + xsltFileName + ": " + e.getMessage());
    }
    return null;
  }
예제 #4
0
  /**
   * Transforms an xml tree putting the result to a stream with optional parameters.
   *
   * @param xml
   * @param styleSheetPath
   * @param result
   * @param params
   * @throws Exception
   */
  public static void transform(
      Element xml, String styleSheetPath, Result result, Map<String, String> params)
      throws Exception {
    File styleSheet = new File(styleSheetPath);
    Source srcXml = new JDOMSource(new Document((Element) xml.detach()));
    Source srcSheet = new StreamSource(styleSheet);

    // Dear old saxon likes to yell loudly about each and every XSLT 1.0
    // stylesheet so switch it off but trap any exceptions because this
    // code is run on transformers other than saxon
    TransformerFactory transFact = TransformerFactoryFactory.getTransformerFactory();
    transFact.setURIResolver(new JeevesURIResolver());
    try {
      transFact.setAttribute(FeatureKeys.VERSION_WARNING, false);
      transFact.setAttribute(FeatureKeys.LINE_NUMBERING, true);
      transFact.setAttribute(FeatureKeys.PRE_EVALUATE_DOC_FUNCTION, false);
      transFact.setAttribute(FeatureKeys.RECOVERY_POLICY, Configuration.RECOVER_SILENTLY);
      // Add the following to get timing info on xslt transformations
      // transFact.setAttribute(FeatureKeys.TIMING,true);
    } catch (IllegalArgumentException e) {
      Log.warning(Log.ENGINE, "WARNING: transformerfactory doesnt like saxon attributes!");
      // e.printStackTrace();
    } finally {
      Transformer t = transFact.newTransformer(srcSheet);
      if (params != null) {
        for (Map.Entry<String, String> param : params.entrySet()) {
          t.setParameter(param.getKey(), param.getValue());
        }
      }
      t.transform(srcXml, result);
    }
  }
예제 #5
0
  /**
   * @param out
   * @param document
   * @param xsltStream
   * @throws TransformerFactoryConfigurationError
   * @throws TransformerException
   */
  public static void parse(
      OutputStream out,
      Document document,
      InputStream xsltStream,
      URIResolver customResolver,
      boolean pretty)
      throws TransformerFactoryConfigurationError, TransformerException {
    Source xsltSource = new StreamSource(xsltStream);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    if (pretty) {
      try {
        transformerFactory.setAttribute("indent-number", new Integer(2));
      } catch (Exception e) {
      }
    }
    if (customResolver != null) {
      transformerFactory.setURIResolver(customResolver);
    }

    Transformer transformer = transformerFactory.newTransformer(xsltSource);
    if (pretty) {
      try {
        transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");
      } catch (Exception e) {
      }
    }

    parse(out, document, transformer);
  }
 @PostConstruct
 protected void init() {
   transformerFactory.setURIResolver(
       new URIResolver() {
         @Override
         public Source resolve(String href, String base) throws TransformerException {
           try {
             return new StreamSource(new ClassPathResource("transform/" + href).getInputStream());
           } catch (IOException e) {
             throw new TransformerException("Failed to resolve uri: " + href, e);
           }
         }
       });
 }
예제 #7
0
  /**
   * Transform an xml tree to PDF using XSL-FOP     * putting the result to a stream (uses a
   * stylesheet on disk)
   */
  public static String transformFOP(String uploadDir, Element xml, String styleSheetPath)
      throws Exception {
    String file = uploadDir + UUID.randomUUID().toString() + ".pdf";

    // Step 1: Construct a FopFactory
    // (reuse if you plan to render multiple documents!)
    FopFactory fopFactory = FopFactory.newInstance();

    // Step 2: Set up output stream.
    // Note: Using BufferedOutputStream for performance reasons (helpful
    // with FileOutputStreams).
    OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file)));

    try {
      // Step 3: Construct fop with desired output format
      Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

      // Step 4: Setup JAXP using identity transformer
      TransformerFactory factory = TransformerFactoryFactory.getTransformerFactory();
      factory.setURIResolver(new JeevesURIResolver());
      Source xslt = new StreamSource(new File(styleSheetPath));
      try {
        factory.setAttribute(FeatureKeys.VERSION_WARNING, false);
        factory.setAttribute(FeatureKeys.LINE_NUMBERING, true);
        factory.setAttribute(FeatureKeys.RECOVERY_POLICY, Configuration.RECOVER_SILENTLY);
      } catch (IllegalArgumentException e) {
        Log.warning(Log.ENGINE, "WARNING: transformerfactory doesnt like saxon attributes!");
        // e.printStackTrace();
      } finally {
        Transformer transformer = factory.newTransformer(xslt);

        // Step 5: Setup input and output for XSLT transformation
        // Setup input stream
        Source src = new JDOMSource(new Document((Element) xml.detach()));

        // Resulting SAX events (the generated FO) must be piped through to
        // FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        // Step 6: Start XSLT transformation and FOP processing
        transformer.transform(src, res);
      }

    } finally {
      // Clean-up
      out.close();
    }

    return file;
  }
예제 #8
0
  /**
   * Get the transformer to use for XSLT transformations (and by implication serialization and
   * XPaths).
   *
   * @return If specific TransformerFactoryClass was specified then new instance of this class will
   *     be returned. New instance of default TransformerFactory otherwise.
   */
  public TransformerFactory newTransformerFactory() {
    TransformerFactory factory;
    if (transformerFactoryClass == null) {
      factory = TransformerFactory.newInstance();
    } else {
      factory =
          TransformerFactory.newInstance(
              transformerFactoryClass.getName(), transformerFactoryClass.getClassLoader());
    }

    if (uriResolver != null) {
      factory.setURIResolver(uriResolver);
    }

    return factory;
  }
예제 #9
0
  static {
    try {
      // Try to load Saxon implementation before defaulting to default implementation.
      transformerFactory =
          (TransformerFactoryImpl)
              Class.forName("net.sf.saxon.TransformerFactoryImpl").getConstructor().newInstance();
      logger.info("Using Saxon transformer.");
    } catch (Exception e) {
      transformerFactory = TransformerFactory.newInstance();
      logger.info("Using default transformer.");
    }

    transformerFactory.setURIResolver(
        new URIResolver() {
          @Override
          public Source resolve(String href, String base) throws TransformerException {
            return !"".equals(base)
                ? null
                : new StreamSource(
                    getClass()
                        .getResourceAsStream(String.format("/iso-schematron-xslt2/%s", href)));
          }
        });
  }
예제 #10
0
  /**
   * @param path Path, starting with /, relative to context root, of xsl
   * @return The jaxp object for the specified path.
   * @exception ConfigException
   */
  protected Templates loadTemplate(String path, ServletContext servletCtx) throws ConfigException {
    boolean pathIsFileUrl = false;
    boolean pathIsOtherUrl = false;
    java.net.URL resURL = null;

    if (this.isMonitoredFile && this.monitoredFile != null) {
      // This happens if the file is monitored and it has changed on the filesystem
      try {
        resURL = this.monitoredFile.toURI().toURL();
        this.monitoredFileLastModified = this.monitoredFile.lastModified();
      } catch (MalformedURLException me) {
        log.error("Eror parsing monitored template URL " + path + ":  " + me.toString());
        throw new ConfigException(me);
      } catch (SecurityException se) {
        log.error("Unable to access monitored template " + path + ":  " + se.toString());
        throw new ConfigException(se);
      }
    } else {
      // Check to see if the path is a URL and what type, otherwise make sure
      // it's a proper servlet resource path
      if (path.toLowerCase().startsWith("file:")) pathIsFileUrl = true;
      else if (path.toLowerCase().startsWith("http:")
          || path.toLowerCase().startsWith("https:")
          || path.toLowerCase().startsWith("ftp:")) pathIsOtherUrl = true;
      else if (!path.startsWith("/")) path = "/" + path;

      try {
        if (pathIsFileUrl && this.isMonitoredFile) {
          resURL = new java.net.URL(path);
          this.monitoredFile = new File(resURL.getFile());

          if (this.monitoredFile == null || !this.monitoredFile.canRead()) {
            this.monitoredFile = null;
            log.error("Resource not found or unable to read file:  " + path);
            throw new ConfigException("Resource not found or unable to read file:  " + path);
          }

          this.monitoredFileLastModified = this.monitoredFile.lastModified();
        } else if (pathIsFileUrl || pathIsOtherUrl) resURL = new java.net.URL(path);
        else resURL = servletCtx.getResource(path);

        if (resURL == null) {
          log.error("Resource not found:  " + path);
          throw new ConfigException("Resource not found:  " + path);
        }
      } catch (MalformedURLException me) {
        log.error("Eror parsing template URL " + path + ":  " + me.toString());
        throw new ConfigException(me);
      }
    }

    try {
      TransformerFactory tFactory = TransformerFactory.newInstance();
      if (this.uriResolver != null) tFactory.setURIResolver(this.uriResolver);

      return tFactory.newTemplates(new StreamSource(resURL.openStream(), resURL.toString()));
    } catch (TransformerException ex) {
      log.error("Error loading template " + path + ":  " + ex.toString());
      throw new ConfigException(ex);
    } catch (IOException ex) {
      log.error("Eror loading template " + path + ":  " + ex.toString());
      throw new ConfigException(ex);
    }
  }
예제 #11
0
  public void initialize(InputStream configFileStream) throws InitializationException {

    try {
      XPathFactory factory = XPathFactory.newInstance();
      XPath xPath = factory.newXPath();
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document document = parser.parse(new InputSource(configFileStream));
      Node node;
      NodeList nodes =
          (NodeList) xPath.evaluate("/htmlextractors/extractor", document, XPathConstants.NODESET);
      if (nodes != null) {
        TransformerFactory transFac = TransformerFactory.newInstance();
        transFac.setURIResolver(new BundleURIResolver());
        for (int j = 0, iCnt = nodes.getLength(); j < iCnt; j++) {
          Node nd = nodes.item(j);
          node = (Node) xPath.evaluate("@id", nd, XPathConstants.NODE);
          String id = node.getNodeValue();
          Node srcNode = (Node) xPath.evaluate("source", nd, XPathConstants.NODE);
          if (srcNode != null) {
            node = (Node) xPath.evaluate("@type", srcNode, XPathConstants.NODE);
            String srcType = node.getNodeValue();
            if (srcType.equals("xslt")) {
              String rdfFormat = "rdfxml";
              Syntax rdfSyntax = Syntax.RdfXml;
              node = (Node) xPath.evaluate("@syntax", srcNode, XPathConstants.NODE);
              if (node != null) {
                rdfFormat = node.getNodeValue();
                if (rdfFormat.equalsIgnoreCase("turtle")) {
                  rdfSyntax = Syntax.Turtle;
                } else if (rdfFormat.equalsIgnoreCase("ntriple")) {
                  rdfSyntax = Syntax.Ntriples;
                } else if (rdfFormat.equalsIgnoreCase("n3")) {
                  rdfSyntax = XsltExtractor.N3;
                } else if (!rdfFormat.equalsIgnoreCase("rdfxml")) {
                  throw new InitializationException(
                      "Unknown RDF Syntax: " + rdfFormat + " for " + id + " extractor");
                }
              }
              // TODO: do something about disjunctions of
              // Extractors? Assume, only RDFa or Microformats are
              // used?
              String fileName = DOMUtils.getText(srcNode);
              XsltExtractor xsltExtractor = new XsltExtractor(id, fileName, transFac);
              xsltExtractor.setSyntax(rdfSyntax);
              // name of URI/URL parameter of the script (default
              // "uri")
              node = (Node) xPath.evaluate("@uri", srcNode, XPathConstants.NODE);
              if (node != null) {
                xsltExtractor.setUriParameter(node.getNodeValue());
              }
              registry.put(id, xsltExtractor);
              activeExtractors.add(id);
            } else if (srcType.equals("java")) {
              String clsName = srcNode.getNodeValue();
              Object extractor = Class.forName(clsName).newInstance();
              if (extractor instanceof HtmlExtractionComponent) {
                registry.put(id, (HtmlExtractionComponent) extractor);
                activeExtractors.add(id);
              } else {
                throw new InitializationException("clsName is not an HtmlExtractionComponent");
              }
            } else {
              LOG.warn("No valid type for extractor found: " + id);
            }
            LOG.info("Extractor for: " + id);
          }
        }
      }
    } catch (FileNotFoundException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (XPathExpressionException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (DOMException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (ParserConfigurationException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (SAXException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (IOException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (ClassNotFoundException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (InstantiationException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
      throw new InitializationException(e.getMessage(), e);
    }
  }
예제 #12
0
  protected String doTransform(
      ThemeDisplay themeDisplay,
      Map<String, String> tokens,
      String viewMode,
      String languageId,
      String xml,
      String script)
      throws Exception {

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    long companyId = GetterUtil.getLong(tokens.get("company_id"));
    Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
    long groupId = GetterUtil.getLong(tokens.get("group_id"));
    String journalTemplatesPath =
        VelocityResourceListener.JOURNAL_SEPARATOR
            + StringPool.SLASH
            + companyId
            + StringPool.SLASH
            + groupId;
    String randomNamespace = PwdGenerator.getPassword(PwdGenerator.KEY3, 4) + StringPool.UNDERLINE;
    Locale locale = LocaleUtil.fromLanguageId(languageId);

    XSLErrorListener xslErrorListener = new XSLErrorListener(locale);

    StreamSource xmlSource = new StreamSource(new UnsyncStringReader(xml));

    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    transformerFactory.setURIResolver(new URIResolver(tokens, languageId));
    transformerFactory.setErrorListener(xslErrorListener);

    try {
      StreamSource scriptSource = new StreamSource(new UnsyncStringReader(script));

      Transformer transformer = transformerFactory.newTransformer(scriptSource);

      transformer.setParameter("company", company);
      transformer.setParameter("companyId", new Long(companyId));
      transformer.setParameter("groupId", String.valueOf(groupId));
      transformer.setParameter("journalTemplatesPath", journalTemplatesPath);
      transformer.setParameter("viewMode", viewMode);
      transformer.setParameter("locale", locale);
      transformer.setParameter("permissionChecker", PermissionThreadLocal.getPermissionChecker());
      transformer.setParameter("randomNamespace", randomNamespace);

      transformer.transform(xmlSource, new StreamResult(unsyncByteArrayOutputStream));
    } catch (Exception e1) {
      String errorTemplate = ContentUtil.get(PropsValues.JOURNAL_ERROR_TEMPLATE_XSL);

      StreamSource scriptSource = new StreamSource(new UnsyncStringReader(errorTemplate));

      Transformer transformer = transformerFactory.newTransformer(scriptSource);

      transformer.setParameter("company", company);
      transformer.setParameter("companyId", new Long(companyId));
      transformer.setParameter("groupId", String.valueOf(groupId));
      transformer.setParameter("journalTemplatesPath", journalTemplatesPath);
      transformer.setParameter("locale", locale);
      transformer.setParameter("randomNamespace", randomNamespace);

      transformer.setParameter("exception", xslErrorListener.getMessageAndLocation());
      transformer.setParameter("script", script);

      if (xslErrorListener.getLocation() != null) {
        transformer.setParameter("column", new Integer(xslErrorListener.getColumnNumber()));
        transformer.setParameter("line", new Integer(xslErrorListener.getLineNumber()));
      }

      transformer.transform(xmlSource, new StreamResult(unsyncByteArrayOutputStream));
    }

    return unsyncByteArrayOutputStream.toString(StringPool.UTF8);
  }
예제 #13
0
  // J2SE does not support Xalan interpretive
  // main -> _main
  public static void _main(String argv[]) {

    // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off
    boolean doStackDumpOnError = false;
    boolean setQuietMode = false;
    boolean doDiag = false;
    String msg = null;
    boolean isSecureProcessing = false;

    // Runtime.getRuntime().traceMethodCalls(false);
    // Runtime.getRuntime().traceInstructions(false);

    /** The default diagnostic writer... */
    java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true);
    java.io.PrintWriter dumpWriter = diagnosticsWriter;
    ResourceBundle resbundle =
        (SecuritySupport.getResourceBundle(
            com.sun.org.apache.xml.internal.utils.res.XResourceBundle.ERROR_RESOURCES));
    String flavor = "s2s";

    if (argv.length < 1) {
      printArgOptions(resbundle);
    } else {
      // J2SE does not support Xalan interpretive
      // false -> true
      boolean useXSLTC = true;
      for (int i = 0; i < argv.length; i++) {
        if ("-XSLTC".equalsIgnoreCase(argv[i])) {
          useXSLTC = true;
        }
      }

      TransformerFactory tfactory;
      if (useXSLTC) {
        String key = "javax.xml.transform.TransformerFactory";
        String value = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
        Properties props = System.getProperties();
        props.put(key, value);
        System.setProperties(props);
      }

      try {
        tfactory = TransformerFactory.newInstance();
        tfactory.setErrorListener(new DefaultErrorHandler());
      } catch (TransformerFactoryConfigurationError pfe) {
        pfe.printStackTrace(dumpWriter);
        //      "XSL Process was not successful.");
        msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
        diagnosticsWriter.println(msg);

        tfactory = null; // shut up compiler

        doExit(msg);
      }

      boolean formatOutput = false;
      boolean useSourceLocation = false;
      String inFileName = null;
      String outFileName = null;
      String dumpFileName = null;
      String xslFileName = null;
      String treedumpFileName = null;
      // J2SE does not support Xalan interpretive
      /*
      PrintTraceListener tracer = null;
      */
      String outputType = null;
      String media = null;
      Vector params = new Vector();
      boolean quietConflictWarnings = false;
      URIResolver uriResolver = null;
      EntityResolver entityResolver = null;
      ContentHandler contentHandler = null;
      int recursionLimit = -1;

      for (int i = 0; i < argv.length; i++) {
        if ("-XSLTC".equalsIgnoreCase(argv[i])) {
          // The -XSLTC option has been processed.
        }
        // J2SE does not support Xalan interpretive
        /*
        else if ("-TT".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceTemplates = true;
          }
          else
            printInvalidXSLTCOption("-TT");

          // tfactory.setTraceTemplates(true);
        }
        else if ("-TG".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceGeneration = true;
          }
          else
            printInvalidXSLTCOption("-TG");

          // tfactory.setTraceSelect(true);
        }
        else if ("-TS".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceSelection = true;
          }
          else
            printInvalidXSLTCOption("-TS");

          // tfactory.setTraceTemplates(true);
        }
        else if ("-TTC".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceElements = true;
          }
          else
            printInvalidXSLTCOption("-TTC");

          // tfactory.setTraceTemplateChildren(true);
        }
        */
        else if ("-INDENT".equalsIgnoreCase(argv[i])) {
          int indentAmount;

          if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) {
            indentAmount = Integer.parseInt(argv[++i]);
          } else {
            indentAmount = 0;
          }

          // TBD:
          // xmlProcessorLiaison.setIndent(indentAmount);
        } else if ("-IN".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') inFileName = argv[++i];
          else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-IN"})); // "Missing argument for);
        } else if ("-MEDIA".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) media = argv[++i];
          else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-MEDIA"})); // "Missing argument for);
        } else if ("-OUT".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') outFileName = argv[++i];
          else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-OUT"})); // "Missing argument for);
        } else if ("-XSL".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') xslFileName = argv[++i];
          else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-XSL"})); // "Missing argument for);
        } else if ("-FLAVOR".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) {
            flavor = argv[++i];
          } else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-FLAVOR"})); // "Missing argument for);
        } else if ("-PARAM".equalsIgnoreCase(argv[i])) {
          if (i + 2 < argv.length) {
            String name = argv[++i];

            params.addElement(name);

            String expression = argv[++i];

            params.addElement(expression);
          } else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-PARAM"})); // "Missing argument for);
        } else if ("-E".equalsIgnoreCase(argv[i])) {

          // TBD:
          // xmlProcessorLiaison.setShouldExpandEntityRefs(false);
        } else if ("-V".equalsIgnoreCase(argv[i])) {
          diagnosticsWriter.println(
              resbundle.getString("version") // ">>>>>>> Xalan Version "
                  + Version.getVersion()
                  + ", "
                  +

                  /* xmlProcessorLiaison.getParserDescription()+ */
                  resbundle.getString("version2")); // "<<<<<<<");
        }
        // J2SE does not support Xalan interpretive
        /*
        else if ("-QC".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
            quietConflictWarnings = true;
          else
            printInvalidXSLTCOption("-QC");
        }
        */
        else if ("-Q".equalsIgnoreCase(argv[i])) {
          setQuietMode = true;
        } else if ("-DIAG".equalsIgnoreCase(argv[i])) {
          doDiag = true;
        } else if ("-XML".equalsIgnoreCase(argv[i])) {
          outputType = "xml";
        } else if ("-TEXT".equalsIgnoreCase(argv[i])) {
          outputType = "text";
        } else if ("-HTML".equalsIgnoreCase(argv[i])) {
          outputType = "html";
        } else if ("-EDUMP".equalsIgnoreCase(argv[i])) {
          doStackDumpOnError = true;

          if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) {
            dumpFileName = argv[++i];
          }
        } else if ("-URIRESOLVER".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) {
            try {
              uriResolver = (URIResolver) ObjectFactory.newInstance(argv[++i], true);

              tfactory.setURIResolver(uriResolver);
            } catch (ConfigurationError cnfe) {
              msg =
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
                      new Object[] {"-URIResolver"});
              System.err.println(msg);
              doExit(msg);
            }
          } else {
            msg =
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-URIResolver"}); // "Missing argument for);
            System.err.println(msg);
            doExit(msg);
          }
        } else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) {
            try {
              entityResolver = (EntityResolver) ObjectFactory.newInstance(argv[++i], true);
            } catch (ConfigurationError cnfe) {
              msg =
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
                      new Object[] {"-EntityResolver"});
              System.err.println(msg);
              doExit(msg);
            }
          } else {
            //            "Missing argument for);
            msg =
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-EntityResolver"});
            System.err.println(msg);
            doExit(msg);
          }
        } else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) {
            try {
              contentHandler = (ContentHandler) ObjectFactory.newInstance(argv[++i], true);
            } catch (ConfigurationError cnfe) {
              msg =
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
                      new Object[] {"-ContentHandler"});
              System.err.println(msg);
              doExit(msg);
            }
          } else {
            //            "Missing argument for);
            msg =
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-ContentHandler"});
            System.err.println(msg);
            doExit(msg);
          }
        }
        // J2SE does not support Xalan interpretive
        /*
        else if ("-L".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
            tfactory.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
          else
            printInvalidXSLTCOption("-L");
        }
        else if ("-INCREMENTAL".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
            tfactory.setAttribute
              ("http://xml.apache.org/xalan/features/incremental",
               java.lang.Boolean.TRUE);
          else
            printInvalidXSLTCOption("-INCREMENTAL");
        }
        else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i]))
        {
          // Default is true.
          //
          // %REVIEW% We should have a generalized syntax for negative
          // switches...  and probably should accept the inverse even
          // if it is the default.
          if (!useXSLTC)
            tfactory.setAttribute
              ("http://xml.apache.org/xalan/features/optimize",
               java.lang.Boolean.FALSE);
          else
            printInvalidXSLTCOption("-NOOPTIMIZE");
        }
        else if ("-RL".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (i + 1 < argv.length)
              recursionLimit = Integer.parseInt(argv[++i]);
            else
              System.err.println(
                XSLMessages.createMessage(
                  XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                  new Object[]{ "-rl" }));  //"Missing argument for);
          }
          else
          {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
             i++;

            printInvalidXSLTCOption("-RL");
          }
        }
        */
        // Generate the translet class and optionally specify the name
        // of the translet class.
        else if ("-XO".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') {
              tfactory.setAttribute("generate-translet", "true");
              tfactory.setAttribute("translet-name", argv[++i]);
            } else tfactory.setAttribute("generate-translet", "true");
          } else {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++;
            printInvalidXalanOption("-XO");
          }
        }
        // Specify the destination directory for the translet classes.
        else if ("-XD".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
              tfactory.setAttribute("destination-directory", argv[++i]);
            else
              System.err.println(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                      new Object[] {"-XD"})); // "Missing argument for);

          } else {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++;

            printInvalidXalanOption("-XD");
          }
        }
        // Specify the jar file name which the translet classes are packaged into.
        else if ("-XJ".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') {
              tfactory.setAttribute("generate-translet", "true");
              tfactory.setAttribute("jar-name", argv[++i]);
            } else
              System.err.println(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                      new Object[] {"-XJ"})); // "Missing argument for);
          } else {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++;

            printInvalidXalanOption("-XJ");
          }

        }
        // Specify the package name prefix for the generated translet classes.
        else if ("-XP".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
              tfactory.setAttribute("package-name", argv[++i]);
            else
              System.err.println(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                      new Object[] {"-XP"})); // "Missing argument for);
          } else {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++;

            printInvalidXalanOption("-XP");
          }

        }
        // Enable template inlining.
        else if ("-XN".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            tfactory.setAttribute("enable-inlining", "true");
          } else printInvalidXalanOption("-XN");
        }
        // Turns on additional debugging message output
        else if ("-XX".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            tfactory.setAttribute("debug", "true");
          } else printInvalidXalanOption("-XX");
        }
        // Create the Transformer from the translet if the translet class is newer
        // than the stylesheet.
        else if ("-XT".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            tfactory.setAttribute("auto-translet", "true");
          } else printInvalidXalanOption("-XT");
        } else if ("-SECURE".equalsIgnoreCase(argv[i])) {
          isSecureProcessing = true;
          try {
            tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
          } catch (TransformerConfigurationException e) {
          }
        } else
          System.err.println(
              XSLMessages.createMessage(
                  XSLTErrorResources.ER_INVALID_OPTION,
                  new Object[] {argv[i]})); // "Invalid argument:);
      }

      // Print usage instructions if no xml and xsl file is specified in the command line
      if (inFileName == null && xslFileName == null) {
        msg = resbundle.getString("xslProc_no_input");
        System.err.println(msg);
        doExit(msg);
      }

      // Note that there are usage cases for calling us without a -IN arg
      // The main XSL transformation occurs here!
      try {
        long start = System.currentTimeMillis();

        if (null != dumpFileName) {
          dumpWriter = new PrintWriter(new FileWriter(dumpFileName));
        }

        Templates stylesheet = null;

        if (null != xslFileName) {
          if (flavor.equals("d2d")) {

            // Parse in the xml data into a DOM
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

            dfactory.setNamespaceAware(true);

            if (isSecureProcessing) {
              try {
                dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
              } catch (ParserConfigurationException pce) {
              }
            }

            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
            Node xslDOM = docBuilder.parse(new InputSource(xslFileName));

            stylesheet = tfactory.newTemplates(new DOMSource(xslDOM, xslFileName));
          } else {
            // System.out.println("Calling newTemplates: "+xslFileName);
            stylesheet = tfactory.newTemplates(new StreamSource(xslFileName));
            // System.out.println("Done calling newTemplates: "+xslFileName);
          }
        }

        PrintWriter resultWriter;
        StreamResult strResult;

        if (null != outFileName) {
          strResult = new StreamResult(new FileOutputStream(outFileName));
          // One possible improvement might be to ensure this is
          //  a valid URI before setting the systemId, but that
          //  might have subtle changes that pre-existing users
          //  might notice; we can think about that later -sc r1.46
          strResult.setSystemId(outFileName);
        } else {
          strResult = new StreamResult(System.out);
          // We used to default to incremental mode in this case.
          // We've since decided that since the -INCREMENTAL switch is
          // available, that default is probably not necessary nor
          // necessarily a good idea.
        }

        SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;

        // J2SE does not support Xalan interpretive
        /*
                // This is currently controlled via TransformerFactoryImpl.
        if (!useXSLTC && useSourceLocation)
           stf.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
        */

        // Did they pass in a stylesheet, or should we get it from the
        // document?
        if (null == stylesheet) {
          Source source =
              stf.getAssociatedStylesheet(new StreamSource(inFileName), media, null, null);

          if (null != source) stylesheet = tfactory.newTemplates(source);
          else {
            if (null != media)
              throw new TransformerException(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA,
                      new Object[] {inFileName, media})); // "No stylesheet found in: "
            // + inFileName + ", media="
            // + media);
            else
              throw new TransformerException(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_NO_STYLESHEET_PI,
                      new Object[] {inFileName})); // "No xml-stylesheet PI found in: "
            // + inFileName);
          }
        }

        if (null != stylesheet) {
          Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer();
          transformer.setErrorListener(new DefaultErrorHandler());

          // Override the output format?
          if (null != outputType) {
            transformer.setOutputProperty(OutputKeys.METHOD, outputType);
          }

          // J2SE does not support Xalan interpretive
          /*
          if (transformer instanceof com.sun.org.apache.xalan.internal.transformer.TransformerImpl)
          {
            com.sun.org.apache.xalan.internal.transformer.TransformerImpl impl = (com.sun.org.apache.xalan.internal.transformer.TransformerImpl)transformer;
            TraceManager tm = impl.getTraceManager();

            if (null != tracer)
              tm.addTraceListener(tracer);

            impl.setQuietConflictWarnings(quietConflictWarnings);

                        // This is currently controlled via TransformerFactoryImpl.
            if (useSourceLocation)
              impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);

            if(recursionLimit>0)
              impl.setRecursionLimit(recursionLimit);

            // sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions
            // impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter );
          }
          */

          int nParams = params.size();

          for (int i = 0; i < nParams; i += 2) {
            transformer.setParameter(
                (String) params.elementAt(i), (String) params.elementAt(i + 1));
          }

          if (uriResolver != null) transformer.setURIResolver(uriResolver);

          if (null != inFileName) {
            if (flavor.equals("d2d")) {

              // Parse in the xml data into a DOM
              DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

              dfactory.setCoalescing(true);
              dfactory.setNamespaceAware(true);

              if (isSecureProcessing) {
                try {
                  dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                } catch (ParserConfigurationException pce) {
                }
              }

              DocumentBuilder docBuilder = dfactory.newDocumentBuilder();

              if (entityResolver != null) docBuilder.setEntityResolver(entityResolver);

              Node xmlDoc = docBuilder.parse(new InputSource(inFileName));
              Document doc = docBuilder.newDocument();
              org.w3c.dom.DocumentFragment outNode = doc.createDocumentFragment();

              transformer.transform(new DOMSource(xmlDoc, inFileName), new DOMResult(outNode));

              // Now serialize output to disk with identity transformer
              Transformer serializer = stf.newTransformer();
              serializer.setErrorListener(new DefaultErrorHandler());

              Properties serializationProps = stylesheet.getOutputProperties();

              serializer.setOutputProperties(serializationProps);

              if (contentHandler != null) {
                SAXResult result = new SAXResult(contentHandler);

                serializer.transform(new DOMSource(outNode), result);
              } else serializer.transform(new DOMSource(outNode), strResult);
            } else if (flavor.equals("th")) {
              for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior
              {
                // System.out.println("Testing the TransformerHandler...");

                XMLReader reader = null;

                // Use JAXP1.1 ( if possible )
                try {
                  javax.xml.parsers.SAXParserFactory factory =
                      javax.xml.parsers.SAXParserFactory.newInstance();

                  factory.setNamespaceAware(true);

                  if (isSecureProcessing) {
                    try {
                      factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    } catch (org.xml.sax.SAXException se) {
                    }
                  }

                  javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();

                  reader = jaxpParser.getXMLReader();
                } catch (javax.xml.parsers.ParserConfigurationException ex) {
                  throw new org.xml.sax.SAXException(ex);
                } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
                  throw new org.xml.sax.SAXException(ex1.toString());
                } catch (NoSuchMethodError ex2) {
                } catch (AbstractMethodError ame) {
                }

                if (null == reader) {
                  reader = XMLReaderFactory.createXMLReader();
                }

                // J2SE does not support Xalan interpretive
                /*
                if (!useXSLTC)
                  stf.setAttribute(com.sun.org.apache.xalan.internal.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL,
                     Boolean.TRUE);
                */

                TransformerHandler th = stf.newTransformerHandler(stylesheet);

                reader.setContentHandler(th);
                reader.setDTDHandler(th);

                if (th instanceof org.xml.sax.ErrorHandler)
                  reader.setErrorHandler((org.xml.sax.ErrorHandler) th);

                try {
                  reader.setProperty("http://xml.org/sax/properties/lexical-handler", th);
                } catch (org.xml.sax.SAXNotRecognizedException e) {
                } catch (org.xml.sax.SAXNotSupportedException e) {
                }
                try {
                  reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
                } catch (org.xml.sax.SAXException se) {
                }

                th.setResult(strResult);

                reader.parse(new InputSource(inFileName));
              }
            } else {
              if (entityResolver != null) {
                XMLReader reader = null;

                // Use JAXP1.1 ( if possible )
                try {
                  javax.xml.parsers.SAXParserFactory factory =
                      javax.xml.parsers.SAXParserFactory.newInstance();

                  factory.setNamespaceAware(true);

                  if (isSecureProcessing) {
                    try {
                      factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    } catch (org.xml.sax.SAXException se) {
                    }
                  }

                  javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();

                  reader = jaxpParser.getXMLReader();
                } catch (javax.xml.parsers.ParserConfigurationException ex) {
                  throw new org.xml.sax.SAXException(ex);
                } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
                  throw new org.xml.sax.SAXException(ex1.toString());
                } catch (NoSuchMethodError ex2) {
                } catch (AbstractMethodError ame) {
                }

                if (null == reader) {
                  reader = XMLReaderFactory.createXMLReader();
                }

                reader.setEntityResolver(entityResolver);

                if (contentHandler != null) {
                  SAXResult result = new SAXResult(contentHandler);

                  transformer.transform(new SAXSource(reader, new InputSource(inFileName)), result);
                } else {
                  transformer.transform(
                      new SAXSource(reader, new InputSource(inFileName)), strResult);
                }
              } else if (contentHandler != null) {
                SAXResult result = new SAXResult(contentHandler);

                transformer.transform(new StreamSource(inFileName), result);
              } else {
                // System.out.println("Starting transform");
                transformer.transform(new StreamSource(inFileName), strResult);
                // System.out.println("Done with transform");
              }
            }
          } else {
            StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>");

            transformer.transform(new StreamSource(reader), strResult);
          }
        } else {
          //          "XSL Process was not successful.");
          msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
          diagnosticsWriter.println(msg);
          doExit(msg);
        }

        // close output streams
        if (null != outFileName && strResult != null) {
          java.io.OutputStream out = strResult.getOutputStream();
          java.io.Writer writer = strResult.getWriter();
          try {
            if (out != null) out.close();
            if (writer != null) writer.close();
          } catch (java.io.IOException ie) {
          }
        }

        long stop = System.currentTimeMillis();
        long millisecondsDuration = stop - start;

        if (doDiag) {
          Object[] msgArgs = new Object[] {inFileName, xslFileName, new Long(millisecondsDuration)};
          msg = XSLMessages.createMessage("diagTiming", msgArgs);
          diagnosticsWriter.println('\n');
          diagnosticsWriter.println(msg);
        }

      } catch (Throwable throwable) {
        while (throwable instanceof com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) {
          throwable =
              ((com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) throwable)
                  .getException();
        }

        if ((throwable instanceof NullPointerException)
            || (throwable instanceof ClassCastException)) doStackDumpOnError = true;

        diagnosticsWriter.println();

        if (doStackDumpOnError) throwable.printStackTrace(dumpWriter);
        else {
          DefaultErrorHandler.printLocation(diagnosticsWriter, throwable);
          diagnosticsWriter.println(
              XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null)
                  + " ("
                  + throwable.getClass().getName()
                  + "): "
                  + throwable.getMessage());
        }

        // diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
        // null)); //"XSL Process was not successful.");
        if (null != dumpFileName) {
          dumpWriter.close();
        }

        doExit(throwable.getMessage());
      }

      if (null != dumpFileName) {
        dumpWriter.close();
      }

      if (null != diagnosticsWriter) {

        // diagnosticsWriter.close();
      }

      // if(!setQuietMode)
      //  diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done");
      // else
      // diagnosticsWriter.println("");  //"Xalan: done");
    }
  }