You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@empire-db.apache.org by do...@apache.org on 2008/08/06 10:47:43 UTC

svn commit: r683173 [10/10] - in /incubator/empire-db/trunk/core/Empire-db: ./ .settings/ bin/ lib/ src/ src/META-INF/ src/org/ src/org/apache/ src/org/apache/empire/ src/org/apache/empire/commons/ src/org/apache/empire/data/ src/org/apache/empire/data...

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLConfiguration.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLConfiguration.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLConfiguration.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLConfiguration.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,210 @@
+/*
+ * ESTEAM Software GmbH, 30.08.2007
+ */
+package org.apache.empire.xml;
+
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.commons.beanutils.BeanUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.empire.commons.ErrorObject;
+import org.apache.empire.commons.Errors;
+import org.apache.empire.commons.ObjectUtils;
+import org.apache.empire.commons.StringUtils;
+import org.apache.log4j.xml.DOMConfigurator;
+import org.w3c.dom.Document;
+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;
+
+
+/**
+ * <PRE>
+ * This class manages the configuration of a Java Bean by an xml configuration file.
+ * It also supports configuration of Log4J.
+ * </PRE>
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public class XMLConfiguration extends ErrorObject
+{
+    // Logger (not final!)
+    protected static Log log = LogFactory.getLog(XMLConfiguration.class);
+
+    private String     loggingNodeName = "log4j:configuration";
+
+    private Element    configRootNode  = null;
+
+    /**
+     * Initialize the configuration.
+     */
+    public boolean init(String filename, boolean fromResource, boolean initLogging)
+    {
+        // Read the properties file
+        if (readConfiguration(filename, fromResource) == false)
+            return false;
+        // Configure Logging
+        if (initLogging)
+            initLogging();
+        // Done
+        return success();
+    }
+
+    /**
+     * Reads the configuration file and parses the XML Configuration.
+     */
+    protected boolean readConfiguration(String fileName, boolean fromResource)
+    {
+        FileReader reader = null;
+        InputStream inputStream = null;
+        try
+        {
+            DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+            Document doc = null;
+            if (fromResource)
+            {   // Open Resource
+                log.info("reading resource file: " + fileName);
+                inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
+                // Parse File
+                doc = docBuilder.parse(inputStream);
+            }
+            else
+            {   // Open File
+                log.info("reading configuration file: " + fileName);
+                reader = new FileReader(fileName);
+                // Parse File
+                doc = docBuilder.parse(new InputSource(reader));
+            }
+            // Get Root Element
+            configRootNode = doc.getDocumentElement();
+            return success();
+        } catch (FileNotFoundException e)
+        {
+            log.error("Configuration file not found! filename=" + fileName);
+            return error(Errors.FileNotFound, fileName);
+        } catch (IOException e)
+        {
+            log.error("Error reading configuration file " + fileName);
+            return error(Errors.FileReadError, fileName);
+        } catch (SAXException e)
+        {
+            log.error("Invalid XML in configuraion file " + fileName, e);
+            return error(e);
+        } catch (ParserConfigurationException e)
+        {
+            log.error("ParserConfigurationException ", e);
+            return error(e);
+        } finally
+        { // Close reader
+            try
+            {
+                if (reader != null)
+                    reader.close();
+                if (inputStream != null)
+                    inputStream.close();
+            } catch (Exception e)
+            {
+                // Nothing to do.
+            }
+        }
+    }
+
+    protected boolean initLogging()
+    {
+        // Check state
+        if (configRootNode == null)
+            return error(Errors.ObjectNotValid, getClass().getName());
+        // Configure Logging
+        if (StringUtils.isValid(loggingNodeName) == false)
+            return success();
+        // Find loggingNode
+        Element loggingNode = XMLUtil.findFirstChild(configRootNode, loggingNodeName);
+        if (loggingNode == null)
+        { // Configuration
+            log.fatal("Logging-Node " + loggingNodeName + " has not been found. Logging has not been configured.");
+            return error(Errors.ItemNotFound, loggingNodeName);
+        }
+        // Init Log4J
+        LogFactory.releaseAll();
+        DOMConfigurator.configure(loggingNode);
+        // Get the new Logger
+        log = LogFactory.getLog(XMLConfiguration.class);
+        log.info("Logging sucessfully configured.");
+        // done
+        return success();
+    }
+
+    public boolean readProperties(Object bean, String propertiesNodeName)
+    {
+        // Check state
+        if (configRootNode == null)
+            return error(Errors.ObjectNotValid, getClass().getName());
+        // Check arguments
+        if (bean == null)
+            return error(Errors.InvalidArg, null, "bean");
+        if (StringUtils.isValid(propertiesNodeName) == false)
+            return error(Errors.InvalidArg, null, "propertiesNodeName");
+        // Get Configuraiton Node
+        Element propertiesNode = XMLUtil.findFirstChild(configRootNode, propertiesNodeName);
+        if (propertiesNode == null)
+        { // Configuration
+            log.error("Property-Node " + propertiesNodeName + " has not been found.");
+            return error(Errors.ItemNotFound, propertiesNodeName);
+        }
+        // configure Connection
+        log.info("reading bean properties from node: " + propertiesNodeName);
+        NodeList nodeList = propertiesNode.getChildNodes();
+        for (int i = 0; i < nodeList.getLength(); i++)
+        {
+            Node item = nodeList.item(i);
+            if (item.getNodeType() != Node.ELEMENT_NODE)
+                continue;
+            // Get the Text and set the Property
+            setPropertyValue(bean, item);
+        }
+        // done
+        return success();
+    }
+    
+    protected void setPropertyValue(Object bean, Node item)
+    {
+        // Get the Text and set the Property
+        String name = item.getNodeName();
+        try
+        {
+            String value = XMLUtil.getElementText(item);
+            BeanUtils.setProperty(bean, name, value);
+
+            Object check = BeanUtils.getProperty(bean, name);
+            if (ObjectUtils.compareEqual(value, check)==false)
+            {
+                log.error("Failed to set property '" + name + "'. Value is " + String.valueOf(check));
+                return;
+            }
+
+            // success
+            log.info("Configuration property '" + name + "' set to \"" + value + "\"");
+
+        } catch (IllegalAccessException e)
+        {
+            log.error("Access to Property " + name + " denied.");
+        } catch (InvocationTargetException e)
+        {
+            log.error("Unable to set Property " + name);
+        } catch (NoSuchMethodException e)
+        {
+            log.error("Property '"  + name + "' not found in " + bean.getClass().getName());
+        }
+    }
+
+}

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLUtil.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLUtil.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLUtil.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLUtil.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,516 @@
+/*
+ * ESTEAM Software GmbH, 13.12.2004
+ */
+package org.apache.empire.xml;
+
+import java.util.Iterator;
+import java.util.Map;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * This class provides a collection of static helper functions for common XML tasks.
+ * The class cannot be instanciated since all.
+ * methods provided are declared static.
+ * <P>
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public class XMLUtil
+{
+    protected static Log log = LogFactory.getLog(XMLUtil.class);
+    
+    /**
+     * DocumentBuilder that is aware of namespaces. This is necessary for parsing xsl files.
+     */
+    private static DocumentBuilder documentBuilder = null;
+
+    /* Static initializer: */
+    static
+    {
+        /* Instantiate a DocumentBuilderFactory. */
+        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
+        /* And setNamespaceAware, which is required when parsing xsl files. */
+        dFactory.setNamespaceAware(true);
+        try
+        {
+            /* Use the DocumentBuilderFactory to create a DocumentBuilder. */
+            documentBuilder = dFactory.newDocumentBuilder();
+        } catch (ParserConfigurationException e)
+        {
+            log.error("XMLUtil::createDocument-->", e);
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * Class contains only static functions! Constructor not available!
+     */
+    private XMLUtil()
+    {
+        /* No instances necessary */
+    }
+
+    /**
+     * Returns a document newly created by the class's static DocumentBuilder.
+     * 
+     * @return An empty DOM document.
+     */
+    static public synchronized Document createDocument()
+    {
+        return documentBuilder.newDocument();
+    }
+
+    /**
+     * Returns an initialzed, namespace aware DocumentBuilder.
+     * 
+     * @return The DocumentBuilder.
+     */
+    static public DocumentBuilder getDocumentBuilder()
+    {
+        return documentBuilder;
+    }
+
+    static public synchronized Element createDocument(String rootElemName)
+    {
+        // create document
+        Document doc = createDocument();
+        Element root = doc.createElement(rootElemName);
+        doc.appendChild(root);
+        return root;
+    }
+
+    static public synchronized Element createDocumentNS(String prefix, String rootElemName, Map<String, String> nsMap)
+    {
+        // create document
+        Document doc = createDocument();
+        // prefix
+        Element root = null;
+        if (prefix != null && prefix.length() > 0)
+        { // Find matching URI
+            String uri = nsMap.get(prefix);
+            if (uri == null)
+            {
+                log.error("Namespace URI for namespace " + prefix + " not found!");
+                return null;
+            }
+            // create Document
+            root = doc.createElementNS(uri, prefix + ":" + rootElemName);
+        } 
+        else
+        {
+            root = doc.createElement(rootElemName);
+        }
+        doc.appendChild(root);
+        // Add Namespace attributes
+        addNamespaceURIs(doc, nsMap);
+        return root;
+    }
+
+    static public boolean addNamespaceURIs(Document doc, Map<String, String> nsMap)
+    {
+        Element root = doc.getDocumentElement();
+        if (root == null)
+            return false;
+        // Add Namespace attributes
+        Iterator<String> i = nsMap.keySet().iterator();
+        while (i.hasNext())
+        {
+            String key = i.next();
+            String val = nsMap.get(key);
+            root.setAttribute("xmlns:" + key, val);
+        }
+        return true;
+    }
+
+    static public String getNamespaceURI(Document doc, String prefix)
+    {
+        Element e = doc.getDocumentElement();
+        return e.getAttributeNS("", prefix);
+    }
+
+    /**
+     * Gets the first (direct) child Element.
+     * 
+     * @param parent the parent element below which to search the child
+     * @return the first child element, or null otherwise
+     */
+    static public Element getFirstChild(Node parent)
+    { // Child Element suchen
+        if (parent == null)
+            return null;
+        Node node = parent.getFirstChild();
+        while (node != null)
+        { // Find all Element nodes
+            if (node.getNodeType() == Node.ELEMENT_NODE)
+                return (Element) node; // found
+            node = node.getNextSibling();
+        }
+        return null; // not found!
+    }
+
+    /**
+     * Finds the first (direct) child Element with a given tag name.
+     * 
+     * @param parent the parent element below which to search the child
+     * @param tagName the (tag) name of the desired child element
+     * @return the child element if an element of that name existed, or null otherwise
+     */
+    static public Element findFirstChild(Node parent, String tagName)
+    { // Child Element suchen
+        if (parent == null)
+            return null;
+        Node node = parent.getFirstChild();
+        while (node != null)
+        { // Find all Element nodes
+            if (node.getNodeType() == Node.ELEMENT_NODE)
+            { // check name
+                Element elem = (Element) node;
+                if (tagName.equalsIgnoreCase(elem.getTagName()))
+                    return elem; // found
+            }
+            node = node.getNextSibling();
+        }
+        return null; // not found!
+    }
+
+    /**
+     * Returns the next sibling Element for an element, optionally matching tag names.
+     * 
+     * @param child the element from which to search for a next sibling
+     * @param sameName true to retrive the next sibling element of the same name, of false if any name is allowed
+     * @return the next sibling element if one exists, or null otherwise
+     */
+    static public Element getNextSiblingElement(Element child, boolean sameName)
+    { // Child Element suchen
+        if (child == null)
+            return null;
+        String name = child.getTagName();
+        Node node = child.getNextSibling();
+        while (node != null)
+        { // Find all Element nodes
+            if (node.getNodeType() == Node.ELEMENT_NODE)
+            { // check name
+                Element elem = (Element) node;
+                if (sameName && name.equalsIgnoreCase(elem.getTagName()))
+                    return elem; // found
+            }
+            node = node.getNextSibling();
+        }
+        return null; // not found!
+    }
+
+    /**
+     * Finds the first (direct) child element with a given tag name and attribute.
+     * 
+     * @param parent the parent element below which to search the child
+     * @param tagName the (tag) name of the desired child element
+     * @param attrName the name of the attribute which value must match the given value
+     * @param value the attribute value to which elements are matched.
+     * @return the child element if an element of that name existed, or null otherwise
+     */
+    static public Element findFirstChildWithAttrib(Node parent, String tagName, String attrName, Object value)
+    {
+        Element elem = findFirstChild(parent, tagName);
+        if (attrName == null)
+            return null;
+        while (elem != null)
+        { // Check Value
+            String attrValue = elem.getAttribute(attrName);
+            if (attrValue == null || attrValue.length() < 1)
+            { // Attribute is null
+                if (value == null)
+                    break; // gefunden!
+            } 
+            else
+            { // Attribute is not null
+                if (attrValue.equals(value.toString()))
+                    break; // gefunden!
+            }
+            // next
+            elem = getNextSiblingElement(elem, true);
+        }
+        return elem;
+    }
+
+    /**
+     * Finds the first element which name matchtes a given tag name
+     * that is locacted anywhere below the given parent.
+     * 
+     * @param parent the parent element below which to search the child
+     * @param tagName the (tag) name of the desired child element
+     * @return the child element if an element of that name existed, or null otherwise
+     */
+    static public Element findFirstChildDeep(Element parent, String tagName)
+    { // Child Element suchen
+        if (parent == null)
+            return null;
+        NodeList nl = parent.getElementsByTagName(tagName);
+        for (int i = 0; i < nl.getLength(); i++)
+        {
+            if (nl.item(i).getNodeType() == Node.ELEMENT_NODE)
+                return (Element) nl.item(i);
+        }
+        return null;
+    }
+
+    /**
+     * Returns the first element which name matchtes a given tag name.
+     * 
+     * @param doc the xml document in which to find an element of the given name
+     * @param tagName the (tag) name of the desired child element
+     * @return the child element if an element of that name existed, or null otherwise
+     */
+    static public Element findFirstChildDeep(Document doc, String tagName)
+    { // Child Element suchen
+        if (doc == null)
+            return null;
+        return findFirstChildDeep(doc.getDocumentElement(), tagName);
+    }
+
+    /**
+     * Retrieves the text of a given element.
+     * 
+     * @param elem the Element for which the text value is requested
+     * @return the text value of that element or null if the element has no text value
+     */
+    static public String getElementText(Node elem)
+    {
+        String value = null;
+        Node node = (elem != null) ? elem.getFirstChild() : null;
+        // Find Text
+        while (node != null)
+        { // Find all Text nodes
+            if (node.getNodeType() == Node.TEXT_NODE)
+            { // set or append
+                if (value == null)
+                    value = node.getNodeValue();
+                else
+                    value += node.getNodeValue();
+            }
+            node = node.getNextSibling();
+        }
+        return value;
+    }
+
+    /**
+     * Sets the text value of an Element. if current text of the element is
+     * replaced with the new text if text is null any
+     * current text value is deleted.
+     * 
+     * @param elem the Element for which the text value should be set
+     * @param text the new text value of the element
+     * @return true if the text could be set or false otherwise
+     */
+    static public boolean setElementText(Node elem, Object text)
+    {
+        if (elem == null)
+            return false; // Fehler
+        // Find Text
+        Node node = elem.getFirstChild();
+        while (node != null)
+        { // Find all Text nodes
+            if (node.getNodeType() == Node.TEXT_NODE)
+                break; // gefunden
+            node = node.getNextSibling();
+        }
+        if (node != null)
+        { // Set or remove text
+            if (text != null)
+                node.setNodeValue(text.toString());
+            else
+                elem.removeChild(node);
+        } 
+        else if (text != null)
+        { // Add Text
+            elem.appendChild(elem.getOwnerDocument().createTextNode(text.toString()));
+        }
+        return true;
+    }
+
+    /**
+     * Adds a new child element to a parent.
+     * 
+     * @param parent the Element to which to append the child
+     * @param name the (tag) name of the new child
+     * @param value the text value of the new element. (can be null!)
+     * @return the new child element
+     */
+    static public Element addElement(Node parent, String name, String value)
+    {
+        if (parent == null)
+            return null; // Fehler
+        Element child = parent.getOwnerDocument().createElement(name);
+        if (value != null)
+            setElementText(child, value);
+        parent.appendChild(child);
+        return child;
+    }
+
+    /**
+     * Adds a child element to the parent.
+     * 
+     * @param parent
+     * @param name
+     * @return the newly created child element
+     */
+    static public Element addElement(Element parent, String name)
+    {
+        return addElement(parent, name, null);
+    }
+
+    /**
+     * Adds a new child element to a parent with a namespace.
+     * 
+     * @param parent the Element to which to append the child
+     * @param prefix the name of the namespace this element belongs to
+     * @param name the (tag) name of the new child
+     * @param value the text value of the new element. (can be null!)
+     * @return the new child element
+     */
+    static public Element addElementNS(Node parent, String prefix, String name, String value)
+    {
+        if (parent == null)
+            return null; // Fehler
+        // URI
+        if (prefix == null || prefix.length() == 0)
+            return addElement(parent, name, value);
+        // Find matching URI
+        Document doc = parent.getOwnerDocument();
+        String uri = getNamespaceURI(doc, prefix);
+        if (uri == null)
+        {
+            log.error("Namespace URI for namespace " + prefix + " not found!");
+            return null;
+        }
+        Element child = doc.createElementNS(uri, prefix + ":" + name);
+        if (value != null)
+            setElementText(child, value);
+        parent.appendChild(child);
+        return child;
+    }
+
+    static public Element addElementNS(Element parent, String prefix, String name)
+    {
+        return addElementNS(parent, prefix, name, null);
+    }
+
+    /**
+     * Inserts a new child element to a parent.
+     * 
+     * @param parent the Element to which to append the child
+     * @param name the (tag) name of the new child
+     * @param value the text value of the new element. (can be null!)
+     * @return the new child element
+     */
+    static public Element insertElement(Node parent, String name, String value, Element pos)
+    {
+        if (parent == null)
+            return null; // Fehler
+        Element child = parent.getOwnerDocument().createElement(name);
+        if (value != null)
+            setElementText(child, value);
+        // insert now
+        parent.insertBefore(child, pos);
+        return child;
+    }
+
+    static public Element insertElement(Node parent, String name, Element pos)
+    {
+        return insertElement(parent, name, null, pos);
+    }
+
+    /**
+     * Inserts a new child element to a parent.
+     * 
+     * @param parent the Element to which to append the child
+     * @param name the (tag) name of the new child
+     * @param value the text value of the new element. (can be null!)
+     * @return the new child element
+     */
+    static public Element insertElementNS(Node parent, String prefix, String name, String value, Element pos)
+    {
+        if (parent == null)
+            return null; // Fehler
+        // Has prefix?
+        if (prefix == null || prefix.length() == 0)
+            return insertElement(parent, name, value, pos);
+        // Find matching URI
+        Document doc = parent.getOwnerDocument();
+        String uri = getNamespaceURI(doc, prefix);
+        if (uri == null)
+        {
+            log.error("Namespace URI for namespace " + prefix + " not found!");
+            return null;
+        }
+        Element child = doc.createElementNS(uri, prefix + ":" + name);
+        if (value != null)
+            setElementText(child, value);
+        // insert now
+        parent.insertBefore(child, pos);
+        return child;
+    }
+
+    static public Element insertElementNS(Node parent, String prefix, String name, Element pos)
+    {
+        return insertElementNS(parent, prefix, name, null, pos);
+    }
+
+    /**
+     * Returns the text value of a given child element.
+     * 
+     * @param parent the Element which contains the child
+     * @param childName the (tag) name of the child
+     * @return the text value of the child or null if no child exists or the child does not have a text value
+     */
+    static public String getChildText(Node parent, String childName)
+    {
+        Element elem = findFirstChild(parent, childName);
+        if (elem == null)
+            return null; // not Found!
+        return getElementText(elem);
+    }
+
+    /**
+     * Changes the tag name of an element.
+     * 
+     * @param elem Element which name should be changed
+     * @param newName new tag name of the element
+     * @return true if the name was changed successfully or false otherwise
+     */
+    static public boolean changeTagName(Element elem, String newName)
+    {
+        if (elem == null)
+            return false; // not Found!
+        Document doc = elem.getOwnerDocument();
+        Element newElem = doc.createElement(newName);
+
+        // Copy the attributes to the new element
+        NamedNodeMap attrs = elem.getAttributes();
+        for (int i = 0; i < attrs.getLength(); i++)
+        {
+            Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
+            newElem.getAttributes().setNamedItem(attr2);
+        }
+
+        // Copy all Child Elements
+        for (Node node = elem.getFirstChild(); node != null; node = node.getNextSibling())
+            newElem.appendChild(node.cloneNode(true));
+        // insert
+        Node parent = elem.getParentNode();
+        parent.replaceChild(newElem, elem);
+        return true;
+    }
+
+}
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLWriter.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLWriter.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLWriter.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/XMLWriter.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,469 @@
+/*
+ * ESTEAM Software GmbH
+ */
+package org.apache.empire.xml;
+
+// Java
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.empire.commons.ErrorObject;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+
+/**
+ * This class prints out a XML-DOM-Tree to an output stream.
+ * <P>
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public class XMLWriter extends ErrorObject
+{
+    // Logger
+    protected static Log   log                  = LogFactory.getLog(XMLWriter.class);
+
+    /** Print writer. */
+    protected PrintWriter  out;
+    /** Canonical output. */
+    protected boolean      canonical;
+    /** xmlWriterRoot for debugToFile function */
+    private static String  xmlWriterRoot        = null;
+
+    /** Default Encoding */
+    private String charsetEncoding = "utf-8";
+
+    /**
+     * Prints out the DOM-Tree on System.out for debugging purposes.
+     * 
+     * @param doc The XML-Document to print
+     */
+    public static void debug(Document doc)
+    {
+        XMLWriter dbg = new XMLWriter(System.out);
+        dbg.print(doc);
+    }
+
+    /**
+     * Prints out the DOM-Tree to a file for debugging purposes.
+     * The file will be truncated if it exists or created if if does
+     * not exist.
+     * 
+     * @param doc The XML-Document to print
+     * @param filename The name of the file to write the XML-Document to
+     */
+    public static void debugToFile(Document doc, String filename)
+    {
+
+        String styleSheet = "../" + filename.substring(0, filename.length() - 3) + "xslt";
+
+        FileOutputStream fileOutputStream = null;
+        try
+        {
+            File file = new File(xmlWriterRoot, filename);
+            if (file.exists() == true)
+            {
+                file.delete();
+            }
+            // do wen need this? file.createNewFile();
+            fileOutputStream = new FileOutputStream(file);
+            // write xml
+            XMLWriter dbg = new XMLWriter(fileOutputStream);
+            dbg.print(doc, styleSheet);
+        } catch (IOException ioe)
+        {
+            log.error("Error: Could not write XML to file: " + filename + " in directory: " + xmlWriterRoot);
+        } finally
+        {
+            try
+            {
+                if (fileOutputStream != null)
+                {
+                    fileOutputStream.close();
+                }
+            } catch (IOException ioe)
+            {
+                log.error("Cannot write Document file", ioe);
+                /* Ignore IOExceptions */
+            }
+        }
+    }
+
+    /**
+     * Prints out the DOM-Tree. The file will be truncated if it
+     * exists or created if if does not exist.
+     * 
+     * @param doc The XML-Document to print
+     * @param filename The name of the file to write the XML-Document to
+     */
+    public static void saveAsFile(Document doc, String filename)
+    {
+        try
+        {
+            File file = new File(filename);
+            if (file.exists() == true)
+            {
+                file.delete();
+            }
+
+            DOMSource domSource = new DOMSource(doc);
+            StreamResult streamResult = new StreamResult(file);
+
+            TransformerFactory transformerFactory = TransformerFactory.newInstance();
+            Transformer trf = transformerFactory.newTransformer();
+            trf.transform(domSource, streamResult);
+
+        } catch (Exception ex)
+        {
+            log.error("Error: Could not write XML to file: " + filename);
+        }
+    }
+
+    public static void setXmlWriterDebugPath(String path)
+    {
+        xmlWriterRoot = path;
+    }
+
+    /**
+     * Creates a XML Writer object.
+     * 
+     * @param writer a writer to the output stream
+     * @param charsetEncoding encoding type (i.e. utf-8)
+     */
+    public XMLWriter(Writer writer, String charsetEncoding)
+    { 
+        this.out = new PrintWriter(writer);
+        this.charsetEncoding = charsetEncoding; 
+        this.canonical = false;
+    }
+
+    /**
+     * Creates a XML Writer object.
+     * 
+     * @param outStream the output stream
+     */
+    public XMLWriter(OutputStream outStream, String charsetEncoding)
+                                            throws UnsupportedEncodingException
+    { // Set Debug Level
+        this(new OutputStreamWriter(outStream, charsetEncoding), charsetEncoding);
+    }
+
+    /**
+     * Constructor
+     * 
+     * @param outStream the output stream
+     */
+    public XMLWriter(OutputStream outStream)
+    { 	
+        try
+        {
+            this.charsetEncoding = "utf-8"; 
+            this.out = new PrintWriter(new OutputStreamWriter(outStream, charsetEncoding));
+            this.canonical = false;
+        } catch (UnsupportedEncodingException e)
+        {
+            log.error(e);
+        }
+    }
+
+    /**
+     * Prints the specified node recursively
+     * 
+     * @param node the current node to print
+     * @param level the nesting level used for indenting the output
+     * @return the node type of this node
+     */
+    public int print(Node node, int level)
+    {
+        // is there anything to do?
+        if (node == null)
+        {
+            return 0;
+        }
+
+        int type = node.getNodeType();
+        switch (type)
+        {
+            // print document
+            case Node.DOCUMENT_NODE:
+            { // Sound not come here
+                print(((Document) node).getDocumentElement(), 0);
+            }
+                break;
+            // print element with attributes
+            case Node.ELEMENT_NODE:
+            {
+                // out
+                out.print('<');
+                out.print(node.getNodeName());
+                Attr attrs[] = sortAttributes(node.getAttributes());
+                for (int i = 0; i < attrs.length; i++)
+                {
+                    Attr attr = attrs[i];
+                    out.print(' ');
+                    out.print(attr.getNodeName());
+                    out.print("=\"");
+                    out.print(normalize(attr.getNodeValue()));
+                    out.print('"');
+                }
+                // children
+                NodeList children = node.getChildNodes();
+                if (children != null)
+                {
+                    // close-tag
+                    int len = children.getLength();
+                    if (len > 0 && children.item(0).getNodeType() != Node.TEXT_NODE)
+                        out.println('>');
+                    else
+                        out.print('>');
+                    // Print all Children
+                    int prevType = 0;
+                    for (int i = 0; i < len; i++)
+                    {
+                        if (i > 0 || children.item(i).getNodeType() != Node.TEXT_NODE)
+                        { // Indent next Line
+                            for (int s = 0; s < level; s++)
+                                out.print(" ");
+                        }
+                        // Print a child
+                        prevType = print(children.item(i), level + 1);
+                    }
+                    // Endtag
+                    if (len > 0 && prevType != Node.TEXT_NODE)
+                    { // padding
+                        for (int s = 1; s < level; s++)
+                            out.print(" ");
+                    }
+                    out.print("</");
+                    out.print(node.getNodeName());
+                    out.println('>');
+                } 
+                else
+                    out.println("/>");
+                break;
+            }
+
+            // handle entity reference nodes
+            case Node.ENTITY_REFERENCE_NODE:
+            {
+                if (canonical)
+                {
+                    NodeList children = node.getChildNodes();
+                    if (children != null)
+                    {
+                        int len = children.getLength();
+                        for (int i = 0; i < len; i++)
+                        {
+                            print(children.item(i), level + 1);
+                        }
+                    }
+                } 
+                else
+                {
+                    out.print('&');
+                    out.print(node.getNodeName());
+                    out.print(';');
+                }
+                break;
+            }
+
+            // print cdata sections
+            case Node.CDATA_SECTION_NODE:
+            {
+                if (canonical == false)
+                {
+                    out.print("<![CDATA[");
+                    out.print(node.getNodeValue());
+                    out.println("]]>");
+                } 
+                else
+                    out.print(normalize(node.getNodeValue()));
+                break;
+            }
+
+            // print text
+            case Node.TEXT_NODE:
+            { // Text
+                out.print(normalize(node.getNodeValue()));
+                break;
+            }
+
+            // print processing instruction
+            case Node.PROCESSING_INSTRUCTION_NODE:
+            {
+                out.print("<?");
+                out.print(node.getNodeName());
+                String data = node.getNodeValue();
+                if (data != null && data.length() > 0)
+                {
+                    out.print(' ');
+                    out.print(data);
+                }
+                out.println("?>");
+                break;
+            }
+        }
+
+        out.flush();
+        return type;
+
+    } // print(Node)
+
+    /**
+     * Prints the specified document.
+     * 
+     * @param doc the XML-DOM-Document to print
+     */
+    public void print(Document doc)
+    {
+        print(doc, null);
+    }
+
+    /**
+     * Prints the specified document.
+     * 
+     * @param doc the XML-DOM-Document to print
+     * @param styleSheet the XML-DOM-Document to print
+     */
+    public void print(Document doc, String styleSheet)
+    {
+        if (!canonical)
+        {
+            out.println("<?xml version=\"1.0\" encoding=\"" + charsetEncoding + "\"?>");
+        }
+        if (styleSheet != null)
+        {
+            //20040427 Marco: xml stylesheet document specification changed from "<?xml:stylesheet name=\"text/xsl\" href=\""
+            // to
+            // "<?xml-stylesheet type=\"text/xsl\" href=\""
+            out.print("<?xml-stylesheet type=\"text/xsl\" href=\"");
+            out.print(styleSheet);
+            out.println("\"?>");
+        }
+        // Print the Document
+        print(doc.getDocumentElement(), 0);
+        out.flush();
+    }
+
+    /**
+     * Sorts attributes by name.
+     * 
+     * @param attrs the unsorted list of attributes
+     * @return the sorted list of attributes
+     */
+    @SuppressWarnings("null")
+    protected Attr[] sortAttributes(NamedNodeMap attrs)
+    {
+
+        int len = (attrs != null) ? attrs.getLength() : 0;
+        Attr array[] = new Attr[len];
+        for (int i = 0; i < len; i++)
+        {
+            array[i] = (Attr) attrs.item(i);
+        }
+        for (int i = 0; i < len - 1; i++)
+        {
+            String name = array[i].getNodeName();
+            int index = i;
+            for (int j = i + 1; j < len; j++)
+            {
+                String curName = array[j].getNodeName();
+                if (curName.compareTo(name) < 0)
+                {
+                    name = curName;
+                    index = j;
+                }
+            }
+            if (index != i)
+            {
+                Attr temp = array[i];
+                array[i] = array[index];
+                array[index] = temp;
+            }
+        }
+
+        return (array);
+
+    } // sortAttributes(NamedNodeMap):Attr[]
+
+    /**
+     * Converts a string to valid XML-Syntax replacing XML entities.
+     * 
+     * @param s the string to normalize
+     */
+    protected String normalize(String s)
+    {
+        return normalize(s, canonical);
+    }
+
+    @SuppressWarnings({ "fallthrough", "null" })
+    static public String normalize(String s, boolean canonical)
+    {
+        StringBuilder str = new StringBuilder();
+
+        int len = (s != null) ? s.length() : 0;
+        for (int i = 0; i < len; i++)
+        {
+            char ch = s.charAt(i);
+            switch (ch)
+            {
+                case '<':
+                {
+                    str.append("&lt;");
+                    break;
+                }
+                case '>':
+                {
+                    str.append("&gt;");
+                    break;
+                }
+                case '&':
+                {
+                    str.append("&amp;");
+                    break;
+                }
+                case '"':
+                {
+                    str.append("&quot;");
+                    break;
+                }
+                case '\r':
+                case '\n':
+                {
+                    if (canonical)
+                    {
+                        str.append("&#");
+                        str.append(Integer.toString(ch));
+                        str.append(';');
+                        break;
+                    }
+                    // else, default append char
+                }
+                default:
+                {
+                    str.append(ch);
+                }
+            }
+        }
+
+        return (str.toString());
+
+    } // normalize(String):String
+
+}
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/package.html
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/package.html?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/package.html (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/xml/package.html Wed Aug  6 01:47:37 2008
@@ -0,0 +1,14 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+<!--
+/*
+ * ESTEAM Software GmbH, 12.12.2007
+ */
+-->
+</head>
+<body>
+
+This package contains classes for XML generation and configuration.
+
+</body></html>
\ No newline at end of file