xsltprocessorapplet.java

来自「JAVA 所有包」· Java 代码 · 共 778 行 · 第 1/2 页

JAVA
778
字号
   * @param s String to escape   *   * The escaped string.   */  public String escapeString(String s)  {    StringBuffer sb = new StringBuffer();    int length = s.length();    for (int i = 0; i < length; i++)    {      char ch = s.charAt(i);      if ('<' == ch)      {        sb.append("&lt;");      }      else if ('>' == ch)      {        sb.append("&gt;");      }      else if ('&' == ch)      {        sb.append("&amp;");      }      else if (0xd800 <= ch && ch < 0xdc00)      {        // UTF-16 surrogate        int next;        if (i + 1 >= length)        {          throw new RuntimeException(            XSLMessages.createMessage(              XSLTErrorResources.ER_INVALID_UTF16_SURROGATE,              new Object[]{ Integer.toHexString(ch) }));  //"Invalid UTF-16 surrogate detected: "          //+Integer.toHexString(ch)+ " ?");        }        else        {          next = s.charAt(++i);          if (!(0xdc00 <= next && next < 0xe000))            throw new RuntimeException(              XSLMessages.createMessage(                XSLTErrorResources.ER_INVALID_UTF16_SURROGATE,                new Object[]{                  Integer.toHexString(ch) + " "                  + Integer.toHexString(next) }));  //"Invalid UTF-16 surrogate detected: "          //+Integer.toHexString(ch)+" "+Integer.toHexString(next));          next = ((ch - 0xd800) << 10) + next - 0xdc00 + 0x00010000;        }        sb.append("&#x");        sb.append(Integer.toHexString(next));        sb.append(";");      }      else      {        sb.append(ch);      }    }    return sb.toString();  }  /**   * Assuming the stylesheet URL and the input XML URL have been set,   * perform the transformation and return the result as a String.   *   * @return A string that contains the contents pointed to by the URL.   *   */  public String getHtmlText()  {    m_trustedAgent.m_getData = true;    m_callThread = Thread.currentThread();    try    {      synchronized (m_callThread)      {        m_callThread.wait();      }    }    catch (InterruptedException ie)    {      System.out.println(ie.getMessage());    }    return m_htmlText;  }  /**   * Get an XML document (or stylesheet)   *   * @param treeURL valid URL string for the document.   *   * @return document   *   * @throws IOException   */  public String getTreeAsText(String treeURL) throws IOException  {    m_treeURL = treeURL;    m_trustedAgent.m_getData = true;    m_trustedAgent.m_getSource = true;    m_callThread = Thread.currentThread();    try    {      synchronized (m_callThread)      {        m_callThread.wait();      }    }    catch (InterruptedException ie)    {      System.out.println(ie.getMessage());    }    return m_sourceText;  }    /**   * Use a Transformer to copy the source document   * to a StreamResult.   *    * @return the document as a string   */  private String getSource() throws TransformerException  {    StringWriter osw = new StringWriter();    PrintWriter pw = new PrintWriter(osw, false);    String text = "";    try    {      URL docURL = new URL(m_documentBase, m_treeURL);      synchronized (m_tfactory)      {        Transformer transformer = m_tfactory.newTransformer();        StreamSource source = new StreamSource(docURL.toString());            StreamResult result = new StreamResult(pw);        transformer.transform(source, result);        text = osw.toString();      }    }    catch (MalformedURLException e)    {      e.printStackTrace();      throw new RuntimeException(e.getMessage());    }          catch (Exception any_error)    {      any_error.printStackTrace();    }    return text;  }  /**   * Get the XML source Tree as a text string suitable   * for display in a browser.  Note that this is for display of the   * XML itself, not for rendering of HTML by the browser.   *   * @return XML source document as a string.   * @throws Exception thrown if tree can not be converted.   */  public String getSourceTreeAsText() throws Exception  {    return getTreeAsText(m_documentURL);  }  /**   * Get the XSL style Tree as a text string suitable   * for display in a browser.  Note that this is for display of the   * XML itself, not for rendering of HTML by the browser.   *   * @return The XSL stylesheet as a string.   * @throws Exception thrown if tree can not be converted.   */  public String getStyleTreeAsText() throws Exception  {    return getTreeAsText(m_styleURL);  }  /**   * Get the HTML result Tree as a text string suitable   * for display in a browser.  Note that this is for display of the   * XML itself, not for rendering of HTML by the browser.   *   * @return Transformation result as unmarked text.   * @throws Exception thrown if tree can not be converted.   */  public String getResultTreeAsText() throws Exception  {    return escapeString(getHtmlText());  }  /**   * Process a document and a stylesheet and return   * the transformation result.  If one of these is null, the   * existing value (of a previous transformation) is not affected.   *   * @param doc URL string to XML document   * @param style URL string to XSL stylesheet   *   * @return HTML transformation result   */  public String transformToHtml(String doc, String style)  {    if (null != doc)    {      m_documentURL = doc;    }    if (null != style)    {      m_styleURL = style;    }    return getHtmlText();  }  /**   * Process a document and a stylesheet and return   * the transformation result. Use the xsl:stylesheet PI to find the   * document, if one exists.   *   * @param doc  URL string to XML document containing an xsl:stylesheet PI.   *   * @return HTML transformation result   */  public String transformToHtml(String doc)  {    if (null != doc)    {      m_documentURL = doc;    }    m_styleURL = null;    return getHtmlText();  }  /**   * Process the transformation.   *   * @return The transformation result as a string.   *   * @throws TransformerException   */  private String processTransformation() throws TransformerException  {    String htmlData = null;    this.showStatus("Waiting for Transformer and Parser to finish loading and JITing...");        synchronized (m_tfactory)    {     URL documentURL = null;      URL styleURL = null;      StringWriter osw = new StringWriter();      PrintWriter pw = new PrintWriter(osw, false);      StreamResult result = new StreamResult(pw);          this.showStatus("Begin Transformation...");      try      {        documentURL = new URL(m_codeBase, m_documentURL);        StreamSource xmlSource = new StreamSource(documentURL.toString());        styleURL = new URL(m_codeBase, m_styleURL);        StreamSource xslSource = new StreamSource(styleURL.toString());        Transformer transformer = m_tfactory.newTransformer(xslSource);                Enumeration m_keys = m_parameters.keys();        while (m_keys.hasMoreElements()){          Object key = m_keys.nextElement();          Object expression = m_parameters.get(key);          transformer.setParameter((String) key, expression);        }        transformer.transform(xmlSource, result);      }      catch (TransformerConfigurationException tfe)      {        tfe.printStackTrace();        throw new RuntimeException(tfe.getMessage());      }      catch (MalformedURLException e)      {        e.printStackTrace();        throw new RuntimeException(e.getMessage());      }	        this.showStatus("Transformation Done!");      htmlData = osw.toString();    }    return htmlData;  }  /**   * This class maintains a worker thread that that is   * trusted and can do things like access data.  You need   * this because the thread that is called by the browser   * is not trusted and can't access data from the URLs.   */  class TrustedAgent implements Runnable  {    /**      * Specifies whether the worker thread should perform a transformation.     */    public boolean m_getData = false;    /**      * Specifies whether the worker thread should get an XML document or XSL stylesheet.     */    public boolean m_getSource = false;    /**     * The real work is done from here.     *     */    public void run()    {      while (true)      {        m_trustedWorker.yield();        if (m_getData)  // Perform a transformation or get a document.        {          try          {            m_getData = false;            m_htmlText = null;            m_sourceText = null;            if (m_getSource)  // Get a document.            {              m_getSource = false;              m_sourceText = getSource();            }            else              // Perform a transformation.              m_htmlText = processTransformation();          }          catch (Exception e)          {            e.printStackTrace();          }          finally          {            synchronized (m_callThread)            {              m_callThread.notify();            }          }        }        else        {          try          {            m_trustedWorker.sleep(50);          }          catch (InterruptedException ie)          {            ie.printStackTrace();          }        }      }    }  }    // For compatiblity with old serialized objects  // We will change non-serialized fields and change methods  // and not have this break us.  private static final long serialVersionUID=4618876841979251422L;    // For compatibility when de-serializing old objects  private void readObject(java.io.ObjectInputStream inStream) throws IOException, ClassNotFoundException   {      inStream.defaultReadObject();            // Needed assignment of non-serialized fields            // A TransformerFactory is not guaranteed to be serializable,       // so we create one here      m_tfactory = TransformerFactory.newInstance();  }      }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?