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

📄 configurationcomponent.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.
*/

/*
 * ConfigurationComponent.java - 18/01/2006
 */
package issrg.editor2.configurations;

import issrg.editor2.WindowUtilities;
import issrg.editor2.PERMISXMLEditorInstantiable;
import issrg.utils.xml.PolicyValidator;
import issrg.utils.xml.ValidationException;
import issrg.utils.xml.XMLEditor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.MissingResourceException;
import java.util.TreeSet;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.apache.xerces.dom.DOMImplementationImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;

/**
 * This class acts similarly to the PERMISPolicyValidator Class and implements 
 * the Policy Validator Interface.
 * <p> 
 * This class will be the policy validator for the Options Dialog.
 * 
 *
 * @see LDAPConfiguration
 * @see EnvParametersConfiguration
 * @see ArgParametersConfiguration
 * @see OptionsDialog
 * @see PERMISPolicyValidator
 * 
 * @author Christian Azzopardi
 */
public class ConfigurationComponent extends XMLEditor implements PolicyValidator
{
    /**
     * The document that will have a valid Dialog Specific XML.
     */
    public Document document;
    
    /**
     * The contents of the TAPFiles
     */
    public PERMISXMLEditorInstantiable TAPFiles = new PERMISXMLEditorInstantiable();
    public PERMISXMLEditorInstantiable WSDDFiles = new PERMISXMLEditorInstantiable();

    /**
     * 
     */
    InputStream configFileDOM;
    
    /**
     * File name of the configuration XML file.
     */
    public String filename;
    
    /**
     * Instance of the ldapConfig NodeItemList & panel. 
     */
    public LDAPConfiguration ldapConfig;
    
    /**
     * Instance of the ldapConfig NodeItemList & panel. 
     */
    public EnvParametersConfiguration envParams;
    
    /**
     * Instance of the Role Types setup panel.
     */
    public RoleTypeParametersConfiguration roleTypeParams;  
    
    /**
     * Instance of the Application Preferences Panel.
     */
    public ApplicationPreferencesPanel appPreferences;       
    
    /**
     * Instance of the TAP Configurations Panel.
     */
    public TAPFileConfiguration tapFileConfig;     
    
    /**
     * Instance of the WSDL Configurations Panel.
     */
    public WSDLFileConfiguration wsdlFileConfig;     
    
    /** 
     * Creates a new instance of ConfigurationComponent. Sets itself as the 
     * policy Validator, and adds the <code>LDAPConfiguration</code> to 
     * this components JPanel. 
     * <p>
     * The constructor then calls a method load() to open a the XML file
     * that stores the OptionsDialog XML.
     */
    public ConfigurationComponent() 
    {
        WindowUtilities.setNativeLookAndFeel();
        policyValidator = this;
        ldapConfig = new LDAPConfiguration(this);
        envParams = new EnvParametersConfiguration(this);
        roleTypeParams = new RoleTypeParametersConfiguration(this);
        appPreferences = new ApplicationPreferencesPanel(this);
        tapFileConfig = new TAPFileConfiguration(this);
        wsdlFileConfig = new WSDLFileConfiguration(this);
        
        addXMLChangeListener(ldapConfig);
        addXMLChangeListener(envParams);
        addXMLChangeListener(roleTypeParams);
        addXMLChangeListener(appPreferences);
        addXMLChangeListener(tapFileConfig);
        addXMLChangeListener(wsdlFileConfig);
        
        load();
    }
    
    /**
     * Tries to Load a file called 'pe.cfg' that contains the XML with the LDAP
     * connections, and later on other XML tags.
     * <p>
     * This method first tries to open the 'pe.cfg' file in the home folder. 
     * If this file does not exist in the home folder, it will obtain a default
     * 'pe.cfg' file stored in the programs Resources.
     * <p>
     * Once this file is loaded, it will set its contents in creating the
     * Document to use.
     */
    public void load()
    {
        File configFile = new File("pe.cfg");
        
        if (!configFile.exists())
        {
            try
            {
                configFileDOM = ConfigurationComponent.class.getClassLoader().getResourceAsStream("issrg/editor2/pe.cfg");
                setFileName("pe.cfg");
            }
            catch(MissingResourceException mre)
            {
                return;
            } 
            //return ??
        }
        else
        {
            try
            {
                configFileDOM = new FileInputStream(configFile); //Name of file to load
                setFileName("pe.cfg");
            }
            catch(FileNotFoundException fnfe)
            {
                return;
            }
        }

        createDOM(configFileDOM); 
        //validates the document if configFileDOM is not null
        //if configFileDOM is null it will go to the getValidDocument() Method.
    }
    
    /**
     * Sets the file Name
     *
     * @param fname   The file Name in String Format
     */
    public void setFileName(String fname)
    {
        filename = fname;
    }
    
    /**
     * Gets the stored file name.
     *
     * @return  a string with the File Name.
     */
    public String getFileName()
    {
        return filename;
    }
    
    /**
     * Sets the Document with the one the class will be using.
     *
     * @param doc   the Document to use.
     */ 
    public void setDocument(Document doc)
    {
        this.document = doc;
    }   
    
    /**
     * Method that is used to return a good Valid Configuration XML Document.
     * If there is no current document set, the method creates a Document 
     * itself.
     * <p>
     * After a document is obtained it will add the required tags and attributes, 
     * to make it valid. 
     *
     * @return   A valid Document that is usable and conformable to the XML 
     *           tags we would like to expect for this configuration file.
     */
    public Document getValidDocument()
    {
        Element rootElement = this.document.getDocumentElement();
        Node rootNode = (Node)rootElement;
        NodeList nlist = rootNode.getChildNodes();
        
        if(this.document == null || !rootElement.getTagName().equals("PolicyEditorConfiguration") || nlist.getLength() != 1 || !nlist.item(0).equals("LDAPConfiguration"))
        {
            //Create a new DOM with root and Valid First Child LDAPConfiguration
            DOMImplementation domImpl = new DOMImplementationImpl();
            DocumentType docType = domImpl.createDocumentType("DTD", null, null);
            this.document = domImpl.createDocument(null, "PolicyEditorConfiguration", docType);   
            Element childElement = this.document.createElement("LDAPConfiguration");
            this.document.getDocumentElement().appendChild(childElement); 
            //------------------------------------------------------------------
        }        
        
        //List of Valid Attributes
        String validAttributes[] = { "Name", "Host", "Version", "Port", "BaseDN", "Login", "Password" };
        TreeSet set = new TreeSet(Arrays.asList(validAttributes));
        //nodelist is assigned the children of the roots first Valid Child
        NodeList nodelist = nlist.item(0).getChildNodes();
        for (int i = 0; i < nodelist.getLength(); i++) 
        {
            //if item is not equal to LDAPDirectory
            if (!nodelist.item(i).getNodeName().equals("LDAPDirectory"))
            {
                //remove it 
                try 
                {
                    nlist.item(0).removeChild(nodelist.item(i));
                }
                catch(DOMException DOMe)
                {
                }
            }
            else //else if it is, Check if it has other child nodes and remove ones not equal to BinaryAttribute
            {
                //nl assigned to the Children Nodes of LDAPDirectory
                NodeList nl = nodelist.item(i).getChildNodes();
                
                //for each of the LDAPDirectory Childs...
                for (int j = 0; j < nl.getLength(); j++)
                {
                    //Check that the children of LDAPDirectory are equal to BinaryAttribute
                    if (!nl.item(j).equals("BinaryAttribute"))
                    {
                        try
                        {
                            nodelist.item(i).removeChild(nl.item(j));
                        }
                        catch(DOMException DOMe)
                        {
                        }
                        //continue;
                    }
                    
                    if (nl.item(j).hasChildNodes())
                    {
                    }
                }
            }
            
            //for all attributes
            for (int j = 0; j < nlist.item(i).getAttributes().getLength(); j++)
            {
                //if attribute not in set,
                if (!set.contains(nlist.item(i).getAttributes().item(j)))
                {
                    //remove attribute
                    nlist.item(i).getAttributes().removeNamedItem(nlist.item(i).getAttributes().item(j).toString());
                }
                
            }
        }
        
        return this.document;
    }
 
    /**
     * Method that validates the current Document. Will validate the document 
     * with the specified 'peconfiguration.dtd'. This is done by parsing the 
     * document.
     *
     * @throws a ValidationException if an error occurs.
     */
    public void validateDocument() throws ValidationException
    {   
        if(this.document == null)
        {
            throw new ValidationException(); 
        }
        
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(false);
        
        try
        {
            XMLReader parser = factory.newSAXParser().getXMLReader();
            InputSource is = new InputSource(ConfigurationComponent.class.getClassLoader().getResourceAsStream("issrg/editor2/pe.cfg"));
            parser.parse(is);
        }
        catch(SAXParseException saxpe)
        {
            throw new ValidationException(saxpe.getMessage());
        }
        catch(SAXException saxe)
        {
            throw new ValidationException(saxe.getMessage());
        }
        catch(ParserConfigurationException pce)
        {
            throw new ValidationException(pce.getMessage());
        }
        catch(IOException ioe)
        {
            throw new ValidationException(ioe.getMessage());
        }
    }
}

⌨️ 快捷键说明

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