/**
   * This method overrides the superclass method of the same name in order to add catalog entries
   * back to the controlling XMLCatalog instance. In this way, we can add classpath lookup for these
   * entries.
   *
   * <p>When we add an external catalog file, the entries inside it get parsed by this method.
   * Therefore, we override it to add each of them back to the controlling XMLCatalog instance. This
   * is done by performing a callback to the ApacheCatalogResolver, which in turn calls the
   * XMLCatalog.
   *
   * <p>XMLCatalog currently only understands <code>PUBLIC</code> and <code>URI</code> entry types,
   * so we ignore the other types.
   *
   * @param entry The CatalogEntry to process.
   */
  public void addEntry(CatalogEntry entry) {

    int type = entry.getEntryType();

    if (type == PUBLIC) {

      String publicid = PublicId.normalize(entry.getEntryArg(0));
      String systemid = normalizeURI(entry.getEntryArg(1));

      if (resolver == null) {
        catalogManager.debug.message(1, "Internal Error: null ApacheCatalogResolver");
      } else {
        resolver.addPublicEntry(publicid, systemid, base);
      }

    } else if (type == URI) {

      String uri = normalizeURI(entry.getEntryArg(0));
      String altURI = normalizeURI(entry.getEntryArg(1));

      if (resolver == null) {
        catalogManager.debug.message(1, "Internal Error: null ApacheCatalogResolver");
      } else {
        resolver.addURIEntry(uri, altURI, base);
      }
    }

    super.addEntry(entry);
  }
  /**
   * Resolves WSDL URIs using Apache Commons Resolver API.
   *
   * @param importURI a URI specifying the document to import
   * @param parent a URI specifying the location of the parent document doing the importing
   * @return the resolved import location, or null if no indirection is performed
   */
  public String getRedirectedURI(String importURI, String parent) {
    String resolvedImportLocation = null;

    try {
      resolvedImportLocation = this.catalogResolver.resolveSystem(importURI);
      if (resolvedImportLocation == null) {
        resolvedImportLocation = catalogResolver.resolveURI(importURI);
      }
      if (resolvedImportLocation == null) {
        resolvedImportLocation = catalogResolver.resolvePublic(importURI, parent);
      }

    } catch (IOException e) {
      throw new RuntimeException("Catalog resolution failed", e);
    }
    return resolvedImportLocation;
  }
Example #3
0
  /**
   * Get CatalogResolver.
   *
   * @return CatalogResolver
   */
  public static synchronized CatalogResolver getCatalogResolver() {
    if (catalogResolver == null) {
      final CatalogManager manager = new CatalogManager();
      manager.setIgnoreMissingProperties(true);
      manager.setUseStaticCatalog(false); // We'll use a private catalog.
      manager.setPreferPublic(true);

      // manager.setVerbosity(10);
      catalogResolver = new CatalogResolver(manager);

      final File catalogFilePath = new File(ditaDir, FILE_NAME_CATALOG);

      final Catalog catalog = catalogResolver.getCatalog();
      try {
        catalog.parseCatalog(catalogFilePath.toURI().toURL());
      } catch (final Exception e) {
        logger.logException(e);
      }
    }

    return catalogResolver;
  }
Example #4
0
  /** The main entry point */
  public static void main(String[] args) throws FileNotFoundException, IOException {

    String xmlfile = null;
    int debug = 0;
    int maxErrs = 10;
    boolean nsAware = true;
    boolean validating = true;
    boolean showWarnings = (debug > 2);
    boolean showErrors = true;
    Vector catalogFiles = new Vector();

    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-c")) {
        ++i;
        catalogFiles.add(args[i]);
        continue;
      }

      if (args[i].equals("-w")) {
        validating = false;
        continue;
      }

      if (args[i].equals("-v")) {
        validating = true;
        continue;
      }

      if (args[i].equals("-n")) {
        nsAware = false;
        continue;
      }

      if (args[i].equals("-N")) {
        nsAware = true;
        continue;
      }

      if (args[i].equals("-d")) {
        ++i;
        String debugstr = args[i];
        try {
          debug = Integer.parseInt(debugstr);
          if (debug >= 0) {
            Debug.setDebug(debug);
            showWarnings = (debug > 2);
          }
        } catch (Exception e) {
          // nop
        }
        continue;
      }

      if (args[i].equals("-E")) {
        ++i;
        String errstr = args[i];
        try {
          int errs = Integer.parseInt(errstr);
          if (errs >= 0) {
            maxErrs = errs;
          }
        } catch (Exception e) {
          // nop
        }
        continue;
      }

      xmlfile = args[i];
    }

    if (xmlfile == null) {
      System.out.println("Usage: org.apache.xml.resolver.apps.xread [opts] xmlfile");
      System.exit(1);
    }

    ResolvingXMLReader reader = new ResolvingXMLReader();

    try {
      reader.setFeature("http://xml.org/sax/features/namespaces", nsAware);
      reader.setFeature("http://xml.org/sax/features/validation", validating);
    } catch (SAXException e) {
      // nop;
    }

    Catalog catalog = reader.getCatalog();

    for (int count = 0; count < catalogFiles.size(); count++) {
      String file = (String) catalogFiles.elementAt(count);
      catalog.parseCatalog(file);
    }

    XParseError xpe = new XParseError(showErrors, showWarnings);
    xpe.setMaxMessages(maxErrs);
    reader.setErrorHandler(xpe);

    String parseType = validating ? "validating" : "well-formed";
    String nsType = nsAware ? "namespace-aware" : "namespace-ignorant";
    if (maxErrs > 0) {
      System.out.println("Attempting " + parseType + ", " + nsType + " parse");
    }

    Date startTime = new Date();

    try {
      reader.parse(xmlfile);
    } catch (SAXException sx) {
      System.out.println("SAX Exception: " + sx);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Date endTime = new Date();

    long millisec = endTime.getTime() - startTime.getTime();
    long secs = 0;
    long mins = 0;
    long hours = 0;

    if (millisec > 1000) {
      secs = millisec / 1000;
      millisec = millisec % 1000;
    }

    if (secs > 60) {
      mins = secs / 60;
      secs = secs % 60;
    }

    if (mins > 60) {
      hours = mins / 60;
      mins = mins % 60;
    }

    if (maxErrs > 0) {
      System.out.print("Parse ");
      if (xpe.getFatalCount() > 0) {
        System.out.print("failed ");
      } else {
        System.out.print("succeeded ");
        System.out.print("(");
        if (hours > 0) {
          System.out.print(hours + ":");
        }
        if (hours > 0 || mins > 0) {
          System.out.print(mins + ":");
        }
        System.out.print(secs + "." + millisec);
        System.out.print(") ");
      }
      System.out.print("with ");

      int errCount = xpe.getErrorCount();
      int warnCount = xpe.getWarningCount();

      if (errCount > 0) {
        System.out.print(errCount + " error");
        System.out.print(errCount > 1 ? "s" : "");
        System.out.print(" and ");
      } else {
        System.out.print("no errors and ");
      }

      if (warnCount > 0) {
        System.out.print(warnCount + " warning");
        System.out.print(warnCount > 1 ? "s" : "");
        System.out.print(".");
      } else {
        System.out.print("no warnings.");
      }

      System.out.println("");
    }

    if (xpe.getErrorCount() > 0) {
      System.exit(1);
    }
  }
  /**
   * Read a catalog from an input stream.
   *
   * <p>This class reads a catalog from an input stream:
   *
   * <ul>
   *   <li>Based on the QName of the root element, it determines which parser to instantiate for
   *       this catalog.
   *   <li>It constructs a DOM Document from the catalog and
   *   <li>For each child of the root node, it calls the parser's parseCatalogEntry method. This
   *       method is expected to make appropriate calls back into the catalog to add entries for the
   *       entries in the catalog. It is free to do this in whatever manner is appropriate (perhaps
   *       using just the node passed in, perhaps wandering arbitrarily throughout the tree).
   * </ul>
   *
   * @param catalog The catalog for which this reader is called.
   * @param is The input stream that is to be read.
   * @throws IOException if the URL cannot be read.
   * @throws UnknownCatalogFormatException if the catalog format is not recognized.
   * @throws UnparseableCatalogException if the catalog cannot be parsed. (For example, if it is
   *     supposed to be XML and isn't well-formed or if the parser class cannot be instantiated.)
   */
  public void readCatalog(Catalog catalog, InputStream is) throws IOException, CatalogException {

    DocumentBuilderFactory factory = null;
    DocumentBuilder builder = null;

    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    try {
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    Document doc = null;

    try {
      doc = builder.parse(is);
    } catch (SAXException se) {
      throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
    }

    Element root = doc.getDocumentElement();

    String namespaceURI = Namespaces.getNamespaceURI(root);
    String localName = Namespaces.getLocalName(root);

    String domParserClass = getCatalogParser(namespaceURI, localName);

    if (domParserClass == null) {
      if (namespaceURI == null) {
        catalog.getCatalogManager().debug.message(1, "No Catalog parser for " + localName);
      } else {
        catalog
            .getCatalogManager()
            .debug
            .message(1, "No Catalog parser for " + "{" + namespaceURI + "}" + localName);
      }
      return;
    }

    DOMCatalogParser domParser = null;

    try {
      domParser = (DOMCatalogParser) Class.forName(domParserClass).newInstance();
    } catch (ClassNotFoundException cnfe) {
      catalog
          .getCatalogManager()
          .debug
          .message(1, "Cannot load XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (InstantiationException ie) {
      catalog
          .getCatalogManager()
          .debug
          .message(1, "Cannot instantiate XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (IllegalAccessException iae) {
      catalog
          .getCatalogManager()
          .debug
          .message(1, "Cannot access XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (ClassCastException cce) {
      catalog
          .getCatalogManager()
          .debug
          .message(1, "Cannot cast XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    Node node = root.getFirstChild();
    while (node != null) {
      domParser.parseCatalogEntry(catalog, node);
      node = node.getNextSibling();
    }
  }