2 * Copyright (c) 2013 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
8 package org.opendaylight.yangtools.yang.data.impl.schema;
10 import com.google.common.base.Function;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Collections2;
13 import com.google.common.collect.Lists;
14 import com.google.common.collect.Sets;
15 import org.junit.Before;
16 import org.junit.Test;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.schema.*;
20 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
21 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableChoiceNodeSchemaAwareBuilder;
22 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeSchemaAwareBuilder;
23 import org.opendaylight.yangtools.yang.model.api.*;
24 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
25 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
26 import org.w3c.dom.Document;
27 import org.w3c.dom.Element;
28 import org.xml.sax.SAXException;
30 import javax.xml.parsers.DocumentBuilder;
31 import javax.xml.parsers.DocumentBuilderFactory;
32 import javax.xml.parsers.ParserConfigurationException;
33 import javax.xml.transform.*;
34 import javax.xml.transform.dom.DOMSource;
35 import javax.xml.transform.stream.StreamResult;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.StringWriter;
40 import java.util.Collections;
41 import java.util.List;
44 public class NormalizedDataBuilderTest {
46 private ContainerSchemaNode containerNode;
47 private SchemaContext schema;
49 SchemaContext parseTestSchema() {
50 YangParserImpl yangParserImpl = new YangParserImpl();
51 Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(getTestYangs());
52 return yangParserImpl.resolveSchemaContext(modules);
55 List<InputStream> getTestYangs() {
57 return Lists.newArrayList(Collections2.transform(Lists.newArrayList("test.yang"),
58 new Function<String, InputStream>() {
60 public InputStream apply(String input) {
61 InputStream resourceAsStream = getClass().getResourceAsStream(input);
62 Preconditions.checkNotNull(resourceAsStream, "File %s was null", resourceAsStream);
63 return resourceAsStream;
69 public void setUp() throws Exception {
70 schema = parseTestSchema();
71 containerNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
75 public void testSchemaUnaware() throws Exception {
77 DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifier, ContainerNode> builder = Builders.containerBuilder().withNodeIdentifier(
78 getNodeIdentifier("container"));
81 LeafNode<String> leafChild = Builders.<String>leafBuilder()
82 .withNodeIdentifier(getNodeIdentifier("leaf")).withValue("String").build();
83 builder.withChild(leafChild);
86 LeafSetNode<Integer> leafList = Builders.<Integer>leafSetBuilder()
87 .withNodeIdentifier(getNodeIdentifier("leaf"))
89 .withChild(Builders.<Integer>leafSetEntryBuilder().withNodeIdentifier(getNodeWithValueIdentifier("leaf", 3)).withValue(3).build())
91 builder.withChild(leafList);
94 MapEntryNode listChild1 = Builders.mapEntryBuilder()
96 Builders.<Integer>leafBuilder()
97 .withNodeIdentifier(getNodeIdentifier("uint32InList")).withValue(1).build())
99 Builders.containerBuilder().withNodeIdentifier(
100 getNodeIdentifier("containerInList"))
103 new InstanceIdentifier.NodeIdentifierWithPredicates(getNodeIdentifier("list").getNodeType(),
104 Collections.singletonMap(getNodeIdentifier("uint32InList").getNodeType(), (Object) 1)))
107 MapNode list = Builders.mapBuilder().withChild(listChild1).withNodeIdentifier(getNodeIdentifier("list")).build();
108 builder.withChild(list);
110 AugmentationNode augmentation = Builders.augmentationBuilder()
111 .withNodeIdentifier(new InstanceIdentifier.AugmentationIdentifier(null, Sets.newHashSet(getQName("augmentUint32"))))
113 Builders.<Integer>leafBuilder().withNodeIdentifier(getNodeIdentifier("augmentUint32")).withValue(11).build())
116 builder.withChild(augmentation);
118 // This works without schema (adding child from augment as a direct child)
119 builder.withChild(Builders.<Integer>leafBuilder().withNodeIdentifier(getNodeIdentifier("augmentUint32")).withValue(11).build());
121 System.out.println(builder.build());
125 public void testSchemaAware() throws Exception {
126 DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifier, ContainerNode> builder = Builders.containerBuilder(containerNode);
128 LeafSchemaNode schemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "uint32");
129 LeafNode<String> leafChild = Builders.<String>leafBuilder(schemaNode)
130 .withValue("String").build();
131 builder.withChild(leafChild);
133 LeafListSchemaNode leafListSchemaNode = (LeafListSchemaNode) getSchemaNode(schema, "test", "leafList");
134 LeafSetNode<Integer> leafList = Builders.<Integer>leafSetBuilder(leafListSchemaNode)
136 .withChild(Builders.<Integer>leafSetEntryBuilder(leafListSchemaNode).withValue(3).build())
138 builder.withChild(leafList);
140 ListSchemaNode listSchema = (ListSchemaNode) getSchemaNode(schema, "test", "list");
141 LeafSchemaNode uint32InListSchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "uint32InList");
142 ContainerSchemaNode containerInListSchemaNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "containerInList");
144 MapEntryNode listChild1 = Builders.mapEntryBuilder(listSchema)
146 Builders.<Integer>leafBuilder(uint32InListSchemaNode).withValue(1).build())
148 Builders.containerBuilder(containerInListSchemaNode).build())
151 MapNode list = ImmutableMapNodeSchemaAwareBuilder.create(listSchema).withChild(listChild1).build();
152 builder.withChild(list);
154 LeafSchemaNode augmentUint32SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentUint32");
155 AugmentationSchema augmentationSchema = getAugmentationSchemaForChild(containerNode, augmentUint32SchemaNode.getQName());
157 AugmentationNode augmentation = Builders.augmentationBuilder(augmentationSchema).withChild(
158 Builders.<Integer>leafBuilder(augmentUint32SchemaNode).withValue(11).build())
161 builder.withChild(augmentation);
163 // This should fail with schema, since the leaf comes from augmentation
164 // builder.withChild(ImmutableLeafNodeSchemaAwareBuilder.<Integer>get(augmentUint32SchemaNode).withValue(11).build());
166 LeafSchemaNode augumentString1SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentString1");
167 LeafSchemaNode augumentString2SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentString2");
169 ChoiceNode choice1SchemaNode = (ChoiceNode) getSchemaNode(schema, "test", "choice");
170 org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode choice = ImmutableChoiceNodeSchemaAwareBuilder.create(choice1SchemaNode)
171 .withChild(Builders.<String>leafBuilder(augumentString1SchemaNode).withValue("case1")
173 // This should fail, since child node belongs to different case
174 // .withChild(Builders.<String>leafBuilder(augumentString2SchemaNode).withValue("case2")
178 ; builder.withChild(choice);
180 // This should fail, child from case
181 // builder.withChild(Builders.<String>leafBuilder(augumentString1SchemaNode).withValue("case1")
184 System.out.println(builder.build());
187 private AugmentationSchema getAugmentationSchemaForChild(ContainerSchemaNode containerNode, QName qName) {
188 for (AugmentationSchema augmentationSchema : containerNode.getAvailableAugmentations()) {
189 if(augmentationSchema.getDataChildByName(qName) != null) {
190 return augmentationSchema;
193 throw new IllegalStateException("Unable to find child augmentation in " + containerNode);
196 private InstanceIdentifier.NodeWithValue getNodeWithValueIdentifier(String localName, Object value) {
197 return new InstanceIdentifier.NodeWithValue(getQName(localName), value);
200 private QName getQName(String localName) {
201 String namespace = "namespace";
202 return new QName(URI.create(namespace), localName);
205 private InstanceIdentifier.NodeWithValue getNodeWithValueIdentifier(QName q, Object value) {
206 return new InstanceIdentifier.NodeWithValue(q, value);
209 private InstanceIdentifier.NodeIdentifier getNodeIdentifier(String localName) {
210 return new InstanceIdentifier.NodeIdentifier(getQName(localName));
213 private InstanceIdentifier.NodeIdentifier getNodeIdentifier(QName q) {
214 return new InstanceIdentifier.NodeIdentifier(q);
217 private Document loadDocument(String xmlPath) throws Exception {
218 InputStream resourceAsStream = getClass().getResourceAsStream(xmlPath);
220 Document currentConfigElement = readXmlToDocument(resourceAsStream);
221 Preconditions.checkNotNull(currentConfigElement);
222 return currentConfigElement;
225 private static final DocumentBuilderFactory BUILDERFACTORY;
228 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
229 factory.setNamespaceAware(true);
230 factory.setCoalescing(true);
231 factory.setIgnoringElementContentWhitespace(true);
232 factory.setIgnoringComments(true);
233 BUILDERFACTORY = factory;
236 private Document readXmlToDocument(InputStream xmlContent) throws IOException, SAXException {
237 DocumentBuilder dBuilder;
239 dBuilder = BUILDERFACTORY.newDocumentBuilder();
240 } catch (ParserConfigurationException e) {
241 throw new RuntimeException("Failed to parse XML document", e);
243 Document doc = dBuilder.parse(xmlContent);
245 doc.getDocumentElement().normalize();
249 public static String toString(Element xml) {
251 Transformer transformer = TransformerFactory.newInstance().newTransformer();
252 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
254 StreamResult result = new StreamResult(new StringWriter());
255 DOMSource source = new DOMSource(xml);
256 transformer.transform(source, result);
258 return result.getWriter().toString();
259 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
260 throw new RuntimeException("Unable to serialize xml element " + xml, e);
264 DataSchemaNode getSchemaNode(SchemaContext context, String moduleName, String childNodeName) {
265 for (Module module : context.getModules()) {
266 if (module.getName().equals(moduleName)) {
267 DataSchemaNode found = findChildNode(module.getChildNodes(), childNodeName);
268 Preconditions.checkState(found!=null, "Unable to find %s", childNodeName);
272 throw new IllegalStateException("Unable to find child node " + childNodeName);
275 DataSchemaNode findChildNode(Set<DataSchemaNode> children, String name) {
276 List<DataNodeContainer> containers = Lists.newArrayList();
278 for (DataSchemaNode dataSchemaNode : children) {
279 if (dataSchemaNode.getQName().getLocalName().equals(name))
280 return dataSchemaNode;
281 if(dataSchemaNode instanceof DataNodeContainer) {
282 containers.add((DataNodeContainer) dataSchemaNode);
283 } else if(dataSchemaNode instanceof ChoiceNode) {
284 containers.addAll(((ChoiceNode) dataSchemaNode).getCases());
288 for (DataNodeContainer container : containers) {
289 DataSchemaNode retVal = findChildNode(container.getChildNodes(), name);