de.fhg.iais.model.aip.util.XmlUtilsTest.java Source code

Java tutorial

Introduction

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

Source

package de.fhg.iais.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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.apache.commons.fileupload.util.Streams;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.transform.JDOMSource;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xml.sax.SAXException;

import de.fhg.iais.commons.dbc.DbcException;
import de.fhg.iais.commons.exception.DomElementException;
import de.fhg.iais.cortex.model.aip.util.XmlProcessor;
import de.fhg.iais.cortex.model.aip.util.XmlUtils;

public class XmlUtilsTest {

    private static final String ADVICES = "<cortex-item-label><div>Bad Homburg v.d.H., Louisenstrasse 84a/84b</div></cortex-item-label>";

    private Element parentElement;

    private Element aipRoot;

    @BeforeClass
    public static void startUp() {
        XMLUnit.setIgnoreWhitespace(true);
    }

    @Before
    public void setup() throws IOException {
        this.parentElement = new Element("parent");
        this.parentElement.addContent(new Element("child1"));
        final String aip = Streams.asString(getClass().getResourceAsStream("/aip-test.xml"));
        this.aipRoot = XmlProcessor.buildDocumentFrom(aip).getRootElement();
    }

    @Test
    public void testSetChild() {
        XmlUtils.setChild(this.parentElement, new Element("test"));

        assertEquals(1, this.parentElement.getChildren().size());
        assertTrue(this.parentElement.getChildren().get(0) instanceof Element);
        assertEquals("test", ((Element) this.parentElement.getChildren().get(0)).getName());
    }

    @Test
    public void testAddChild() {
        XmlUtils.addChild(this.parentElement, new Element("test"));

        assertEquals(2, this.parentElement.getChildren().size());
        assertTrue(this.parentElement.getChildren().get(0) instanceof Element);
        assertEquals("child1", ((Element) this.parentElement.getChildren().get(0)).getName());
        assertTrue(this.parentElement.getChildren().get(1) instanceof Element);
        assertEquals("test", ((Element) this.parentElement.getChildren().get(1)).getName());
    }

    @Test
    public void testValidator() throws IOException {
        final String exampleXml = Streams.asString(getClass().getResourceAsStream("/xml/anAddress.xml"));
        final URL xsd = getClass().getResource("/xml/address.xsd");

        parseAndValidate(exampleXml, xsd);
    }

    @Test
    public void testValidatorIfSchemaIsMissing() throws IOException {
        final String exampleXml = Streams
                .asString(getClass().getResourceAsStream("/xml/anAddressWithoutSchemaInfo.xml"));
        final URL xsd = getClass().getResource("/xml/address.xsd");

        parseAndValidate(exampleXml, xsd);
    }

    @Test
    public void testElement() {
        final Element e = XmlUtils.element(this.aipRoot, false, "/cortex/cortex-ingest-id");

        assertNotNull("node not found", e);
    }

    @Test
    public void testList() {
        final List<Element> l = XmlUtils.list(this.aipRoot, false, "cortex");

        assertNotNull("node not found", l);
        assertEquals(9, l.size());
    }

    @Test(expected = DomElementException.class)
    public void testElementcreateNonExisting() {
        XmlUtils.element(this.aipRoot, false, "subcortex", "cortex-ingest-id");
    }

    @Test
    public void testElementcreateNonExisting2() {
        final Element e = XmlUtils.element(this.aipRoot, true, "cortex", "cortex-ingest-id-NEW");

        assertNotNull("node not found", e);
    }

    @Test
    public void testElementcreateNonExisting3() {
        final Element e = XmlUtils.element(this.aipRoot, true, "/cortex/cortex-ingest-id", "newnode");

        assertNotNull("node not found", e);
    }

    @Test
    public void testContent() {
        final String content = XmlUtils.text(this.aipRoot, "cortex/cortex-ingest-id");

        assertEquals("2000000100", content);
        assertNotNull("content not found", content);
        assertTrue("content not found", content.length() > 0);
    }

    @Test
    public void testAttributes() {
        final String att = attribute("data-media", this.aipRoot, "cortex/cortex-content/cortex-item-preview",
                "div");

        assertEquals("image,text", att);
        assertNotNull("attribute not found", att);
        assertTrue("content not found", att.length() > 0);
    }

    private String attribute(String attributeName, Element root, String... path) {
        final Element element = XmlUtils.element(root, false, path);
        if (element == null) {
            return "";
        }
        final Attribute attribute = element.getAttribute(attributeName);
        if (attribute == null) {
            return "";
        }
        return attribute.getValue();
    }

    @Test
    public void testXml() throws SAXException, IOException {

        final String b = XmlUtils.xml(this.aipRoot, "cortex", "cortex-content", "cortex-item-label");
        XMLUnit.setIgnoreWhitespace(true);
        Diff diff = XMLUnit.compareXML(b, ADVICES);
        assertTrue(diff.toString(), diff.similar());
        assertNotNull("content not found", b);
        assertTrue("content not found", b.length() > 0);
    }

    //    @Test
    //    public void testContains() {
    //        final boolean t = XmlUtils.contains(this.aipRoot, "cortex/cortex-content");
    //        final boolean f = XmlUtils.contains(this.aipRoot, "cortex/advicesNONONO");
    //
    //        assertTrue("node missing", t);
    //        assertFalse("node should be missing", f);
    //    }
    //
    //    @Test
    //    public void testContentToString() throws SAXException, IOException {
    //        final Element adv = XmlUtils.element(this.aipRoot, false, "cortex/cortex-content/cortex-item-label");
    //        final String result = XmlUtils.contentToString(true, adv);
    //
    //        Diff diff = XMLUnit.compareXML(ADVICES, result);
    //        assertTrue(diff.toString(), diff.similar());
    //    }
    //
    //    @Test
    //    public void testElementContentToString() throws SAXException, IOException {
    //        final Element adv = XmlUtils.element(this.aipRoot, false, "cortex/cortex-content/cortex-item-label");
    //        final String result = "<cortex-item-label>" + XmlUtils.elementContentToString(true, adv) + "</cortex-item-label>";
    //
    //        Diff diff = XMLUnit.compareXML(ADVICES, result);
    //        assertTrue(diff.toString(), diff.similar());
    //    }
    //
    //    @Test
    //    public void testXmlDocToString() throws SAXException, IOException {
    //        final Element adv = XmlUtils.element(this.aipRoot, false, "cortex/cortex-content/cortex-item-label");
    //        final String result = XmlUtils.contentToString(true, adv);
    //
    //        Diff diff = XMLUnit.compareXML(ADVICES, result);
    //        assertTrue(diff.toString(), diff.similar());
    //    }
    //
    //    @Test
    //    public final void testMap2xml() {
    //        final Map<String, String> map = new Hashtable<String, String>();
    //        map.put("creator", "a");
    //        map.put("title", "t");
    //        final String xml = XmlUtils.map2xml(map);
    //        final String expected = "<creator>a</creator><title>t</title>";
    //
    //        assertEquals(expected, xml);
    //    }

    private static Document parseAndValidate(String xml, URL xsd) {
        final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema;
        try {
            schema = factory.newSchema(xsd);
        } catch (final SAXException e) {
            throw new DbcException(e);
        }

        //        final Document xmlDocument = XmlUtils.parse(xml);
        final Document xmlDocument = XmlProcessor.buildDocumentFrom(xml);
        final Validator validator = schema.newValidator();
        try {
            validator.validate(new JDOMSource(xmlDocument));
            return xmlDocument;
        } catch (final SAXException e) {
            throw new DbcException(e);
        } catch (final IOException e) {
            throw new DbcException(e);
        }
    }

}