Java/XML/XML Properties

Материал из Java эксперт
Версия от 07:11, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Parse Properties Files

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.Properties;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.Properties;
import java.util.Enumeration;
import org.apache.xerces.parsers.*;
public class ParseNonXML extends DefaultHandler {
  public static void main(String args[]) throws SAXException {
    PropertyFileParser pfp = new PropertyFileParser();
    pfp.setContentHandler(new ParseNonXML());
    pfp.parse(buildProperties());
  }
  public static Properties buildProperties() {
    Properties props = new Properties();
    for (int i = 0; i < 10; i++)
      props.setProperty("key" + i, "value" + i);
    return props;
  }
  public void startDocument() {
    System.out.println("<keys>");
  }
  public void endDocument() {
    System.out.println("</keys>");
  }
  public void characters(char[] data, int start, int end) {
    String str = new String(data, start, end);
    System.out.print(str);
  }
  public void startElement(String uri, String qName, String lName, Attributes atts) {
    System.out.print("<" + lName + ">");
  }
  public void endElement(String uri, String qName, String lName) {
    System.out.println("</" + lName + ">");
  }
}
class PropertyFileParser extends SAXParser {
  private Properties props = null;
  private ContentHandler handler = null;
  public void parse(Properties props) throws SAXException {
    handler = getContentHandler();
    handler.startDocument();
    Enumeration e = props.propertyNames();
    while (e.hasMoreElements()) {
      String key = (String) e.nextElement();
      String val = (String) props.getProperty(key);
      handler.startElement("", key, key, new AttributesImpl());
      char[] chars = getChars(val);
      handler.characters(chars, 0, chars.length);
      handler.endElement("", key, key);
    }
    handler.endDocument();
  }
  private char[] getChars(String value) {
    char[] chars = new char[value.length()];
    value.getChars(0, value.length(), chars, 0);
    return chars;
  }
}





Properties To XML

/*-- 
 Copyright (C) 2001 Brett McLaughlin.
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions, and the following disclaimer.
 
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions, and the disclaimer that follows 
    these conditions in the documentation and/or other materials 
    provided with the distribution.
 3. The name "Java and XML" must not be used to endorse or promote products
    derived from this software without prior written permission.  For
    written permission, please contact brett@newInstance.ru.
 
 In addition, we request (but do not require) that you include in the 
 end-user documentation provided with the redistribution and/or in the 
 software itself an acknowledgement equivalent to the following:
     "This product includes software developed for the
      "Java and XML" book, by Brett McLaughlin (O"Reilly & Associates)."
 THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED.  IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
 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.
 */
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.jdom.Attribute;
import org.jdom.rument;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.jdom.output.XMLOutputter;
/**
 * <b><code>PropsToXML</code></b> takes a standard Java properties
 *   file, and converts it into an XML format. This makes properties
 *   like <code>enhydra.classpath.separator</code> "groupbable" by
 *   "enhydra", "classpath", and by the key name, "separator", which
 *   the standard Java <code>java.util.Properties</code> class does
 *   not allow.
 */
public class PropsToXML {
    
    /**
     * <p> This will take the supplied properties file, and
     *   convert that file to an XML representation, which is
     *   then output to the supplied XML document filename. </p>
     *
     * @param propertiesFilename file to read in as Java properties.
     * @param xmlFilename file to output XML representation to.
     * @throws <code>IOException</code> - when errors occur.
     */
    public void convert(String propertiesFilename, String xmlFilename)
        throws IOException {
            
        // Get Java Properties object
        FileInputStream input = new FileInputStream(propertiesFilename);
        Properties props = new Properties();
        props.load(input);
        
        // Convert to XML
        convertToXML(props, xmlFilename);
    }        
    
    /**
     * <p> This will handle the detail of conversion from a Java
     *  <code>Properties</code> object to an XML document. </p>
     *
     * @param props <code>Properties</code> object to use as input.
     * @param xmlFilename file to output XML to.
     * @throws <code>IOException</code> - when errors occur.
     */
    private void convertToXML(Properties props, String xmlFilename)
        throws IOException {
    
        // Create a new JDOM Document with a root element "properties"
        Element root = new Element("properties");
        Document doc = new Document(root);
        
        // Get the property names
        Enumeration propertyNames = props.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyName = (String)propertyNames.nextElement();
            String propertyValue = props.getProperty(propertyName);
            createXMLRepresentation(root, propertyName, propertyValue);
        }        
        
        // Output document to supplied filename
        XMLOutputter outputter = new XMLOutputter("  ", true);
        FileOutputStream output = new FileOutputStream(xmlFilename);
        outputter.output(doc, output); 
    }
    
    /**
     * <p> This will convert a single property and its value to
     *  an XML element and textual value. </p>
     *
     * @param root JDOM root <code>Element</code> to add children to.
     * @param propertyName name to base element creation on.
     * @param propertyValue value to use for property.
     */
    private void createXMLRepresentation(Element root, 
                                         String propertyName,
                                         String propertyValue) {
        
        /*           
        Element element = new Element(propertyName);
        element.setText(propertyValue);
        root.addContent(element);
        */
        
        int split;
        String name = propertyName;
        Element current = root;
        Element test = null;
              
        while ((split = name.indexOf(".")) != -1) {
            String subName = name.substring(0, split);
            name = name.substring(split+1);
            
            // Check for existing element            
            if ((test = current.getChild(subName)) == null) {
                Element subElement = new Element(subName);
                current.addContent(subElement);
                current = subElement;
            } else {
                current = test;
            }
        }
        
        // When out of loop, what"s left is the final element"s name        
        Element last = new Element(name);                        
        // last.setText(propertyValue);
        last.setAttribute("value", propertyValue);
        current.addContent(last);
    }
                                        
    /**
     * <p> Provide a static entry point for running. </p>
     */
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java PropsToXML " +
                "[properties file] [XML file for output]");
            System.exit(0);
        }
        
        try {
            PropsToXML propsToXML = new PropsToXML();
            propsToXML.convert(args[0], args[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }        
    }
}
/*-- 
 Copyright (C) 2001 Brett McLaughlin.
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions, and the following disclaimer.
 
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions, and the disclaimer that follows 
    these conditions in the documentation and/or other materials 
    provided with the distribution.
 3. The name "Java and XML" must not be used to endorse or promote products
    derived from this software without prior written permission.  For
    written permission, please contact brett@newInstance.ru.
 
 In addition, we request (but do not require) that you include in the 
 end-user documentation provided with the redistribution and/or in the 
 software itself an acknowledgement equivalent to the following:
     "This product includes software developed for the
      "Java and XML" book, by Brett McLaughlin (O"Reilly & Associates)."
 THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED.  IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
 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.
 */
/**
 * <b><code>XMLProperties</code></b> extends Java"s 
 *  <code>java.util.Properties</code> class, and provides
 *  behavior similar to properties but that use XML as the
 *  input and output format.
 */
class XMLProperties extends Properties {
    
    /**
     * <p> This overrides the default <code>load()</code>
     *   behavior to read from an XML document. </p>
     *
     * @param reader the reader to read XML from
     * @throws <code>IOException</code> - when errors occur reading.
     */
    public void load(Reader reader) 
        throws IOException {
        
        try { 
            // Load XML into JDOM Document
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(reader);
            
            // Turn into properties objects
            loadFromElements(doc.getRootElement().getChildren(), 
                new StringBuffer(""));
            
        } catch (JDOMException e) {
            throw new IOException(e.getMessage());
        }        
    }    
    /**
     * <p> This overrides the default <code>load()</code>
     *   behavior to read from an XML document. </p>
     *
     * @param inputStream the input stream
     * @throws <code>IOException</code> - when errors occur reading.
     */
    public void load(InputStream inputStream) 
        throws IOException {
         
        load(new InputStreamReader(inputStream));    
    }
    
    /**
     * <p> This overrides the default <code>load()</code>
     *   behavior to read from an XML document. </p>
     *
     * @param xmlDocument the XML document to read
     * @throws <code>IOException</code> - when errors occur reading.
     */
    public void load(File xmlDocument) 
        throws IOException {
        
        load(new FileReader(xmlDocument));    
    }  
    
    /**
     * <p>This helper method loads the XML properties from a specific
     *   XML element, or set of elements.</p>
     *
     * @param elements <code>List</code> of elements to load from.
     * @param baseName the base name of this property.
     */
    private void loadFromElements(List elements, StringBuffer baseName) {
        // Iterate through each element
        for (Iterator i = elements.iterator(); i.hasNext(); ) {
            Element current = (Element)i.next();
            String name = current.getName();
            String text = current.getTextTrim();
            // String text = current.getAttributeValue("value");            
            
            // Don"t add "." if no baseName
            if (baseName.length() > 0) {
                baseName.append(".");
            }            
            baseName.append(name);
            
            // See if we have an element value
            if ((text == null) || (text.equals(""))) {
                // If no text, recurse on children
                loadFromElements(current.getChildren(),
                                 baseName);
            } else {                
                // If text, this is a property
                setProperty(baseName.toString(), 
                            text);
            }            
            
            // On unwind from recursion, remove last name
            if (baseName.length() == name.length()) {
                baseName.setLength(0);
            } else {                
                baseName.setLength(baseName.length() - 
                    (name.length() + 1));
            }            
        }        
    }    
    
    /**
     * @deprecated This method does not throw an IOException
     *   if an I/O error occurs while saving the property list.
     *   As of the Java 2 platform v1.2, the preferred way to save
     *   a properties list is via the 
     *   <code>{@link store(OutputStream out, String header}</code>
     *   method.
     */
    public void save(OutputStream out, String header) {
        try {            
            store(out, header);
        } catch (IOException ignored) {
            // Deprecated version doesn"t pass errors
        }        
    }   
    
    /**
     * <p> This will output the properties in this object
     *   as XML to the supplied output writer. </p>
     *
     * @param writer the writer to output XML to.
     * @param header comment to add at top of file
     * @throws <code>IOException</code> - when writing errors occur.
     */ 
    public void store(Writer writer, String header)
        throws IOException {
            
        // Create a new JDOM Document with a root element "properties"
        Element root = new Element("properties");
        Document doc = new Document(root);
        
        // Add in header information
        Comment comment = new Comment(header);
        doc.getContent().add(0, comment);
        
        // Get the property names
        Enumeration propertyNames = propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyName = (String)propertyNames.nextElement();
            String propertyValue = getProperty(propertyName);
            createXMLRepresentation(root, propertyName, propertyValue);
        }        
        
        // Output document to supplied filename
        XMLOutputter outputter = new XMLOutputter("  ", true);
        outputter.output(doc, writer);
        writer.flush();
    }    
    
    /**
     * <p> This will output the properties in this object
     *   as XML to the supplied output stream. </p>
     *
     * @param out the output stream.
     * @param header comment to add at top of file
     * @throws <code>IOException</code> - when writing errors occur.
     */ 
    public void store(OutputStream out, String header)
        throws IOException {
            
        store(new OutputStreamWriter(out), header);
    }
    
    /**
     * <p> This will output the properties in this object
     *   as XML to the supplied output file. </p>
     *
     * @param xmlDocument XML file to output to.
     * @param header comment to add at top of file
     * @throws <code>IOException</code> - when writing errors occur.
     */ 
    public void store(File xmlDocument, String header)
        throws IOException {
            
        store(new FileWriter(xmlDocument), header);
    }    
    
    /**
     * <p> This will convert a single property and its value to
     *  an XML element and textual value. </p>
     *
     * @param root JDOM root <code>Element</code> to add children to.
     * @param propertyName name to base element creation on.
     * @param propertyValue value to use for property.
     */
    private void createXMLRepresentation(Element root, 
                                         String propertyName,
                                         String propertyValue) {
        
        int split;
        String name = propertyName;
        Element current = root;
        Element test = null;
              
        while ((split = name.indexOf(".")) != -1) {
            String subName = name.substring(0, split);
            name = name.substring(split+1);
            
            // Check for existing element            
            if ((test = current.getChild(subName)) == null) {
                Element subElement = new Element(subName);
                current.addContent(subElement);
                current = subElement;
            } else {
                current = test;
            }
        }
        
        // When out of loop, what"s left is the final element"s name        
        Element last = new Element(name);                        
        last.setText(propertyValue);
        /** Uncomment this for Attribute usage */
        /*
        last.setAttribute("value", propertyValue);
        */
        current.addContent(last);
    }                
}
/*-- 
 Copyright (C) 2001 Brett McLaughlin.
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions, and the following disclaimer.
 
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions, and the disclaimer that follows 
    these conditions in the documentation and/or other materials 
    provided with the distribution.
 3. The name "Java and XML" must not be used to endorse or promote products
    derived from this software without prior written permission.  For
    written permission, please contact brett@newInstance.ru.
 
 In addition, we request (but do not require) that you include in the 
 end-user documentation provided with the redistribution and/or in the 
 software itself an acknowledgement equivalent to the following:
     "This product includes software developed for the
      "Java and XML" book, by Brett McLaughlin (O"Reilly & Associates)."
 THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED.  IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
 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.
 */
/**
 * <b><code>TestXMLProperties</code></b> is a simple class that tests
 *   usage of the <code>{@link XMLProperties}</code> class for reading
 *   XML property files.
 */
class TestXMLProperties {
    /**
     * <p>Provide a static entry point for testing.</p>
     */
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java TestXMLProperties " +
                "[XML input document] [XML output document]");
            System.exit(0);
        }
    
        try {
            // Create and load properties
            System.out.println("Reading XML properties from " + args[0]);
            XMLProperties props = new XMLProperties();
            props.load(new FileInputStream(args[0]));
            
            // Print out properties and values
            System.out.println("\n\n---- Property Values ----");
            Enumeration names = props.propertyNames();
            while (names.hasMoreElements()) {
                String name = (String)names.nextElement();
                String value = props.getProperty(name);
                System.out.println("Property Name: " + name + 
                                   " has value " + value);
            }            
            
            // Store properties
            System.out.println("\n\nWriting XML properies to " + args[1]);
            props.store(new FileOutputStream(args[1]),
                "Testing XMLProperties class");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// Demo file: enhydra.properties
/*
#
# This file has several Enhydra-specific properties
#   to make available to Java programs running with
#   knowledge of this properties file.
#
# sax parser implementing class
org.xml.sax.parser="org.apache.xerces.parsers.SAXParser"
# Class used to start the server
org.enhydra.initialclass=org.enhydra.multiServer.bootstrap.Bootstrap
# initial arguments passed to the server
org.enhydra.initialargs="./bootstrap.conf"
# Classpath for the parent top enhydra classloader
org.enhydra.classpath="."
# separator for the classpath above
org.enhydra.classpath.separator=":"

*/