commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ebo...@apache.org
Subject cvs commit: jakarta-commons/configuration/src/java/org/apache/commons/configuration XMLConfiguration.java
Date Thu, 23 Sep 2004 11:43:27 GMT
ebourg      2004/09/23 04:43:27

  Modified:    configuration/src/java/org/apache/commons/configuration
                        XMLConfiguration.java
  Log:
  Added a constructor using a URL
  Removed set/getFile()
  Code formating
  
  Revision  Changes    Path
  1.15      +192 -119  jakarta-commons/configuration/src/java/org/apache/commons/configuration/XMLConfiguration.java
  
  Index: XMLConfiguration.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/configuration/src/java/org/apache/commons/configuration/XMLConfiguration.java,v
  retrieving revision 1.14
  retrieving revision 1.15
  diff -u -r1.14 -r1.15
  --- XMLConfiguration.java	22 Sep 2004 17:17:30 -0000	1.14
  +++ XMLConfiguration.java	23 Sep 2004 11:43:27 -0000	1.15
  @@ -20,6 +20,7 @@
   import java.io.Reader;
   import java.io.StringWriter;
   import java.io.Writer;
  +import java.net.URL;
   import java.util.ArrayList;
   import java.util.Iterator;
   import java.util.List;
  @@ -65,7 +66,7 @@
    * @version $Revision$, $Date$
    */
   public class XMLConfiguration extends AbstractFileConfiguration
  -{    
  +{
       // For conformance with xpath
       private static final String ATTRIBUTE_START = "[@";
   
  @@ -88,15 +89,18 @@
       private boolean autoSave = false;
   
       /**
  -     * Empty construtor. You must provide a file/fileName to save the
  -     * configuration.
  +     * Creates an empty XML configuration.
        */
  -    public XMLConfiguration() {
  +    public XMLConfiguration()
  +    {
           // build an empty document.
           DocumentBuilder builder = null;
  -        try {
  +        try
  +        {
               builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  -        } catch (ParserConfigurationException e) {
  +        }
  +        catch (ParserConfigurationException e)
  +        {
               throw new ConfigurationRuntimeException(e.getMessage(), e);
           }
   
  @@ -105,33 +109,46 @@
       }
   
       /**
  -     * Attempts to load the XML file as a resource from the classpath. The XML
  -     * file must be located somewhere in the classpath.
  +     * Creates and loads the XML configuration from the specified resource.
  +     *
  +     * @param resource The name of the resource to load.
        *
  -     * @param resource
  -     *            Name of the resource
  -     * @throws ConfigurationException
  -     *             If error reading data source.
  +     * @throws ConfigurationException Error while loading the XML file
        */
  -    public XMLConfiguration(String resource) throws ConfigurationException {
  +    public XMLConfiguration(String resource) throws ConfigurationException
  +    {
           this.fileName = resource;
           url = ConfigurationUtils.locate(resource);
           load();
       }
   
       /**
  -     * Attempts to load the XML file.
  +     * Creates and loads the XML configuration from the specified file.
        *
  -     * @param file
  -     *            File object representing the XML file.
  -     * @throws ConfigurationException
  -     *             If error reading data source.
  +     * @param file The XML file to load.
  +     * @throws ConfigurationException Error while loading the XML file
        */
  -    public XMLConfiguration(File file) throws ConfigurationException {
  +    public XMLConfiguration(File file) throws ConfigurationException
  +    {
           setFile(file);
           load();
       }
   
  +    /**
  +     * Creates and loads the XML configuration from the specified URL.
  +     *
  +     * @param url The location of the XML file to load.
  +     * @throws ConfigurationException Error while loading the XML file
  +     */
  +    public XMLConfiguration(URL url) throws ConfigurationException
  +    {
  +        setURL(url);
  +        load();
  +    }
  +
  +    /**
  +     * {@inheritDoc}
  +     */
       public void load(Reader in) throws ConfigurationException
       {
           try
  @@ -155,26 +172,32 @@
        *            the root element of the document.
        * @param hierarchy
        */
  -    private void initProperties(Element element, StringBuffer hierarchy) {
  +    private void initProperties(Element element, StringBuffer hierarchy)
  +    {
           StringBuffer buffer = new StringBuffer();
           NodeList list = element.getChildNodes();
  -        for (int i = 0; i < list.getLength(); i++) {
  +        for (int i = 0; i < list.getLength(); i++)
  +        {
               Node node = list.item(i);
  -            if (node instanceof Element) {
  +            if (node instanceof Element)
  +            {
                   Element child = (Element) node;
   
                   StringBuffer subhierarchy = new StringBuffer(hierarchy.toString());
                   subhierarchy.append(child.getTagName());
                   processAttributes(subhierarchy.toString(), child);
                   initProperties(child, subhierarchy.append(NODE_DELIMITER));
  -            } else if (node instanceof CDATASection || node instanceof Text) {
  +            }
  +            else if (node instanceof CDATASection || node instanceof Text)
  +            {
                   CharacterData data = (CharacterData) node;
                   buffer.append(data.getData());
               }
           }
   
           String text = buffer.toString().trim();
  -        if (text.length() > 0 && hierarchy.length() > 0) {
  +        if (text.length() > 0 && hierarchy.length() > 0)
  +        {
               super.addProperty(hierarchy.substring(0, hierarchy.length() - 1), text);
           }
       }
  @@ -188,10 +211,12 @@
        * @param element
        *            the actual XML element
        */
  -    private void processAttributes(String hierarchy, Element element) {
  +    private void processAttributes(String hierarchy, Element element)
  +    {
           // Add attributes as x.y{ATTRIBUTE_START}att{ATTRIBUTE_END}
           NamedNodeMap attributes = element.getAttributes();
  -        for (int i = 0; i < attributes.getLength(); ++i) {
  +        for (int i = 0; i < attributes.getLength(); ++i)
  +        {
               Attr attr = (Attr) attributes.item(i);
               String attrName = hierarchy + ATTRIBUTE_START + attr.getName() + ATTRIBUTE_END;
               super.addProperty(attrName, attr.getValue());
  @@ -205,13 +230,15 @@
        * @param name
        * @param value
        */
  -    public void addProperty(String name, Object value) {
  +    public void addProperty(String name, Object value)
  +    {
           super.addProperty(name, value);
           addXmlProperty(name, value);
           possiblySave();
       }
   
  -    public Object getXmlProperty(String name) {
  +    public Object getXmlProperty(String name)
  +    {
           // parse the key
           String[] nodes = parseElementNames(name);
           String attName = parseAttributeName(name);
  @@ -220,35 +247,43 @@
           List children = findElementsForPropertyNodes(nodes);
   
           List properties = new ArrayList();
  -        if (attName == null) {
  +        if (attName == null)
  +        {
               // return text contents of elements
               Iterator cIter = children.iterator();
  -            while (cIter.hasNext()) {
  +            while (cIter.hasNext())
  +            {
                   Element child = (Element) cIter.next();
                   // add non-empty strings
                   String text = getChildText(child);
  -                if (StringUtils.isNotEmpty(text)) {
  +                if (StringUtils.isNotEmpty(text))
  +                {
                       properties.add(text);
                   }
               }
  -        } else {
  +        }
  +        else
  +        {
               // return text contents of attributes
               Iterator cIter = children.iterator();
  -            while (cIter.hasNext()) {
  +            while (cIter.hasNext())
  +            {
                   Element child = (Element) cIter.next();
  -                if (child.hasAttribute(attName)) {
  +                if (child.hasAttribute(attName))
  +                {
                       properties.add(child.getAttribute(attName));
                   }
               }
           }
   
  -        switch (properties.size()) {
  -        case 0:
  -            return null;
  -        case 1:
  -            return properties.get(0);
  -        default:
  -            return properties;
  +        switch (properties.size())
  +        {
  +            case 0:
  +                return null;
  +            case 1:
  +                return properties.get(0);
  +            default:
  +                return properties;
           }
       }
   
  @@ -258,50 +293,62 @@
        * @param nodes
        * @return
        */
  -    private List findElementsForPropertyNodes(String[] nodes) {
  +    private List findElementsForPropertyNodes(String[] nodes)
  +    {
           List children = new ArrayList();
           List elements = new ArrayList();
   
           children.add(document.getDocumentElement());
  -        for (int i = 0; i < nodes.length; i++) {
  +        for (int i = 0; i < nodes.length; i++)
  +        {
               elements.clear();
               elements.addAll(children);
               children.clear();
   
               String eName = nodes[i];
               Iterator eIter = elements.iterator();
  -            while (eIter.hasNext()) {
  +            while (eIter.hasNext())
  +            {
                   Element element = (Element) eIter.next();
                   NodeList list = element.getChildNodes();
  -                for (int j = 0; j < list.getLength(); j++) {
  +                for (int j = 0; j < list.getLength(); j++)
  +                {
                       Node node = list.item(j);
  -                    if (node instanceof Element) {
  +                    if (node instanceof Element)
  +                    {
                           Element child = (Element) node;
  -                        if (eName.equals(child.getTagName())) {
  +                        if (eName.equals(child.getTagName()))
  +                        {
                               children.add(child);
                           }
                       }
                   }
               }
           }
  +
           return children;
       }
   
  -    private static String getChildText(Node node) {
  -
  +    private static String getChildText(Node node)
  +    {
           // is there anything to do?
  -        if (node == null) {
  +        if (node == null)
  +        {
               return null;
           }
   
           // concatenate children text
           StringBuffer str = new StringBuffer();
           Node child = node.getFirstChild();
  -        while (child != null) {
  +        while (child != null)
  +        {
               short type = child.getNodeType();
  -            if (type == Node.TEXT_NODE) {
  +            if (type == Node.TEXT_NODE)
  +            {
                   str.append(child.getNodeValue());
  -            } else if (type == Node.CDATA_SECTION_NODE) {
  +            }
  +            else if (type == Node.CDATA_SECTION_NODE)
  +            {
                   str.append(child.getNodeValue());
               }
               child = child.getNextSibling();
  @@ -319,7 +366,8 @@
        * @param name
        * @param value
        */
  -    public void setProperty(String name, Object value) {
  +    public void setProperty(String name, Object value)
  +    {
           super.setProperty(name, value);
           setXmlProperty(name, value);
           possiblySave();
  @@ -333,41 +381,51 @@
        * @param value
        *            The value to set.
        */
  -    private void setXmlProperty(String name, Object value) {
  +    private void setXmlProperty(String name, Object value)
  +    {
           // parse the key
           String[] nodes = parseElementNames(name);
           String attName = parseAttributeName(name);
   
           Element element = document.getDocumentElement();
  -        for (int i = 0; i < nodes.length; i++) {
  +        for (int i = 0; i < nodes.length; i++)
  +        {
               String eName = nodes[i];
               Element child = getChildElementWithName(eName, element);
               // If we don't find this part of the property in the XML hierarchy
               // we add it as a new node
  -            if (child == null) {
  +            if (child == null)
  +            {
                   child = document.createElement(eName);
                   element.appendChild(child);
               }
               element = child;
           }
   
  -        if (attName == null) {
  +        if (attName == null)
  +        {
               CharacterData data = document.createTextNode(String.valueOf(value));
               element.appendChild(data);
  -        } else {
  +        }
  +        else
  +        {
               element.setAttribute(attName, (String) value);
           }
       }
   
  -    private Element getChildElementWithName(String eName, Element element) {
  +    private Element getChildElementWithName(String eName, Element element)
  +    {
           Element child = null;
   
           NodeList list = element.getChildNodes();
  -        for (int j = 0; j < list.getLength(); j++) {
  +        for (int j = 0; j < list.getLength(); j++)
  +        {
               Node node = list.item(j);
  -            if (node instanceof Element) {
  +            if (node instanceof Element)
  +            {
                   child = (Element) node;
  -                if (eName.equals(child.getTagName())) {
  +                if (eName.equals(child.getTagName()))
  +                {
                       break;
                   }
                   child = null;
  @@ -384,7 +442,8 @@
        * @param value
        *            The value to set.
        */
  -    private void addXmlProperty(String name, Object value) {
  +    private void addXmlProperty(String name, Object value)
  +    {
           // parse the key
           String[] nodes = parseElementNames(name);
           String attName = parseAttributeName(name);
  @@ -392,7 +451,8 @@
           Element element = document.getDocumentElement();
           Element parent = element;
   
  -        for (int i = 0; i < nodes.length; i++) {
  +        for (int i = 0; i < nodes.length; i++)
  +        {
               if (element == null)
                   break;
               parent = element;
  @@ -404,10 +464,13 @@
   
           Element child = document.createElement(nodes[nodes.length - 1]);
           parent.appendChild(child);
  -        if (attName == null) {
  +        if (attName == null)
  +        {
               CharacterData data = document.createTextNode(String.valueOf(value));
               child.appendChild(data);
  -        } else {
  +        }
  +        else
  +        {
               child.setAttribute(attName, String.valueOf(value));
           }
       }
  @@ -419,13 +482,15 @@
        * @param name
        *            The name of the property to clear.
        */
  -    public void clearProperty(String name) {
  +    public void clearProperty(String name)
  +    {
           super.clearProperty(name);
           clearXmlProperty(name);
           possiblySave();
       }
   
  -    private void clearXmlProperty(String name) {
  +    private void clearXmlProperty(String name)
  +    {
           // parse the key
           String[] nodes = parseElementNames(name);
           String attName = parseAttributeName(name);
  @@ -433,43 +498,55 @@
           // get all the matching elements
           List children = findElementsForPropertyNodes(nodes);
   
  -        if (attName == null) {
  +        if (attName == null)
  +        {
               // remove children with no subelements
               Iterator cIter = children.iterator();
  -            while (cIter.hasNext()) {
  +            while (cIter.hasNext())
  +            {
                   Element child = (Element) cIter.next();
   
                   // determine if child has subelments
                   boolean hasSubelements = false;
                   Node subchild = child.getFirstChild();
  -                while (subchild != null) {
  -                    if (subchild.getNodeType() == Node.ELEMENT_NODE) {
  +                while (subchild != null)
  +                {
  +                    if (subchild.getNodeType() == Node.ELEMENT_NODE)
  +                    {
                           hasSubelements = true;
                           break;
                       }
                       subchild = subchild.getNextSibling();
                   }
   
  -                if (!hasSubelements) {
  +                if (!hasSubelements)
  +                {
                       // safe to remove
  -                    if (!child.hasAttributes()) {
  +                    if (!child.hasAttributes())
  +                    {
                           // remove entire node
                           Node parent = child.getParentNode();
                           parent.removeChild(child);
  -                    } else {
  +                    }
  +                    else
  +                    {
                           // only remove node contents
                           subchild = child.getLastChild();
  -                        while (subchild != null) {
  +                        while (subchild != null)
  +                        {
                               child.removeChild(subchild);
                               subchild = child.getLastChild();
                           }
                       }
                   }
               }
  -        } else {
  +        }
  +        else
  +        {
               // remove attributes from children
               Iterator cIter = children.iterator();
  -            while (cIter.hasNext()) {
  +            while (cIter.hasNext())
  +            {
                   Element child = (Element) cIter.next();
                   child.removeAttribute(attName);
               }
  @@ -480,11 +557,16 @@
        * Save the configuration if the automatic persistence is enabled and a file
        * is specified.
        */
  -    private void possiblySave() {
  -        if (autoSave && fileName != null) {
  -            try {
  +    private void possiblySave()
  +    {
  +        if (autoSave && fileName != null)
  +        {
  +            try
  +            {
                   save();
  -            } catch (ConfigurationException ce) {
  +            }
  +            catch (ConfigurationException ce)
  +            {
                   throw new ConfigurationRuntimeException("Failed to auto-save", ce);
               }
           }
  @@ -495,15 +577,13 @@
        *
        * @param autoSave
        */
  -    public void setAutoSave(boolean autoSave) {
  +    public void setAutoSave(boolean autoSave)
  +    {
           this.autoSave = autoSave;
       }
   
       /**
  -     * Save the configuration to the specified stream.
  -     *
  -     * @param writer
  -     *            the output stream used to save the configuration
  +     * {@inheritDoc}
        */
       public void save(Writer writer) throws ConfigurationException
       {
  @@ -522,30 +602,15 @@
           }
       }
   
  -    /**
  -     * Returns the file.
  -     *
  -     * @return File
  -     */
  -    public File getFile() {
  -        return ConfigurationUtils.constructFile(getBasePath(), getFileName());
  -    }
  -
  -    /**
  -     * Sets the file.
  -     *
  -     * @param file
  -     *            The file to set
  -     */
  -    public void setFile(File file) {
  -        this.fileName = file.getAbsolutePath();
  -    }
  -
  -    public String toString() {
  +    public String toString()
  +    {
           StringWriter writer = new StringWriter();
  -        try {
  +        try
  +        {
               save(writer);
  -        } catch (ConfigurationException e) {
  +        }
  +        catch (ConfigurationException e)
  +        {
               e.printStackTrace();
           }
           return writer.toString();
  @@ -560,14 +625,19 @@
        *
        * @return the elements in the key
        */
  -    protected static String[] parseElementNames(String key) {
  -        if (key == null) {
  -            return new String[] {};
  -        } else {
  +    protected static String[] parseElementNames(String key)
  +    {
  +        if (key == null)
  +        {
  +            return new String[]{};
  +        }
  +        else
  +        {
               // find the beginning of the attribute name
               int attStart = key.indexOf(ATTRIBUTE_START);
   
  -            if (attStart > -1) {
  +            if (attStart > -1)
  +            {
                   // remove the attribute part of the key
                   key = key.substring(0, attStart);
               }
  @@ -584,14 +654,17 @@
        *
        * @return the attribute name, or null if the key doesn't contain one
        */
  -    protected static String parseAttributeName(String key) {
  +    protected static String parseAttributeName(String key)
  +    {
           String name = null;
   
  -        if (key != null) {
  +        if (key != null)
  +        {
               // find the beginning of the attribute name
               int attStart = key.indexOf(ATTRIBUTE_START);
   
  -            if (attStart > -1) {
  +            if (attStart > -1)
  +            {
                   // find the end of the attribute name
                   int attEnd = key.indexOf(ATTRIBUTE_END);
                   attEnd = attEnd > -1 ? attEnd : key.length();
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message