de.fhg.iais.cortex.model.aip.util.XmlUtils.java Source code

Java tutorial

Introduction

Here is the source code for de.fhg.iais.cortex.model.aip.util.XmlUtils.java

Source

package de.fhg.iais.cortex.model.aip.util;

/******************************************************************************
 * Copyright 2011 (c) Fraunhofer IAIS Netmedia  http://www.iais.fraunhofer.de *
 * ************************************************************************** *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License.                   *
 * You may obtain a copy of the License at                                    *
 * http://www.apache.org/licenses/LICENSE-2.0                                 *
 * Unless required by applicable law or agreed to in writing,                 *
 * software distributed under the License is distributed on an "AS IS" BASIS, *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 ******************************************************************************/

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;

import de.fhg.iais.commons.Cast;
import de.fhg.iais.commons.dbc.DbcException;
import de.fhg.iais.commons.exception.DomElementException;

public final class XmlUtils {

    private XmlUtils() {
        // construction not allowed
    }

    //    public static Unmarshaller createUnmarshaller(String jaxbcontext) {
    //
    //        JAXBContext context = null;
    //        Unmarshaller unmarshaller = null;
    //        try {
    //            context = JAXBContext.newInstance(jaxbcontext);
    //        } catch ( JAXBException e ) {
    //            throw new DbcException(e);
    //        }
    //        try {
    //            unmarshaller = context.createUnmarshaller();
    //        } catch ( JAXBException e ) {
    //            throw new DbcException(e);
    //        }
    //        return unmarshaller;
    //    }

    //    public synchronized static Object unmarshalToObject(Unmarshaller unmarshaller, String xml) {
    //
    //        StringReader sr = null;
    //        try {
    //            sr = new StringReader(xml);
    //            Object res = unmarshaller.unmarshal(sr);
    //
    //            return getObjectFromJAXBElement(res);
    //        } catch ( JAXBException e ) {
    //            throw new DbcException(e);
    //        } finally {
    //            if ( sr != null ) {
    //                sr.close();
    //            }
    //        }
    //    }

    //    public synchronized static Object unmarshalToObject(UnmarshallerHandler unmarshalHandler, XMLFilter filter, String xml) {
    //
    //        StringReader sr = null;
    //        try {
    //            sr = new StringReader(xml);
    //            filter.parse(new InputSource(sr));
    //
    //            Object res = unmarshalHandler.getResult();
    //
    //            return getObjectFromJAXBElement(res);
    //        } catch ( JAXBException e ) {
    //            throw new DbcException(e);
    //        } catch ( IOException e ) {
    //            throw new DbcException(e);
    //        } catch ( SAXException e ) {
    //            throw new DbcException(e);
    //        } finally {
    //            if ( sr != null ) {
    //                sr.close();
    //            }
    //        }
    //    }

    //    public static Marshaller createMarshaller(String jaxbcontext) {
    //
    //        JAXBContext jaxbContext = null;
    //        Marshaller m = null;
    //        try {
    //            jaxbContext = JAXBContext.newInstance(jaxbcontext);
    //        } catch ( JAXBException e ) {
    //            throw new DbcException(e);
    //        }
    //        try {
    //            m = jaxbContext.createMarshaller();
    //            m.setProperty("jaxb.formatted.output", true);
    //        } catch ( JAXBException e ) {
    //            throw new DbcException(e);
    //        }
    //
    //        return m;
    //
    //    }

    //    public synchronized static String marshallToString(Object object, Marshaller marshaller) {
    //
    //        StringWriter stringWriter = new StringWriter();
    //
    //        try {
    //            marshaller.marshal(object, stringWriter);
    //        } catch ( JAXBException e ) {
    //            throw new DbcException(e);
    //        }
    //
    //        return stringWriter.toString();
    //
    //    }

    //    private static Object getObjectFromJAXBElement(Object object) {
    //
    //        JAXBElement<?> jaxb = null;
    //        if ( object instanceof JAXBElement<?> ) {
    //            jaxb = (JAXBElement<?>) object;
    //        } else {
    //            return object;
    //        }
    //
    //        Object actualObject = jaxb.getValue();
    //        return actualObject;
    //
    //    }
    //
    //    public static Document buildDocumentFrom(InputSource source) {
    //        try {
    //            return new SAXBuilder().build(source);
    //        } catch ( JDOMException e ) {
    //            throw new DbcException(e);
    //        } catch ( IOException e ) {
    //            throw new DbcException(e);
    //        }
    //    }

    //    public static String xmlDocToString(Document doc) {
    //        return contentToString(false, doc.getRootElement());
    //    }
    //
    //    public static Document parse(String xml) {
    //        return readAndParse(new StringReader(xml));
    //    }
    //
    //    private static Document readAndParse(Reader reader) {
    //        final SAXBuilder parser = new SAXBuilder();
    //        try {
    //            return parser.build(reader);
    //        } catch ( JDOMException e ) {
    //            throw new DbcException(e);
    //        } catch ( IOException e ) {
    //            throw new DbcException(e);
    //        } finally {
    //            IOUtils.closeQuietly(reader);
    //        }
    //    }

    //    public static Document buildDocumentFrom(String xml) {
    //        SAXBuilder sxbuild = new SAXBuilder();
    //        StringReader reader = null;
    //        Document result = null;
    //        try {
    //            reader = new StringReader(xml);
    //            result = sxbuild.build(new InputSource(reader));
    //        } catch ( JDOMException e ) {
    //            throw new DbcException(e);
    //        } catch ( IOException e ) {
    //            throw new DbcException(e);
    //        } finally {
    //            IOUtils.closeQuietly(reader);
    //        }
    //
    //        return result;
    //    }

    //    public static String contentToString(boolean copyNamespace, Content content) {
    //        if ( content instanceof Element ) {
    //            return elementToString(copyNamespace, (Element) content);
    //        }
    //        if ( content instanceof Text ) {
    //            return ((Text) content).getText();
    //        }
    //        if ( content instanceof Comment ) {
    //            Logger logger = LoggerFactory.getLogger("XMLUtils");
    //            logger.warn("encountered Comment in contentToString, ignoring it");
    //            return "";
    //        }
    //        throw new DbcException("Cannot parse the content");
    //    }

    public static String elementToString(boolean copyNamespace, Element element) {
        StringWriter sw = new StringWriter();
        Format format = Format.getPrettyFormat();
        format.setOmitDeclaration(true);
        XMLOutputter outputter = new XMLOutputter(format);
        try {
            if (copyNamespace) {
                Document neudoc = new Document(((Element) element.clone()));
                outputter.output(neudoc, sw);
            } else {
                outputter.output(element, sw);
            }
        } catch (IOException e) {
            throw new DbcException("XML-Outputter failed. ", e);
        }

        return sw.toString().trim();
    }

    /**
     * @return concatenation of element content as string
     */
    //    public static String elementContentToString(boolean copyNamespace, final Element element) {
    //        StringBuilder contentString = new StringBuilder(element.getContentSize() * 20); // pre-set
    //        for ( Content content : Cast.contentList(element.getContent()) ) {
    //            final String contentAsString = XmlUtils.contentToString(copyNamespace, content);
    //            if ( contentAsString != null ) {
    //                contentString.append(contentAsString.trim());
    //            }
    //        }
    //
    //        return contentString.toString();
    //    }

    /**
     * Setzt element als Kind von parent. Entfernt andere gegenenfalls existierende children.
     * 
     * @param parent
     * @param child
     */
    public static void setChild(final Element parent, final Element child) {
        if (parent == null || child == null) {
            return;
        }
        child.detach();
        parent.setContent(child);
    }

    public static void addChild(final Element parent, final Element child) {
        if (parent == null || child == null) {
            return;
        }
        child.detach();
        parent.addContent(child);
    }

    public static List<Element> list(Element root, boolean create, String... path) {
        Element parent = element(root, create, path);
        if (parent != null) {
            List<Element> children = Cast.elementList(parent.getChildren());
            return children;
        }
        return Collections.emptyList();
    }

    public static final Joiner JOINER = Joiner.on("/");
    public static final Splitter SPLITTER = Splitter.on("/").omitEmptyStrings();

    public static Element element(Element root, boolean create, String... path) {
        Element e = root;
        Element parent = null;
        if (path != null) {
            String joinedPaths = JOINER.join(path);
            String[] pathElements = Iterables.toArray(SPLITTER.split(joinedPaths), String.class);
            if (pathElements.length > 0) {
                if (!root.getName().equals(pathElements[0])) {
                    throw new DomElementException(
                            "Expected root '" + pathElements[0] + "', found '" + root.getName() + "'!");
                }
                for (int i = 1; i < pathElements.length; i++) {
                    parent = e;
                    e = e.getChild(pathElements[i]);
                    if (e == null) {
                        e = retryWithNamespace(parent, pathElements[i],
                                Namespace.getNamespace("http://www.deutsche-digitale-bibliothek.de/cortex"));
                        if (e == null) {
                            e = retryWithNamespace(parent, pathElements[i], Namespace
                                    .getNamespace("http://www.deutsche-digitale-bibliothek.de/institution"));
                        }
                        if (e == null) {
                            e = retryWithNamespace(parent, pathElements[i],
                                    Namespace.getNamespace("http://www.deutsche-digitale-bibliothek.de/item"));
                        }
                        if (e == null) {
                            if (create) {
                                e = new Element(pathElements[i]);
                                XmlUtils.addChild(parent, e);
                            } else {
                                return null;
                            }
                        }
                    }
                }
            } else {
                return null;
            }
        }
        return e;
    }

    private static Element retryWithNamespace(Element parent, String pathElement, Namespace xmlns) {
        return parent.getChild(pathElement, xmlns);
    }

    public static String text(Element root, String... path) {
        Element e = element(root, false, path);
        return e == null ? "" : e.getTextTrim();
    }

    public static String xml(Element root, String... path) {
        Element element;
        if (path == null) {
            element = root;
        } else {
            String joinedPaths = JOINER.join(path);
            String[] pe = Iterables.toArray(SPLITTER.split(joinedPaths), String.class);
            if (pe.length == 0) {
                element = root;
            } else {
                element = element(root, false, path);
                if (element == null) {
                    element = new Element(pe[pe.length - 1]);
                }
            }
        }
        StringWriter sw = new StringWriter();
        try {
            new XMLOutputter(Format.getPrettyFormat()).output(element, sw);
        } catch (IOException e) {
            throw new DbcException("Unable to output content xml, path: " + JOINER.join("/", path), e);
        }

        return sw.toString().trim();
    }

    //    @OnlyCalledFromTests
    //    public static boolean contains(Element root, String... path) {
    //        return element(root, false, path) != null;
    //    }

    /**
     * Transform a map to a single xml string surrounded with < > and </ >. (Formerly known as
     * SimpleTagger.getXml())
     * 
     * @param map
     * @return the given map as xmp string
     */
    //    public static String map2xml(final Map<String, String> map) {
    //        StringBuilder xml = new StringBuilder(40 + map.size() * 80); // pre-set
    //        for ( Entry<String, String> entry : map.entrySet() ) {
    //            xml.append("<").append(entry.getKey()).append(">");
    //            xml.append(entry.getValue());
    //            xml.append("<").append("/" + entry.getKey()).append(">");
    //        }
    //
    //        return xml.toString();
    //    }
}