⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 readablexml.java

📁 一个完整的XACML工程,学习XACML技术的好例子!
💻 JAVA
字号:
/*
* Copyright (c) 2006, University of Kent
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this 
* list of conditions and the following disclaimer.
* 
* Redistributions in binary form must reproduce the above copyright notice, 
* this list of conditions and the following disclaimer in the documentation 
* and/or other materials provided with the distribution. 
*
* 1. Neither the name of the University of Kent nor the names of its 
* contributors may be used to endorse or promote products derived from this 
* software without specific prior written permission. 
*
* 2. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS  
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. 
*
* 3. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
* POSSIBILITY OF SUCH DAMAGE.
*
* 4. YOU AGREE THAT THE EXCLUSIONS IN PARAGRAPHS 2 AND 3 ABOVE ARE REASONABLE
* IN THE CIRCUMSTANCES.  IN PARTICULAR, YOU ACKNOWLEDGE (1) THAT THIS
* SOFTWARE HAS BEEN MADE AVAILABLE TO YOU FREE OF CHARGE, (2) THAT THIS
* SOFTWARE IS NOT "PRODUCT" QUALITY, BUT HAS BEEN PRODUCED BY A RESEARCH
* GROUP WHO DESIRE TO MAKE THIS SOFTWARE FREELY AVAILABLE TO PEOPLE WHO WISH
* TO USE IT, AND (3) THAT BECAUSE THIS SOFTWARE IS NOT OF "PRODUCT" QUALITY
* IT IS INEVITABLE THAT THERE WILL BE BUGS AND ERRORS, AND POSSIBLY MORE
* SERIOUS FAULTS, IN THIS SOFTWARE.
*
* 5. This license is governed, except to the extent that local laws
* necessarily apply, by the laws of England and Wales.
*/

/**
 * ReadableXML.java - 12/11/05
 */
package issrg.utils.xml;

import issrg.editor2.LinkFollower;
import issrg.editor2.ReadablePERMISXML;
import org.w3c.dom.*;
import java.awt.BorderLayout;
import javax.swing.*;
import java.io.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import org.apache.xml.serialize.HTMLSerializer;
import org.apache.xml.serialize.OutputFormat;

/**
 * This abstract class defines the component that will contain an XML
 * Transformation with an XSL file. It is implemented as an abstract file
 * so as not to limit its functionality just to one XSL transformation.
 * <p>
 * The component presents the transformation, on a JEditorPane situated on the
 * extended JPanel. The transformation would result in an HTML document, that
 * could be easily displayed by these components.
 * <p>
 * This component is made to be a registered XMLChangeListener, so as to update
 * itself in real time on any modifications that have occurred to the section
 * of XML that it is representing.
 *
 * @author   Christian Azzopardi
 */
public abstract class ReadableXML extends JPanel implements XMLChangeListener {
    /**
     * The component that can render html. Therefore will be the output of
     * this component.
     */
    public JEditorPane that;
    
    /**
     * The Name of the node that will be transformed in the transformation.
     * If the string is empty then the whole document will be transformed.
     */
    String nodeName;
    
    /**
     * The reference to the XML Editor.
     */
    XMLEditor xmlED;
    
    /**
     * A TransformerFactory instance is used to create the Transformer object.
     */
    TransformerFactory tFactory;
    
    /**
     * The Stream of the Transformation style that is to be used.
     */
    StreamSource stylesource;
    
    /**
     * The Transformer Instance.
     */
    Transformer transformer;
    
    private boolean empty;
    
    public JScrollPane scrollPane;
    
    public String mimeType;
    
    /**
     * Creates a new instance of ReadableXML and initialises the JPanel super
     * class. The JEditor Instance is placed on the JPanel, and the transformation
     * is output as 'text/html'
     * <p>
     * The nodename can be specified depending on the style sheets, recognised
     * Node Names. If the nodename is passed as an empty string, the
     * transformation will occur to the whole XML Document. Otherwise if a
     * particular node is passed, the style transformation will only happen
     * to that particular node.
     * <p>
     * This is useful as it can transform the sub-policy that is being modified
     * at the moment, and can be displayed to the user so he would be informed
     * of his modifications to the XML policy.
     *
     * @param xmlED    the XML Editor Reference
     * @param nodeName the name of the XML Node to convert to readable policy
     */
    public ReadableXML(XMLEditor xmlED, String nodeName, String mimeType)
    {
        super();
        
        this.setLayout(new BorderLayout());
        that = new JEditorPane();
        scrollPane = new JScrollPane(that);
        this.add(scrollPane, BorderLayout.CENTER);
        this.mimeType = mimeType;
        that.setContentType(mimeType);  
        that.setEditable(false);
        //that.addHyperlinkListener(new LinkFollower(that));
        
        if (nodeName != null && nodeName.equals("")) nodeName=null;
        this.nodeName = nodeName;
       
        try
        {
            tFactory = TransformerFactory.newInstance();
            stylesource = new StreamSource(ReadablePERMISXML.class.getClassLoader().getResourceAsStream(getStyle()));
            transformer = tFactory.newTransformer(stylesource);
        }
        catch (TransformerConfigurationException tce)
        { 
            // Use the contained exception, if any
            Throwable x = tce;
            if (tce.getException() != null)
            x = tce.getException();
            x.printStackTrace();
        }
        setXMLEditor(xmlED);
    }
    
    /**
     * An abstract method, that when overridden will return the path to the
     * style that the XML will be transformed with.
     *
     * @return the style transformation that the XML will be transformed with.
     */
    public abstract String getStyle();
    
    /**
     * Sets the XML Editor by removing the previously one that was set, and 
     * setting the one that was just passed. This method then requests that 
     * the transformed output is refreshed.
     *
     * @param xmlED
     */
    public void setXMLEditor(XMLEditor xmlED) 
    {
        if (this.xmlED!=null) this.xmlED.removeXMLChangeListener(this);
        if (xmlED!=null) xmlED.addXMLChangeListener(this);
        this.xmlED = xmlED;
        getXML();
    }
    
    public XMLEditor getXMLEditor()
    {
        return xmlED;
    }
    
    /**
     * When an XMLChangeEvent is received, instruction is given to refresh the
     * contents of this component.
     */
    public void XMLChanged(XMLChangeEvent ev) 
    {
        getXML();
    }
    
    /**
     * This method returns true if the result of the last transformation 
     * resulted in an empty XML.
     */
    public boolean isEmpty()
    {
      return empty;
    }    
    
    public void setEmpty(boolean em)
    {
      empty=em;
    }    
    

    /**
     * Method that actually loads the XML document to transform. 
     * <p>
     * It checks if the nodeName is empty. If it is, it will search for the root 
     * element of the XML document. If it is not the root element will be set to 
     * nodeName.
     * <p>
     * The Transformation takes place under the transformer that was declared 
     * in this class's Constructor. Position of Cursor is always set at the 
     * beggining of the transformed Document.
     * <p>
     * This method performs a transformation of the XML into a readable form.
     * It returns the result of isEmpty(), i.e.&nbsp;it returns true, if the
     * transformation resulted in an empty XML.
     *
     * @return  boolean specifying if XML is empty or not.
     */
    public boolean getXML()
    {
        setEmpty(true);

        if (xmlED==null || xmlED.DOM==null) return isEmpty(); // nothing to display yet - there is no DOM         
        DOMSource source;
        
        if (mimeType.intern().equals("text/html"))
        {
            try
            {
                Node root = xmlED.DOM;
                if (root != null){ // it's null, if NEW_XML is created, so there is no node that we are looking for, so item(0) returns null;
                  source = new DOMSource(root);

                  DOMResult result = new DOMResult();
                  transformer.transform(source, result); 

                  Document newDoc = (Document)result.getNode();

                  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                  OutputFormat of = new OutputFormat(newDoc);
                  HTMLSerializer xs = new HTMLSerializer(baos, of);

                  if (nodeName!=null){
                      NodeList nl=newDoc.getElementsByTagName("span");
                      for (int i = 0; i < nl.getLength(); i++ ) {
                          Element e=(Element)nl.item(i);
                          if (e.getAttribute("class")!=null && e.getAttribute("class").equals(nodeName)){
                              xs.serialize(e);
                              setEmpty(false);
                          }
                      }
                  }else{
                      xs.serialize(newDoc.getDocumentElement());
                      setEmpty(false);
                  }

                  String line;
                  line = new String(baos.toByteArray());              

                  that.setText(line);
                  that.setCaretPosition(0);
                }            
            }
            catch (TransformerException te)
            {
               // Use the contained exception, if any
               Throwable x = te;
               if (te.getException() != null)
               x = te.getException();
               x.printStackTrace();
            }
            catch(IOException ioe)
            {
                // this shouldn't happen
            }
        }
        else if (mimeType.intern().equals("text/plain"))
        {
            String xmlToPrint = this.xmlED.GenerateXML();
            that.setText(xmlToPrint);
            that.setCaretPosition(0);          
        }
        this.repaint();
        this.revalidate();
        return isEmpty();
    }       
}

⌨️ 快捷键说明

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