/**
   * Constructor.
   *
   * @param contentHandler The implemention of the contentHandler operation (toXMLString, digest,
   *     ...)
   */
  public TreeWalker(ContentHandler contentHandler, String systemId) {
    // Set the content handler
    m_contentHandler = contentHandler;
    if (m_contentHandler instanceof SerializationHandler) {
      m_Serializer = (SerializationHandler) m_contentHandler;
    } else m_Serializer = null;

    // Set the system ID, if it is given
    m_contentHandler.setDocumentLocator(m_locator);
    if (systemId != null) m_locator.setSystemId(systemId);
    else {
      try {
        // Bug see Bugzilla  26741
        m_locator.setSystemId(
            SecuritySupport.getSystemProperty("user.dir") + File.separator + "dummy.xsl");
      } catch (SecurityException se) { // user.dir not accessible from applet
      }
    }

    // Set the document locator
    if (m_contentHandler != null) m_contentHandler.setDocumentLocator(m_locator);
    try {
      // Bug see Bugzilla  26741
      m_locator.setSystemId(
          SecuritySupport.getSystemProperty("user.dir") + File.separator + "dummy.xsl");
    } catch (SecurityException se) { // user.dir not accessible from applet

    }
    m_dh = new DOM2Helper();
  }
  /**
   * Overrides the default readObject implementation since we decided it would be cleaner not to
   * serialize the entire tranformer factory. [ ref bugzilla 12317 ] We need to check if the user
   * defined class for URIResolver also implemented Serializable if yes then we need to deserialize
   * the URIResolver Fix for bugzilla bug 22438
   */
  @SuppressWarnings("unchecked")
  private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
      String temp = SecuritySupport.getSystemProperty(DESERIALIZE_TRANSLET);
      if (temp == null || !(temp.length() == 0 || temp.equalsIgnoreCase("true"))) {
        ErrorMsg err = new ErrorMsg(ErrorMsg.DESERIALIZE_TRANSLET_ERR);
        throw new UnsupportedOperationException(err.toString());
      }
    }

    // We have to read serialized fields first.
    ObjectInputStream.GetField gf = is.readFields();
    _name = (String) gf.get("_name", null);
    _bytecodes = (byte[][]) gf.get("_bytecodes", null);
    _class = (Class[]) gf.get("_class", null);
    _transletIndex = gf.get("_transletIndex", -1);

    _outputProperties = (Properties) gf.get("_outputProperties", null);
    _indentNumber = gf.get("_indentNumber", 0);

    if (is.readBoolean()) {
      _uriResolver = (URIResolver) is.readObject();
    }

    _tfactory = new TransformerFactoryImpl();
  }
 /*
  * Check the version of the current JDK against that specified in the
  * parameter
  *
  * There is a proposal to change the java version string to:
  * MAJOR.MINOR.FU.CPU.PSU-BUILDNUMBER_BUGIDNUMBER_OPTIONAL
  * This method would work with both the current format and that proposed
  *
  * @param compareTo a JDK version to be compared to
  * @return true if the current version is the same or above that represented
  * by the parameter
  */
 public static boolean isJavaVersionAtLeast(int compareTo) {
   String javaVersion = SecuritySupport.getSystemProperty("java.version");
   String versions[] = javaVersion.split("\\.", 3);
   if (Integer.parseInt(versions[0]) >= compareTo || Integer.parseInt(versions[1]) >= compareTo) {
     return true;
   }
   return false;
 }
 /*     */ public final void initialize(int node, int last, DOM dom, SortSettings settings)
     /*     */ throws TransletException
       /*     */ {
   /* 104 */ this._dom = dom;
   /* 105 */ this._node = node;
   /* 106 */ this._last = last;
   /* 107 */ this._settings = settings;
   /*     */
   /* 109 */ int levels = settings.getSortOrders().length;
   /* 110 */ this._values = new Object[levels];
   /*     */
   /* 112 */ String colFactClassname = null;
   /*     */ try
   /*     */ {
     /* 115 */ colFactClassname =
         SecuritySupport.getSystemProperty(
             "com.sun.org.apache.xalan.internal.xsltc.COLLATOR_FACTORY");
     /*     */ }
   /*     */ catch (SecurityException e)
   /*     */ {
     /*     */ }
   /*     */
   /* 122 */ if (colFactClassname != null) {
     /*     */ try {
       /* 124 */ Object candObj = ObjectFactory.findProviderClass(colFactClassname, true);
       /* 125 */ this._collatorFactory = ((CollatorFactory) candObj);
       /*     */ } catch (ClassNotFoundException e) {
       /* 127 */ throw new TransletException(e);
       /*     */ }
     /* 129 */ Locale[] locales = settings.getLocales();
     /* 130 */ this._collators = new Collator[levels];
     /* 131 */ for (int i = 0; i < levels; i++) {
       /* 132 */ this._collators[i] = this._collatorFactory.getCollator(locales[i]);
       /*     */ }
     /* 134 */ this._collator = this._collators[0];
     /*     */ } else {
     /* 136 */ this._collators = settings.getCollators();
     /* 137 */ this._collator = this._collators[0];
     /*     */ }
   /*     */ }
  /**
   * Retrieves a cached XMLReader for this thread, or creates a new XMLReader, if the existing
   * reader is in use. When the caller no longer needs the reader, it must release it with a call to
   * {@link #releaseXMLReader}.
   */
  public synchronized XMLReader getXMLReader() throws SAXException {
    XMLReader reader;

    if (m_readers == null) {
      // When the m_readers.get() method is called for the first time
      // on a thread, a new XMLReader will automatically be created.
      m_readers = new ThreadLocal();
    }

    if (m_inUse == null) {
      m_inUse = new HashMap();
    }

    // If the cached reader for this thread is in use, construct a new
    // one; otherwise, return the cached reader unless it isn't an
    // instance of the class set in the 'org.xml.sax.driver' property
    reader = (XMLReader) m_readers.get();
    boolean threadHasReader = (reader != null);
    String factory = SecuritySupport.getSystemProperty(property);
    if (threadHasReader
        && m_inUse.get(reader) != Boolean.TRUE
        && (factory == null || reader.getClass().getName().equals(factory))) {
      m_inUse.put(reader, Boolean.TRUE);
    } else {
      try {
        try {
          // According to JAXP 1.2 specification, if a SAXSource
          // is created using a SAX InputSource the Transformer or
          // TransformerFactory creates a reader via the
          // XMLReaderFactory if setXMLReader is not used
          reader = XMLReaderFactory.createXMLReader();
          try {
            reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _secureProcessing);
          } catch (SAXNotRecognizedException e) {
            System.err.println("Warning:  " + reader.getClass().getName() + ": " + e.getMessage());
          }
        } catch (Exception e) {
          try {
            // If unable to create an instance, let's try to use
            // the XMLReader from JAXP
            if (m_parserFactory == null) {
              m_parserFactory = FactoryImpl.getSAXFactory(m_useServicesMechanism);
              m_parserFactory.setNamespaceAware(true);
            }

            reader = m_parserFactory.newSAXParser().getXMLReader();
          } catch (ParserConfigurationException pce) {
            throw pce; // pass along pce
          }
        }
        try {
          reader.setFeature(NAMESPACES_FEATURE, true);
          reader.setFeature(NAMESPACE_PREFIXES_FEATURE, false);
        } catch (SAXException se) {
          // Try to carry on if we've got a parser that
          // doesn't know about namespace prefixes.
        }
      } catch (ParserConfigurationException ex) {
        throw new SAXException(ex);
      } catch (FactoryConfigurationError ex1) {
        throw new SAXException(ex1.toString());
      } catch (NoSuchMethodError ex2) {
      } catch (AbstractMethodError ame) {
      }

      // Cache the XMLReader if this is the first time we've created
      // a reader for this thread.
      if (!threadHasReader) {
        m_readers.set(reader);
        m_inUse.put(reader, Boolean.TRUE);
      }
    }

    try {
      // reader is cached, but this property might have been reset
      reader.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD);
    } catch (SAXException se) {
      System.err.println("Warning:  " + reader.getClass().getName() + ": " + se.getMessage());
    }

    try {
      if (_xmlSecurityManager != null) {
        for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
          reader.setProperty(limit.apiProperty(), _xmlSecurityManager.getLimitValueAsString(limit));
        }
        if (_xmlSecurityManager.printEntityCountInfo()) {
          reader.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
        }
      }
    } catch (SAXException se) {
      System.err.println("Warning:  " + reader.getClass().getName() + ": " + se.getMessage());
    }

    return reader;
  }
  /**
   * Fillin hash with info about SystemProperties.
   *
   * <p>Logs java.class.path and other likely paths; then attempts to search those paths for .jar
   * files with Xalan-related classes.
   *
   * <p>//@todo NOTE: We don't actually search java.ext.dirs for // *.jar files therein! This should
   * be updated
   *
   * @param h Hashtable to put information in
   * @see #jarNames
   * @see #checkPathForJars(String, String[])
   */
  protected void checkSystemProperties(Hashtable h) {

    if (null == h) h = new Hashtable();

    // Grab java version for later use
    try {
      String javaVersion = SecuritySupport.getSystemProperty("java.version");

      h.put("java.version", javaVersion);
    } catch (SecurityException se) {

      // For applet context, etc.
      h.put(
          "java.version", "WARNING: SecurityException thrown accessing system version properties");
    }

    // Printout jar files on classpath(s) that may affect operation
    //  Do this in order
    try {

      // This is present in all JVM's
      String cp = SecuritySupport.getSystemProperty("java.class.path");

      h.put("java.class.path", cp);

      Vector classpathJars = checkPathForJars(cp, jarNames);

      if (null != classpathJars) h.put(FOUNDCLASSES + "java.class.path", classpathJars);

      // Also check for JDK 1.2+ type classpaths
      String othercp = SecuritySupport.getSystemProperty("sun.boot.class.path");

      if (null != othercp) {
        h.put("sun.boot.class.path", othercp);

        classpathJars = checkPathForJars(othercp, jarNames);

        if (null != classpathJars) h.put(FOUNDCLASSES + "sun.boot.class.path", classpathJars);
      }

      // @todo NOTE: We don't actually search java.ext.dirs for
      //  *.jar files therein! This should be updated
      othercp = SecuritySupport.getSystemProperty("java.ext.dirs");

      if (null != othercp) {
        h.put("java.ext.dirs", othercp);

        classpathJars = checkPathForJars(othercp, jarNames);

        if (null != classpathJars) h.put(FOUNDCLASSES + "java.ext.dirs", classpathJars);
      }

      // @todo also check other System properties' paths?
      //  v2 = checkPathForJars(System.getProperty("sun.boot.library.path"), jarNames);   // ?? may
      // not be needed
      //  v3 = checkPathForJars(System.getProperty("java.library.path"), jarNames);   // ?? may not
      // be needed
    } catch (SecurityException se2) {
      // For applet context, etc.
      h.put(
          "java.class.path",
          "WARNING: SecurityException thrown accessing system classpath properties");
    }
  }
  /**
   * Load the properties file from a resource stream. If a key name such as "org.apache.xslt.xxx",
   * fix up the start of string to be a curly namespace. If a key name starts with
   * "xslt.output.xxx", clip off "xslt.output.". If a key name *or* a key value is discovered, check
   * for \u003a in the text, and fix it up to be ":", since earlier versions of the JDK do not
   * handle the escape sequence (at least in key names).
   *
   * @param resourceName non-null reference to resource name.
   * @param defaults Default properties, which may be null.
   */
  private static Properties loadPropertiesFile(final String resourceName, Properties defaults)
      throws IOException {

    // This static method should eventually be moved to a thread-specific class
    // so that we can cache the ContextClassLoader and bottleneck all properties file
    // loading throughout Xalan.

    Properties props = new Properties(defaults);

    InputStream is = null;
    BufferedInputStream bis = null;

    try {
      if (ACCESS_CONTROLLER_CLASS != null) {
        is =
            (InputStream)
                AccessController.doPrivileged(
                    new PrivilegedAction() {
                      public Object run() {
                        return OutputPropertiesFactory.class.getResourceAsStream(resourceName);
                      }
                    });
      } else {
        // User may be using older JDK ( JDK < 1.2 )
        is = OutputPropertiesFactory.class.getResourceAsStream(resourceName);
      }

      bis = new BufferedInputStream(is);
      props.load(bis);
    } catch (IOException ioe) {
      if (defaults == null) {
        throw ioe;
      } else {
        throw new WrappedRuntimeException(
            Utils.messages.createMessage(
                MsgKey.ER_COULD_NOT_LOAD_RESOURCE, new Object[] {resourceName}),
            ioe);
        // "Could not load '"+resourceName+"' (check CLASSPATH), now using just the defaults ",
        // ioe);
      }
    } catch (SecurityException se) {
      // Repeat IOException handling for sandbox/applet case -sc
      if (defaults == null) {
        throw se;
      } else {
        throw new WrappedRuntimeException(
            Utils.messages.createMessage(
                MsgKey.ER_COULD_NOT_LOAD_RESOURCE, new Object[] {resourceName}),
            se);
        // "Could not load '"+resourceName+"' (check CLASSPATH, applet security), now using just the
        // defaults ", se);
      }
    } finally {
      if (bis != null) {
        bis.close();
      }
      if (is != null) {
        is.close();
      }
    }

    // Note that we're working at the HashTable level here,
    // and not at the Properties level!  This is important
    // because we don't want to modify the default properties.
    // NB: If fixupPropertyString ends up changing the property
    // name or value, we need to remove the old key and re-add
    // with the new key and value.  However, then our Enumeration
    // could lose its place in the HashTable.  So, we first
    // clone the HashTable and enumerate over that since the
    // clone will not change.  When we migrate to Collections,
    // this code should be revisited and cleaned up to use
    // an Iterator which may (or may not) alleviate the need for
    // the clone.  Many thanks to Padraig O'hIceadha
    // <*****@*****.**> for finding this problem.  Bugzilla 2000.

    Enumeration keys = ((Properties) props.clone()).keys();
    while (keys.hasMoreElements()) {
      String key = (String) keys.nextElement();
      // Now check if the given key was specified as a
      // System property. If so, the system property
      // overides the default value in the propery file.
      String value = null;
      try {
        value = SecuritySupport.getSystemProperty(key);
      } catch (SecurityException se) {
        // No-op for sandbox/applet case, leave null -sc
      }
      if (value == null) value = (String) props.get(key);

      String newKey = fixupPropertyString(key, true);
      String newValue = null;
      try {
        newValue = SecuritySupport.getSystemProperty(newKey);
      } catch (SecurityException se) {
        // No-op for sandbox/applet case, leave null -sc
      }
      if (newValue == null) newValue = fixupPropertyString(value, false);
      else newValue = fixupPropertyString(newValue, false);

      if (key != newKey || value != newValue) {
        props.remove(key);
        props.put(newKey, newValue);
      }
    }

    return props;
  }
Beispiel #8
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");
    }
  }