changeset 102:4122dbc9711b

Added a new package artifacts-common for classes and utilities used in several packages. artifacts/trunk@1285 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Ingo Weinzierl <ingo.weinzierl@intevation.de>
date Wed, 02 Feb 2011 14:37:28 +0000
parents 7fc0650f194c
children 1282cf96d3eb
files ChangeLog artifacts-common/pom.xml artifacts-common/src/main/java/de/intevation/artifacts/common/utils/XMLUtils.java pom.xml
diffstat 4 files changed, 353 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/ChangeLog	Tue Feb 01 16:15:03 2011 +0000
+++ b/ChangeLog	Wed Feb 02 14:37:28 2011 +0000
@@ -1,3 +1,13 @@
+2011-02-02  Ingo Weinzierl <ingo@intevation.de>
+
+	* artifacts-common/src/main/java/de/intevation/artifacts/common/utils/XMLUtils.java,
+	  artifacts-common/pom.xml: New package. It will serve some classes and
+	  utilities that are used in the artifact-database package as well as in
+	  concrete artifact packages.
+
+	* pom.xml: Added the artifacts-common package to be able to build all
+	  packages using just the upper level pom file.
+
 2011-02-01  Ingo Weinzierl <ingo@intevation.de>
 
 	* artifact-database/pom.xml: Upgraded Restlet from version 2.0-SNAPSHOT
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/artifacts-common/pom.xml	Wed Feb 02 14:37:28 2011 +0000
@@ -0,0 +1,30 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>de.intevation.artifacts.common</groupId>
+  <artifactId>artifacts-common</artifactId>
+  <version>1.0-SNAPSHOT</version>
+  <packaging>jar</packaging>
+
+  <name>artifacts-common</name>
+  <url>http://maven.apache.org</url>
+
+  <properties>
+    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+  </properties>
+
+  <dependencies>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <version>3.8.1</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>log4j</groupId>
+      <artifactId>log4j</artifactId>
+      <version>1.2.14</version>
+    </dependency>
+  </dependencies>
+</project>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/artifacts-common/src/main/java/de/intevation/artifacts/common/utils/XMLUtils.java	Wed Feb 02 14:37:28 2011 +0000
@@ -0,0 +1,311 @@
+/*
+ * Copyright (c) 2010 by Intevation GmbH
+ *
+ * This program is free software under the LGPL (>=v2.1)
+ * Read the file LGPL.txt coming with the software for details
+ * or visit http://www.gnu.org/licenses/ if it does not exist.
+ */
+
+package de.intevation.artifactdatabase;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+
+import javax.xml.transform.dom.DOMSource;
+
+import javax.xml.transform.stream.StreamResult;
+
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+
+import org.apache.log4j.Logger;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import org.xml.sax.SAXException;
+
+/**
+ * Some helper functions to ease work with XML concering namespaces, XPATH
+ * and so on.
+ *  @author <a href="mailto:sascha.teichmann@intevation.de">Sascha L. Teichmann</a>
+ */
+public final class XMLUtils
+{
+    /**
+     * W3C URL of XForms
+     */
+    public static final String XFORM_URL    = "http://www.w3.org/2002/xforms";
+    /**
+     * W3C prefix of XForms
+     */
+    public static final String XFORM_PREFIX = "xform";
+
+    private static Logger logger = Logger.getLogger(XMLUtils.class);
+
+    private XMLUtils() {
+    }
+
+    /**
+     * Helper class to generate elements and attributes with
+     * namespaces.
+     */
+    public static class ElementCreator
+    {
+        /**
+         * owner document of the elements to be created
+         */
+        protected Document document;
+        /**
+         * namespace to be used
+         */
+        protected String   ns;
+        /**
+         * prefix to be used
+         */
+        protected String   prefix;
+
+        /**
+         * Constructor to create an element/attribute creator
+         * with a given namespace and namespace prefix using a
+         * given owner document.
+         * @param document The owning document
+         * @param ns       The namespace
+         * @param prefix   The namespace prefix
+         */
+        public ElementCreator(Document document, String ns, String prefix) {
+            this.document = document;
+            this.ns       = ns;
+            this.prefix   = prefix;
+        }
+
+        /**
+         * Creates a new element using the owning document with
+         * the this creators namespace and namespace prefix.
+         * @param name The name of the element
+         * @return     The new element
+         */
+        public Element create(String name) {
+            Element element = document.createElementNS(ns, name);
+            element.setPrefix(prefix);
+            return element;
+        }
+
+        /**
+         * Adds a new attribute and its value to a given element.
+         * It does not set the namespace prefix.
+         * @param element The element to add the attribute to
+         * @param name    The name of the attribute
+         * @param value   The value of the attribute
+         */
+        public void addAttr(Element element, String name, String value) {
+            addAttr(element, name, value, false);
+        }
+
+        /**
+         * Adds a new attribute and its value to a given element.
+         * If the namespace prefix is used is decided by the 'addPrefix' flag.
+         * @param element The element to add the attribute to
+         * @param name    The name of the attribute
+         * @param value   The value of the attribute
+         * @param addPrefix If true the creators namespace prefix is
+         * set on the attribute.
+         */
+        public void addAttr(
+            Element element,
+            String  name,
+            String  value,
+            boolean addPrefix
+        ) {
+            Attr attr = document.createAttributeNS(ns, name);
+            attr.setValue(value);
+
+            if (addPrefix)
+                attr.setPrefix(prefix);
+
+            element.setAttributeNode(attr);
+        }
+    } // class ElementCreator
+
+    /**
+     * Creates a new XML document
+     * @return the new XML document ot null if something went wrong during
+     * creation.
+     */
+    public static final Document newDocument() {
+        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+        factory.setNamespaceAware(true);
+
+        try {
+            return factory.newDocumentBuilder().newDocument();
+        }
+        catch (ParserConfigurationException pce) {
+            logger.error(pce.getLocalizedMessage(), pce);
+        }
+        return null;
+    }
+
+    /**
+     * Loads a XML document namespace aware from a file
+     * @param file The file to load.
+     * @return the XML document or null if something went wrong
+     * during loading.
+     */
+    public static final Document parseDocument(File file) {
+        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+        factory.setNamespaceAware(true);
+
+        try {
+            return factory.newDocumentBuilder().parse(file);
+        }
+        catch (ParserConfigurationException pce) {
+            logger.error(pce.getLocalizedMessage(), pce);
+        }
+        catch (SAXException se) {
+            logger.error(se.getLocalizedMessage(), se);
+        }
+        catch (IOException ioe) {
+            logger.error(ioe.getLocalizedMessage(), ioe);
+        }
+        return null;
+    }
+
+    /**
+     * Creates a new XPath without a namespace context.
+     * @return the new XPath.
+     */
+    public static final XPath newXPath() {
+        return newXPath(null);
+    }
+
+    /**
+     * Creates a new XPath with a given namespace context.
+     * @param namespaceContext The namespace context to be used or null
+     * if none should be used.
+     * @return The new XPath
+     */
+    public static final XPath newXPath(NamespaceContext namespaceContext) {
+        XPathFactory factory = XPathFactory.newInstance();
+        XPath        xpath   = factory.newXPath();
+        if (namespaceContext != null) {
+            xpath.setNamespaceContext(namespaceContext);
+        }
+        return xpath;
+    }
+
+    /**
+     * Evaluates an XPath query on a given object and returns the result
+     * as a given type. No namespace context is used.
+     * @param root  The object which is used as the root of the tree to
+     * be searched in.
+     * @param query The XPath query
+     * @param returnTyp The type of the result.
+     * @return The result of type 'returnTyp' or null if something
+     * went wrong during XPath evaluation.
+     */
+    public static final Object xpath(
+        Object root,
+        String query,
+        QName  returnTyp
+    ) {
+        return xpath(root, query, returnTyp, null);
+    }
+
+    /**
+     * Evaluates an XPath query on a given object and returns the result
+     * as a string. A given namespace context is used.
+     * @param root  The object which is used as the root of the tree to
+     * be searched in.
+     * @param query The XPath query
+     * @param namespaceContext The namespace context to be used or null
+     * if none should be used.
+     * @return The result of the query or null if something went wrong
+     * during XPath evaluation.
+     */
+    public static final String xpathString(
+        Object root, String query, NamespaceContext namespaceContext
+    ) {
+        return (String)xpath(
+            root, query, XPathConstants.STRING, namespaceContext);
+    }
+
+    /**
+     * Evaluates an XPath query on a given object and returns the result
+     * as a given type. Optionally a namespace context is used.
+     * @param root The object which is used as the root of the tree to
+     * be searched in.
+     * @param query The XPath query
+     * @param returnType The type of the result.
+     * @param namespaceContext The namespace context to be used or null
+     * if none should be used.
+     * @return The result of type 'returnTyp' or null if something
+     * went wrong during XPath evaluation.
+     */
+    public static final Object xpath(
+        Object           root,
+        String           query,
+        QName            returnType,
+        NamespaceContext namespaceContext
+    ) {
+        if (root == null) {
+            return null;
+        }
+
+        try {
+            XPath xpath = newXPath(namespaceContext);
+            if (xpath != null) {
+                return xpath.evaluate(query, root, returnType);
+            }
+        }
+        catch (XPathExpressionException xpee) {
+            logger.error(xpee.getLocalizedMessage(), xpee);
+        }
+
+        return null;
+    }
+
+    /**
+     * Streams out an XML document to a given output stream.
+     * @param document The document to be streamed out.
+     * @param out      The output stream to be used.
+     * @return true if operation succeeded else false.
+     */
+    public static boolean toStream(Document document, OutputStream out) {
+        try {
+            Transformer transformer =
+                TransformerFactory.newInstance().newTransformer();
+            DOMSource    source = new DOMSource(document);
+            StreamResult result = new StreamResult(out);
+            transformer.transform(source, result);
+            return true;
+        }
+        catch (TransformerConfigurationException tce) {
+            logger.error(tce.getLocalizedMessage(), tce);
+        }
+        catch (TransformerFactoryConfigurationError tfce) {
+            logger.error(tfce.getLocalizedMessage(), tfce);
+        }
+        catch (TransformerException te) {
+            logger.error(te.getLocalizedMessage(), te);
+        }
+
+        return false;
+    }
+}
+// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/pom.xml	Tue Feb 01 16:15:03 2011 +0000
+++ b/pom.xml	Wed Feb 02 14:37:28 2011 +0000
@@ -73,5 +73,6 @@
   <modules>
     <module>artifacts</module>
     <module>artifact-database</module>
+    <module>artifacts-common</module>
   </modules>
-</project>
+</project>
\ No newline at end of file

http://dive4elements.wald.intevation.org