view gnv/src/main/java/de/intevation/gnv/util/XMLUtils.java @ 389:416ff31f6273

Removed local-name() method from xsl stylesheet and adjusted xpathes while reading xml documents. gnv/trunk@511 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Ingo Weinzierl <ingo.weinzierl@intevation.de>
date Wed, 06 Jan 2010 09:13:45 +0000
parents fccf90761825
children cbd397712ecf
line wrap: on
line source
package de.intevation.gnv.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.io.StringWriter;

import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
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.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * @author Sascha L. Teichmann
 */
public class XMLUtils {
    private static Logger logger = Logger.getLogger(XMLUtils.class);

    public XMLUtils() {
    }

    public static class ElementCreator {
        protected Document document;
        protected String ns;
        protected String prefix;

        public ElementCreator(Document document, String ns, String prefix) {
            this.document = document;
            this.ns = ns;
            this.prefix = prefix;
        }

        public Element create(String name) {
            Element element = document.createElementNS(ns, name);
            element.setPrefix(prefix);
            return element;
        }

        public void addAttr(Element element, String name, String value) {
            Attr attr = document.createAttributeNS(ns, name);
            attr.setValue(value);
            attr.setPrefix(prefix);
            element.setAttributeNode(attr);
        }
    } // class ElementCreator

    public Document newDocument() {
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .newDocument();
        } catch (ParserConfigurationException pce) {
            logger.error(pce.getLocalizedMessage(), pce);
        }
        return null;
    }

    public XPath newXPath() {
        return newXPath(null);
    }

    public XPath newXPath(NamespaceContext namespaceContext) {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        if (namespaceContext != null) {
            xpath.setNamespaceContext(namespaceContext);
        }
        return xpath;
    }

    public Object xpath(Object root, String query, QName returnTyp) {
        return xpath(root, query, returnTyp, null);
    }

    public final String xpathString(Object root, String query,
                                    NamespaceContext namespaceContext) {
        return (String) xpath(root, query, XPathConstants.STRING,
                namespaceContext);
    }

    public static final Object xpath(Object root, String query,
                                     QName returnType,
                                     NamespaceContext namespaceContext) {
        if (root == null) {
            return null;
        }

        try {
            XPath xpath = new XMLUtils().newXPath(namespaceContext);
            if (xpath != null) {
                return xpath.evaluate(query, root, returnType);
            }
        } catch (XPathExpressionException xpee) {
            logger.error(xpee.getLocalizedMessage(), xpee);
        }

        return null;
    }

    public Object getXPath(Object root, String query, QName returnType) {
        return getXPath(root,query,returnType,ArtifactNamespaceContext.INSTANCE);
    }

    public Object getXPath(
        Object root, String query, QName returnType, NamespaceContext context
    ) {
        return xpath(root, query, returnType, context);
    }

    public String getStringXPath(String xpath) {
        return getStringXPath(xpath, null);
    }

    public NodeList getNodeSetXPath(Object root, String query) {
        return (NodeList) getXPath(root, query, XPathConstants.NODESET);
    }

    public Node getNodeXPath(Object root, String query) {
        return (Node) getXPath(root, query, XPathConstants.NODE);
    }

    public String getStringXPath(Object root, String xpath) {
        return getStringXPath(root, xpath, null);
    }

    public String getStringXPath(Object root, String query, String def) {
        String s = (String) getXPath(root, query, XPathConstants.STRING);
        return s == null || s.length() == 0 ? def : s;
    }

    public Document readDocument(InputStream inputStream) {
        Document returnValue = null;
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
                    .newInstance();
            docBuilderFactory.setNamespaceAware(true);
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            returnValue = docBuilder.parse(inputStream);
        } catch (ParserConfigurationException e) {
            logger.error(e, e);
        } catch (SAXException e) {
            logger.error(e, e);
        } catch (IOException e) {
            logger.error(e, e);
        }
        return returnValue;
    }

    public String writeNode2String(Node node) {
        try {
            DOMSource source = new DOMSource(node);
            return writeDOMSource2String(source);
        } catch (TransformerConfigurationException e) {
            logger.error(e, e);
        } catch (TransformerFactoryConfigurationError e) {
            logger.error(e, e);
        } catch (TransformerException e) {
            logger.error(e, e);
        }
        return null;
    }

    public Document reInitDocument(Document document) {

        StringBufferInputStream inputStream = new StringBufferInputStream(this
                .writeDocument2String(document));
        return this.readDocument(inputStream);
    }

    public String writeDocument2String(Document document) {
        try {
            DOMSource source = new DOMSource(document);
            return writeDOMSource2String(source);
        } catch (TransformerConfigurationException e) {
            logger.error(e, e);
        } catch (TransformerFactoryConfigurationError e) {
            logger.error(e, e);
        } catch (TransformerException e) {
            logger.error(e, e);
        }
        return null;
    }

    /**
     * @param source
     * @return
     * @throws TransformerFactoryConfigurationError
     * @throws TransformerConfigurationException
     * @throws TransformerException
     */
    private String writeDOMSource2String(DOMSource source)
                                                          throws TransformerFactoryConfigurationError,
                                                          TransformerConfigurationException,
                                                          TransformerException {
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        transformer.transform(source, result);
        return sw.getBuffer().toString();
    }
}
// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:

http://dive4elements.wald.intevation.org