/**
   * Used internally when a document can't be loaded--returns XHTML as an XMLResource indicating
   * that fact.
   *
   * @param uri The URI which could not be loaded.
   * @return An XMLResource containing XML which about the failure.
   */
  private HTMLResource getNotFoundDocument(final String uri) {
    HTMLResource xr;

    // URI may contain & symbols which can "break" the XHTML we're creating
    final String cleanUri = GeneralUtil.escapeHTML(uri);
    final String notFound =
        "<html><h1>Document not found</h1><p>Could not access URI <pre>"
            + cleanUri
            + "</pre></p></html>";

    xr = HTMLResource.load(new StringReader(notFound));
    return xr;
  }
  /** {@inheritDoc} */
  public HTMLResource getXMLResource(String uri) {
    uri = resolveURI(uri);
    if (uri != null && uri.startsWith("file:")) {
      File file = null;
      try {
        final StringBuffer sbURI = GeneralUtil.htmlEscapeSpace(uri);

        LOGGER.info("Encoded URI: " + sbURI);
        file = new File(new URI(sbURI.toString()));
      } catch (final URISyntaxException e) {
        LOGGER.error("Invalid file URI " + uri, e);
        return getNotFoundDocument(uri);
      }
      if (file.isDirectory()) {
        final String dirlist = DirectoryLister.list(file);
        return HTMLResource.load(new StringReader(dirlist));
      }
    }
    HTMLResource xr = null;
    URLConnection uc = null;
    InputStream inputStream = null;
    try {
      final StreamResource strm = new StreamResource(uri);
      strm.connect();
      uc = strm.getUrlConnection();
      final String contentType = uc.getContentType();

      LOGGER.info("Content-Type = " + contentType);

      if (uc instanceof HttpURLConnection) {
        LOGGER.info("Response Code = " + ((HttpURLConnection) uc).getResponseCode());
        LOGGER.info("Response Message = " + ((HttpURLConnection) uc).getResponseMessage());
      }

      // Maybe should popup a choice when content/unknown!
      if (contentType == null
          || contentType.equals("text/plain")
          || contentType.equals("content/unknown")) {
        inputStream = strm.bufferedStream();
        xr = HTMLResource.load(inputStream, uri);
      } else if (contentType.startsWith("image")) {
        final String doc = "<img src='" + uri + "'/>";
        xr = HTMLResource.load(doc);
      } else {
        inputStream = strm.bufferedStream();
        xr = HTMLResource.load(inputStream, uri);
      }
    } catch (final MalformedURLException e) {
      LOGGER.error("bad URL given: " + uri, e);
    } catch (final IOException e) {
      LOGGER.error("IO problem for " + uri, e);
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (final IOException e) {
          // swallow
        }
      }
    }

    if (xr == null) {
      xr = getNotFoundDocument(uri);
    }
    return xr;
  }