2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.config.util.xml;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertTrue;
13 import static org.junit.Assert.fail;
15 import com.google.common.base.Optional;
16 import java.io.ByteArrayInputStream;
17 import org.custommonkey.xmlunit.Diff;
18 import org.custommonkey.xmlunit.XMLUnit;
19 import org.junit.Test;
20 import org.w3c.dom.Document;
21 import org.w3c.dom.Element;
22 import org.xml.sax.SAXParseException;
24 public class XmlUtilTest {
26 private final String xml = "<top xmlns=\"namespace\">\n" +
27 "<innerText>value</innerText>\n" +
28 "<innerPrefixedText xmlns:pref=\"prefixNamespace\">prefix:value</innerPrefixedText>\n" +
29 "<innerPrefixedText xmlns=\"randomNamespace\" xmlns:pref=\"prefixNamespace\">prefix:value</innerPrefixedText>\n" +
33 public void testCreateElement() throws Exception {
34 final Document document = XmlUtil.newDocument();
35 final Element top = XmlUtil.createElement(document, "top", Optional.of("namespace"));
37 top.appendChild(XmlUtil.createTextElement(document, "innerText", "value", Optional.of("namespace")));
38 top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref", "prefixNamespace", "value", Optional.of("namespace")));
39 top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref", "prefixNamespace", "value", Optional.of("randomNamespace")));
41 document.appendChild(top);
42 assertEquals("top", XmlUtil.createDocumentCopy(document).getDocumentElement().getTagName());
44 XMLUnit.setIgnoreAttributeOrder(true);
45 XMLUnit.setIgnoreWhitespace(true);
47 final Diff diff = XMLUnit.compareXML(XMLUnit.buildControlDocument(xml), document);
48 assertTrue(diff.toString(), diff.similar());
52 public void testLoadSchema() throws Exception {
55 XmlUtil.loadSchema(new ByteArrayInputStream(xml.getBytes()));
56 fail("Input stream does not contain xsd");
57 } catch (final IllegalStateException e) {
58 assertTrue(e.getCause() instanceof SAXParseException);
63 @Test(expected = SAXParseException.class)
64 public void testXXEFlaw() throws Exception {
65 XmlUtil.readXmlToDocument("<!DOCTYPE foo [ \n" +
66 "<!ELEMENT foo ANY >\n" +
67 "<!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]>\n" +
68 "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
70 " <capability>urn:ietf:params:netconf:base:1.0 &xxe;</capability>\n" +
71 " </capabilities>\n" +