Exemplo n.º 1
0
 private SVNErrorMessage readData(
     InputStream is, String method, String path, DefaultHandler handler)
     throws FactoryConfigurationError, UnsupportedEncodingException, IOException {
   try {
     if (mySAXParser == null) {
       mySAXParser = getSAXParserFactory().newSAXParser();
     }
     XMLReader reader = new XMLReader(is);
     while (!reader.isClosed()) {
       org.xml.sax.XMLReader xmlReader = mySAXParser.getXMLReader();
       xmlReader.setContentHandler(handler);
       xmlReader.setDTDHandler(handler);
       xmlReader.setErrorHandler(handler);
       xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
       xmlReader.parse(new InputSource(reader));
     }
   } catch (SAXException e) {
     if (e instanceof SAXParseException) {
       if (handler instanceof DAVErrorHandler) {
         // failed to read svn-specific error, return null.
         return null;
       }
     } else if (e.getException() instanceof SVNException) {
       return ((SVNException) e.getException()).getErrorMessage();
     } else if (e.getCause() instanceof SVNException) {
       return ((SVNException) e.getCause()).getErrorMessage();
     }
     return SVNErrorMessage.create(
         SVNErrorCode.RA_DAV_REQUEST_FAILED,
         "Processing {0} request response failed: {1} ({2}) ",
         new Object[] {method, e.getMessage(), path});
   } catch (ParserConfigurationException e) {
     return SVNErrorMessage.create(
         SVNErrorCode.RA_DAV_REQUEST_FAILED,
         "XML parser configuration error while processing {0} request response: {1} ({2}) ",
         new Object[] {method, e.getMessage(), path});
   } catch (EOFException e) {
     // skip it.
   } finally {
     if (mySAXParser != null) {
       // to avoid memory leaks when connection is cached.
       org.xml.sax.XMLReader xmlReader = null;
       try {
         xmlReader = mySAXParser.getXMLReader();
       } catch (SAXException e) {
       }
       if (xmlReader != null) {
         xmlReader.setContentHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setDTDHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setErrorHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
       }
     }
     myRepository.getDebugLog().flushStream(is);
   }
   return null;
 }
Exemplo n.º 2
0
  public void process(Exchange exchange) throws Exception {
    Jaxp11XMLReaderCreator xmlCreator = new Jaxp11XMLReaderCreator();
    DefaultValidationErrorHandler errorHandler = new DefaultValidationErrorHandler();

    PropertyMapBuilder mapBuilder = new PropertyMapBuilder();
    mapBuilder.put(ValidateProperty.XML_READER_CREATOR, xmlCreator);
    mapBuilder.put(ValidateProperty.ERROR_HANDLER, errorHandler);
    PropertyMap propertyMap = mapBuilder.toPropertyMap();

    Validator validator = getSchema().createValidator(propertyMap);

    Message in = exchange.getIn();
    SAXSource saxSource = in.getBody(SAXSource.class);
    if (saxSource == null) {
      Source source = exchange.getIn().getMandatoryBody(Source.class);
      saxSource = ExchangeHelper.convertToMandatoryType(exchange, SAXSource.class, source);
    }
    InputSource bodyInput = saxSource.getInputSource();

    // now lets parse the body using the validator
    XMLReader reader = xmlCreator.createXMLReader();
    reader.setContentHandler(validator.getContentHandler());
    reader.setDTDHandler(validator.getDTDHandler());
    reader.setErrorHandler(errorHandler);
    reader.parse(bodyInput);

    errorHandler.handleErrors(exchange, schema);
  }
 /** Loads edits file, uses visitor to process all elements */
 public void loadEdits() throws IOException {
   try {
     XMLReader xr = XMLReaderFactory.createXMLReader();
     xr.setContentHandler(this);
     xr.setErrorHandler(this);
     xr.setDTDHandler(null);
     xr.parse(new InputSource(fileReader));
     visitor.close(null);
   } catch (SAXParseException e) {
     System.out.println(
         "XML parsing error: "
             + "\n"
             + "Line:    "
             + e.getLineNumber()
             + "\n"
             + "URI:     "
             + e.getSystemId()
             + "\n"
             + "Message: "
             + e.getMessage());
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (SAXException e) {
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (RuntimeException e) {
     visitor.close(e);
     throw e;
   } finally {
     fileReader.close();
   }
 }
Exemplo n.º 4
0
 /**
  * Validates given XML file using specified schema.
  *
  * @param fileUrl the URL of the file to be validated.
  * @param schemaUrl the URL of the schema to be used.
  * @throws ParserConfigurationException if parser is badly configured.
  * @throws IOException if the schema does not exist.
  * @throws SAXException if the schema is malformed.
  */
 public void validate(URL fileUrl, URL schemaUrl)
     throws SAXException, ParserConfigurationException, IOException {
   Verifier verifier = getVerifier(schemaUrl);
   XMLReader reader = saxParser.getXMLReader();
   InputSource source = new InputSource(fileUrl.toString());
   reader.setContentHandler(verifier);
   reader.setDTDHandler(verifier);
   reader.parse(source);
 }
Exemplo n.º 5
0
  /**
   * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link
   * org.xml.sax.helpers.DefaultHandler}.
   *
   * @param is The InputSource containing the content to be parsed.
   * @param dh The SAX DefaultHandler to use.
   * @throws IllegalArgumentException If the <code>InputSource</code> object is <code>null</code>.
   * @throws IOException If any IO errors occur.
   * @throws SAXException If any SAX errors occur during processing.
   * @see org.xml.sax.DocumentHandler
   */
  public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException {
    if (is == null) {
      throw new IllegalArgumentException("InputSource cannot be null");
    }

    XMLReader reader = this.getXMLReader();
    if (dh != null) {
      reader.setContentHandler(dh);
      reader.setEntityResolver(dh);
      reader.setErrorHandler(dh);
      reader.setDTDHandler(dh);
    }
    reader.parse(is);
  }
Exemplo n.º 6
0
 public void parse(InputSource paramInputSource, DefaultHandler paramDefaultHandler)
     throws SAXException, IOException {
   if (paramInputSource == null) {
     throw new IllegalArgumentException("InputSource cannot be null");
   }
   XMLReader localXMLReader = getXMLReader();
   if (paramDefaultHandler != null) {
     localXMLReader.setContentHandler(paramDefaultHandler);
     localXMLReader.setEntityResolver(paramDefaultHandler);
     localXMLReader.setErrorHandler(paramDefaultHandler);
     localXMLReader.setDTDHandler(paramDefaultHandler);
   }
   localXMLReader.parse(paramInputSource);
 }
Exemplo n.º 7
0
  /**
   * This will create a SAX XMLReader capable of parsing a DTD and configure it so that the DTD
   * parsing events are routed to the handlers registered onto this SAXOutputter.
   *
   * @return <code>XMLReader</code> a SAX2 parser.
   * @throws JDOMException if no parser can be created.
   */
  private XMLReader createDTDParser() throws JDOMException {
    XMLReader parser = null;

    // Get a parser instance
    try {
      parser = createParser();
    } catch (Exception ex1) {
      throw new JDOMException("Error in SAX parser allocation", ex1);
    }

    // Register handlers
    if (this.getDTDHandler() != null) {
      parser.setDTDHandler(this.getDTDHandler());
    }
    if (this.getEntityResolver() != null) {
      parser.setEntityResolver(this.getEntityResolver());
    }
    if (this.getLexicalHandler() != null) {
      try {
        parser.setProperty(SAX_PROPERTY_LEXICAL_HANDLER, this.getLexicalHandler());
      } catch (SAXException ex1) {
        try {
          parser.setProperty(SAX_PROPERTY_LEXICAL_HANDLER_ALT, this.getLexicalHandler());
        } catch (SAXException ex2) {
          // Forget it!
        }
      }
    }
    if (this.getDeclHandler() != null) {
      try {
        parser.setProperty(SAX_PROPERTY_DECLARATION_HANDLER, this.getDeclHandler());
      } catch (SAXException ex1) {
        try {
          parser.setProperty(SAX_PROPERTY_DECLARATION_HANDLER_ALT, this.getDeclHandler());
        } catch (SAXException ex2) {
          // Forget it!
        }
      }
    }

    // Absorb errors as much as possible, per Laurent
    parser.setErrorHandler(new DefaultHandler());

    return parser;
  }
Exemplo n.º 8
0
  // {{{ loadMode() method
  public void loadMode(Mode mode, XModeHandler xmh) {
    String fileName = (String) mode.getProperty("file");

    Log.log(Log.NOTICE, this, "Loading edit mode " + fileName);

    XMLReader parser;
    try {
      parser = XMLReaderFactory.createXMLReader();
    } catch (SAXException saxe) {
      Log.log(Log.ERROR, this, saxe);
      return;
    }
    mode.setTokenMarker(xmh.getTokenMarker());

    InputStream resource = ClassLoader.getSystemClassLoader().getResourceAsStream(fileName);
    if (resource == null) {
      // don't just print an error to console. This is a problem.
      throw new RuntimeException("File not found " + fileName);
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(resource));

    try {
      InputSource isrc = new InputSource(br);
      // isrc.setSystemId("jedit.jar");
      parser.setContentHandler(xmh);
      parser.setDTDHandler(xmh);
      parser.setEntityResolver(xmh);
      parser.setErrorHandler(xmh);
      parser.parse(isrc);

      mode.setProperties(xmh.getModeProperties());
    } catch (Throwable e) {
      error(fileName, e);
    } finally {
      IOUtilities.closeQuietly(resource);
    }
  } // }}}
Exemplo n.º 9
0
  public void parse(InputSource input) throws SAXException, IOException {
    try {
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
      XMLReader reader = parser.getXMLReader();

      reader.setFeature("http://xml.org/sax/features/namespaces", true);

      if (parser.getClass().getName().equals("org.apache.xerces.jaxp.SAXParserImpl")) {
        // disable DTD validate
        String feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
        reader.setFeature(feature, false);
      }

      reader.setContentHandler(this);
      reader.setErrorHandler(this);
      reader.setDTDHandler(this);
      reader.setEntityResolver(this);

      reader.parse(input);
    } catch (ParserConfigurationException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 10
0
  public void validate(Source source, Result result) throws SAXException, IOException {
    if (result instanceof SAXResult || result == null) {
      final SAXSource saxSource = (SAXSource) source;
      final SAXResult saxResult = (SAXResult) result;

      if (result != null) {
        setContentHandler(saxResult.getHandler());
      }

      try {
        XMLReader reader = saxSource.getXMLReader();
        if (reader == null) {
          // create one now
          SAXParserFactory spf = SAXParserFactory.newInstance();
          spf.setNamespaceAware(true);
          try {
            reader = spf.newSAXParser().getXMLReader();
            // If this is a Xerces SAX parser, set the security manager if there is one
            if (reader instanceof com.sun.org.apache.xerces.internal.parsers.SAXParser) {
              SecurityManager securityManager =
                  (SecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
              if (securityManager != null) {
                try {
                  reader.setProperty(SECURITY_MANAGER, securityManager);
                }
                // Ignore the exception if the security manager cannot be set.
                catch (SAXException exc) {
                }
              }
            }
          } catch (Exception e) {
            // this is impossible, but better safe than sorry
            throw new FactoryConfigurationError(e);
          }
        }

        // If XML names and Namespace URIs are already internalized we
        // can avoid running them through the SymbolTable.
        try {
          fStringsInternalized = reader.getFeature(STRING_INTERNING);
        } catch (SAXException exc) {
          // The feature isn't recognized or getting it is not supported.
          // In either case, assume that strings are not internalized.
          fStringsInternalized = false;
        }

        ErrorHandler errorHandler = fComponentManager.getErrorHandler();
        reader.setErrorHandler(
            errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance());
        reader.setEntityResolver(fResolutionForwarder);
        fResolutionForwarder.setEntityResolver(fComponentManager.getResourceResolver());
        reader.setContentHandler(this);
        reader.setDTDHandler(this);

        InputSource is = saxSource.getInputSource();
        reader.parse(is);
      } finally {
        // release the reference to user's handler ASAP
        setContentHandler(null);
      }
      return;
    }
    throw new IllegalArgumentException(
        JAXPValidationMessageFormatter.formatMessage(
            Locale.getDefault(),
            "SourceResultMismatch",
            new Object[] {source.getClass().getName(), result.getClass().getName()}));
  }
Exemplo n.º 11
0
  public static FSLock convertDAVLockToSVNLock(
      DAVLock davLock, String path, boolean isSVNClient, SAXParserFactory saxParserFactory)
      throws DAVException {
    if (davLock.getType() != DAVLockType.WRITE) {
      throw new DAVException(
          "Only 'write' locks are supported.",
          HttpServletResponse.SC_BAD_REQUEST,
          DAVErrorCode.LOCK_SAVE_LOCK);
    }
    if (davLock.getScope() != DAVLockScope.EXCLUSIVE) {
      throw new DAVException(
          "Only exclusive locks are supported.",
          HttpServletResponse.SC_BAD_REQUEST,
          DAVErrorCode.LOCK_SAVE_LOCK);
    }

    boolean isDAVComment = false;
    String comment = null;
    if (davLock.getOwner() != null) {
      if (isSVNClient) {
        try {
          SAXParser xmlParser = saxParserFactory.newSAXParser();
          XMLReader reader = xmlParser.getXMLReader();
          FetchXMLHandler handler = new FetchXMLHandler(DAVElement.LOCK_OWNER);
          reader.setContentHandler(handler);
          reader.setDTDHandler(handler);
          reader.setErrorHandler(handler);
          reader.setEntityResolver(handler);
          String owner = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + davLock.getOwner();
          reader.parse(new InputSource(new ByteArrayInputStream(owner.getBytes())));
          comment = handler.getData();
        } catch (ParserConfigurationException e) {
          throw new DAVException(
              e.getMessage(),
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              DAVErrorCode.LOCK_SAVE_LOCK);
        } catch (SAXException e) {
          throw new DAVException(
              e.getMessage(),
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              DAVErrorCode.LOCK_SAVE_LOCK);
        } catch (IOException e) {
          throw new DAVException(
              e.getMessage(),
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              DAVErrorCode.LOCK_SAVE_LOCK);
        }
      } else {
        isDAVComment = true;
        comment = davLock.getOwner();
      }
    }

    return new FSLock(
        path,
        davLock.getLockToken(),
        davLock.getAuthUser(),
        comment,
        new Date(System.currentTimeMillis()),
        davLock.getTimeOutDate(),
        isDAVComment);
  }
Exemplo n.º 12
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");
    }
  }
  /**
   * Parses the project file, configuring the project as it goes.
   *
   * @param project the current project
   * @param source the xml source
   * @param handler the root handler to use (contains the current context)
   * @exception BuildException if the configuration is invalid or cannot be read
   */
  public void parse(Project project, Object source, RootHandler handler) throws BuildException {

    AntXMLContext context = handler.context;

    File buildFile = null;
    URL url = null;
    String buildFileName = null;

    if (source instanceof File) {
      buildFile = (File) source;
    } else if (source instanceof URL) {
      url = (URL) source;
    } else if (source instanceof Resource) {
      FileProvider fp = (FileProvider) ((Resource) source).as(FileProvider.class);
      if (fp != null) {
        buildFile = fp.getFile();
      } else {
        URLProvider up = (URLProvider) ((Resource) source).as(URLProvider.class);
        if (up != null) {
          url = up.getURL();
        }
      }
    }
    if (buildFile != null) {
      buildFile = FILE_UTILS.normalize(buildFile.getAbsolutePath());
      context.setBuildFile(buildFile);
      buildFileName = buildFile.toString();
    } else if (url != null) {
      try {
        context.setBuildFile((File) null);
        context.setBuildFile(url);
      } catch (java.net.MalformedURLException ex) {
        throw new BuildException(ex);
      }
      buildFileName = url.toString();
    } else {
      throw new BuildException(
          "Source " + source.getClass().getName() + " not supported by this plugin");
    }
    InputStream inputStream = null;
    InputSource inputSource = null;
    ZipFile zf = null;

    try {
      /** SAX 2 style parser used to parse the given file. */
      XMLReader parser = JAXPUtils.getNamespaceXMLReader();

      String uri = null;
      if (buildFile != null) {
        uri = FILE_UTILS.toURI(buildFile.getAbsolutePath());
        inputStream = new FileInputStream(buildFile);
      } else {
        uri = url.toString();
        int pling = -1;
        if (uri.startsWith("jar:file") && (pling = uri.indexOf("!/")) > -1) {
          zf = new ZipFile(org.apache.tools.ant.launch.Locator.fromJarURI(uri), "UTF-8");
          inputStream = zf.getInputStream(zf.getEntry(uri.substring(pling + 1)));
        } else {
          inputStream = url.openStream();
        }
      }

      inputSource = new InputSource(inputStream);
      if (uri != null) {
        inputSource.setSystemId(uri);
      }
      project.log(
          "parsing buildfile "
              + buildFileName
              + " with URI = "
              + uri
              + (zf != null ? " from a zip file" : ""),
          Project.MSG_VERBOSE);

      DefaultHandler hb = handler;

      parser.setContentHandler(hb);
      parser.setEntityResolver(hb);
      parser.setErrorHandler(hb);
      parser.setDTDHandler(hb);
      parser.parse(inputSource);
    } catch (SAXParseException exc) {
      Location location =
          new Location(exc.getSystemId(), exc.getLineNumber(), exc.getColumnNumber());

      Throwable t = exc.getException();
      if (t instanceof BuildException) {
        BuildException be = (BuildException) t;
        if (be.getLocation() == Location.UNKNOWN_LOCATION) {
          be.setLocation(location);
        }
        throw be;
      }
      throw new BuildException(exc.getMessage(), t == null ? exc : t, location);
    } catch (SAXException exc) {
      Throwable t = exc.getException();
      if (t instanceof BuildException) {
        throw (BuildException) t;
      }
      throw new BuildException(exc.getMessage(), t == null ? exc : t);
    } catch (FileNotFoundException exc) {
      throw new BuildException(exc);
    } catch (UnsupportedEncodingException exc) {
      throw new BuildException("Encoding of project file " + buildFileName + " is invalid.", exc);
    } catch (IOException exc) {
      throw new BuildException(
          "Error reading project file " + buildFileName + ": " + exc.getMessage(), exc);
    } finally {
      FileUtils.close(inputStream);
      ZipFile.closeQuietly(zf);
    }
  }
Exemplo n.º 14
0
 /** Initializes the reader for this parser. */
 private void initialize() {
   reader.setContentHandler(this);
   reader.setDTDHandler(this);
   reader.setEntityResolver(this);
   reader.setErrorHandler(this);
 }
 // Register handler directly with the incremental parser
 public void setDTDHandler(org.xml.sax.DTDHandler handler) {
   // Typecast required in Xerces2; SAXParser doesn't inheret XMLReader
   // %OPT% Cast at asignment?
   ((XMLReader) fIncrementalParser).setDTDHandler(handler);
 }
 /**
  * @param arg0
  * @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler)
  */
 public void setDTDHandler(DTDHandler arg0) {
   wrappedReader.setDTDHandler(arg0);
 }
Exemplo n.º 17
0
  /**
   * Get an instance of a DTM, loaded with the content from the specified source. If the unique flag
   * is true, a new instance will always be returned. Otherwise it is up to the DTMManager to return
   * a new instance or an instance that it already created and may be being used by someone else. (I
   * think more parameters will need to be added for error handling, and entity resolution).
   *
   * @param source the specification of the source object.
   * @param unique true if the returned DTM must be unique, probably because it is going to be
   *     mutated.
   * @param whiteSpaceFilter Enables filtering of whitespace nodes, and may be null.
   * @param incremental true if the DTM should be built incrementally, if possible.
   * @param doIndexing true if the caller considers it worth it to use indexing schemes.
   * @param hasUserReader true if <code>source</code> is a <code>SAXSource</code> object that has an
   *     <code>XMLReader</code>, that was specified by the user.
   * @param size Specifies initial size of tables that represent the DTM
   * @param buildIdIndex true if the id index table should be built.
   * @param newNameTable true if we want to use a separate ExpandedNameTable for this DTM.
   * @return a non-null DTM reference.
   */
  public DTM getDTM(
      Source source,
      boolean unique,
      DTMWSFilter whiteSpaceFilter,
      boolean incremental,
      boolean doIndexing,
      boolean hasUserReader,
      int size,
      boolean buildIdIndex,
      boolean newNameTable) {
    if (DEBUG && null != source) {
      System.out.println(
          "Starting " + (unique ? "UNIQUE" : "shared") + " source: " + source.getSystemId());
    }

    int dtmPos = getFirstFreeDTMID();
    int documentID = dtmPos << IDENT_DTM_NODE_BITS;

    if ((null != source) && source instanceof StAXSource) {
      final StAXSource staxSource = (StAXSource) source;
      StAXEvent2SAX staxevent2sax = null;
      StAXStream2SAX staxStream2SAX = null;
      if (staxSource.getXMLEventReader() != null) {
        final XMLEventReader xmlEventReader = staxSource.getXMLEventReader();
        staxevent2sax = new StAXEvent2SAX(xmlEventReader);
      } else if (staxSource.getXMLStreamReader() != null) {
        final XMLStreamReader xmlStreamReader = staxSource.getXMLStreamReader();
        staxStream2SAX = new StAXStream2SAX(xmlStreamReader);
      }

      SAXImpl dtm;

      if (size <= 0) {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                DTMDefaultBase.DEFAULT_BLOCKSIZE,
                buildIdIndex,
                newNameTable);
      } else {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                size,
                buildIdIndex,
                newNameTable);
      }

      dtm.setDocumentURI(source.getSystemId());

      addDTM(dtm, dtmPos, 0);

      try {
        if (staxevent2sax != null) {
          staxevent2sax.setContentHandler(dtm);
          staxevent2sax.parse();
        } else if (staxStream2SAX != null) {
          staxStream2SAX.setContentHandler(dtm);
          staxStream2SAX.parse();
        }

      } catch (RuntimeException re) {
        throw re;
      } catch (Exception e) {
        throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(e);
      }

      return dtm;
    } else if ((null != source) && source instanceof DOMSource) {
      final DOMSource domsrc = (DOMSource) source;
      final org.w3c.dom.Node node = domsrc.getNode();
      final DOM2SAX dom2sax = new DOM2SAX(node);

      SAXImpl dtm;

      if (size <= 0) {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                DTMDefaultBase.DEFAULT_BLOCKSIZE,
                buildIdIndex,
                newNameTable);
      } else {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                size,
                buildIdIndex,
                newNameTable);
      }

      dtm.setDocumentURI(source.getSystemId());

      addDTM(dtm, dtmPos, 0);

      dom2sax.setContentHandler(dtm);

      try {
        dom2sax.parse();
      } catch (RuntimeException re) {
        throw re;
      } catch (Exception e) {
        throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(e);
      }

      return dtm;
    } else {
      boolean isSAXSource = (null != source) ? (source instanceof SAXSource) : true;
      boolean isStreamSource = (null != source) ? (source instanceof StreamSource) : false;

      if (isSAXSource || isStreamSource) {
        XMLReader reader;
        InputSource xmlSource;

        if (null == source) {
          xmlSource = null;
          reader = null;
          hasUserReader = false; // Make sure the user didn't lie
        } else {
          reader = getXMLReader(source);
          xmlSource = SAXSource.sourceToInputSource(source);

          String urlOfSource = xmlSource.getSystemId();

          if (null != urlOfSource) {
            try {
              urlOfSource = SystemIDResolver.getAbsoluteURI(urlOfSource);
            } catch (Exception e) {
              // %REVIEW% Is there a better way to send a warning?
              System.err.println("Can not absolutize URL: " + urlOfSource);
            }

            xmlSource.setSystemId(urlOfSource);
          }
        }

        // Create the basic SAX2DTM.
        SAXImpl dtm;
        if (size <= 0) {
          dtm =
              new SAXImpl(
                  this,
                  source,
                  documentID,
                  whiteSpaceFilter,
                  null,
                  doIndexing,
                  DTMDefaultBase.DEFAULT_BLOCKSIZE,
                  buildIdIndex,
                  newNameTable);
        } else {
          dtm =
              new SAXImpl(
                  this,
                  source,
                  documentID,
                  whiteSpaceFilter,
                  null,
                  doIndexing,
                  size,
                  buildIdIndex,
                  newNameTable);
        }

        // Go ahead and add the DTM to the lookup table.  This needs to be
        // done before any parsing occurs. Note offset 0, since we've just
        // created a new DTM.
        addDTM(dtm, dtmPos, 0);

        if (null == reader) {
          // Then the user will construct it themselves.
          return dtm;
        }

        reader.setContentHandler(dtm.getBuilder());

        if (!hasUserReader || null == reader.getDTDHandler()) {
          reader.setDTDHandler(dtm);
        }

        if (!hasUserReader || null == reader.getErrorHandler()) {
          reader.setErrorHandler(dtm);
        }

        try {
          reader.setProperty("http://xml.org/sax/properties/lexical-handler", dtm);
        } catch (SAXNotRecognizedException e) {
        } catch (SAXNotSupportedException e) {
        }

        try {
          reader.parse(xmlSource);
        } catch (RuntimeException re) {
          throw re;
        } catch (Exception e) {
          throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(e);
        } finally {
          if (!hasUserReader) {
            releaseXMLReader(reader);
          }
        }

        if (DUMPTREE) {
          System.out.println("Dumping SAX2DOM");
          dtm.dumpDTM(System.err);
        }

        return dtm;
      } else {
        // It should have been handled by a derived class or the caller
        // made a mistake.
        throw new DTMException(
            XMLMessages.createXMLMessage(
                XMLErrorResources.ER_NOT_SUPPORTED, new Object[] {source}));
      }
    }
  }
Exemplo n.º 18
0
 public void setDTDHandler(DTDHandler handler) {
   expatReader.setDTDHandler(handler);
 }