60b93cef801fa2333ac5d02f7ce684e1295b94fb
[yangtools.git] / yang / yang-data-impl / src / test / java / org / opendaylight / yangtools / yang / data / impl / schema / NormalizedDataBuilderTest.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.impl.schema;
9
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;
29
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;
39 import java.net.URI;
40 import java.util.Collections;
41 import java.util.List;
42 import java.util.Set;
43
44 public class NormalizedDataBuilderTest {
45
46     private ContainerSchemaNode containerNode;
47     private SchemaContext schema;
48
49     SchemaContext parseTestSchema() {
50         YangParserImpl yangParserImpl = new YangParserImpl();
51         Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(getTestYangs());
52         return yangParserImpl.resolveSchemaContext(modules);
53     }
54
55     List<InputStream> getTestYangs() {
56
57         return Lists.newArrayList(Collections2.transform(Lists.newArrayList("test.yang"),
58                 new Function<String, InputStream>() {
59                     @Override
60                     public InputStream apply(String input) {
61                         InputStream resourceAsStream = getClass().getResourceAsStream(input);
62                         Preconditions.checkNotNull(resourceAsStream, "File %s was null", resourceAsStream);
63                         return resourceAsStream;
64                     }
65                 }));
66     }
67
68     @Before
69     public void setUp() throws Exception {
70         schema = parseTestSchema();
71         containerNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
72     }
73
74     @Test
75     public void testSchemaUnaware() throws Exception {
76         // Container
77         DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifier, ContainerNode> builder = Builders.containerBuilder().withNodeIdentifier(
78                 getNodeIdentifier("container"));
79
80         // leaf
81         LeafNode<String> leafChild = Builders.<String>leafBuilder()
82                 .withNodeIdentifier(getNodeIdentifier("leaf")).withValue("String").build();
83         builder.withChild(leafChild);
84
85         // leafList
86         LeafSetNode<Integer> leafList = Builders.<Integer>leafSetBuilder()
87                 .withNodeIdentifier(getNodeIdentifier("leaf"))
88                 .withChildValue(1)
89                 .withChild(Builders.<Integer>leafSetEntryBuilder().withNodeIdentifier(getNodeWithValueIdentifier("leaf", 3)).withValue(3).build())
90                 .build();
91         builder.withChild(leafList);
92
93         // list
94         MapEntryNode listChild1 = Builders.mapEntryBuilder()
95                 .withChild(
96                         Builders.<Integer>leafBuilder()
97                                 .withNodeIdentifier(getNodeIdentifier("uint32InList")).withValue(1).build())
98                 .withChild(
99                         Builders.containerBuilder().withNodeIdentifier(
100                                 getNodeIdentifier("containerInList"))
101                                 .build())
102                 .withNodeIdentifier(
103                         new InstanceIdentifier.NodeIdentifierWithPredicates(getNodeIdentifier("list").getNodeType(),
104                                 Collections.singletonMap(getNodeIdentifier("uint32InList").getNodeType(), (Object) 1)))
105                 .build();
106
107         MapNode list = Builders.mapBuilder().withChild(listChild1).withNodeIdentifier(getNodeIdentifier("list")).build();
108         builder.withChild(list);
109
110         AugmentationNode augmentation = Builders.augmentationBuilder()
111                 .withNodeIdentifier(new InstanceIdentifier.AugmentationIdentifier(null, Sets.newHashSet(getQName("augmentUint32"))))
112                 .withChild(
113                         Builders.<Integer>leafBuilder().withNodeIdentifier(getNodeIdentifier("augmentUint32")).withValue(11).build())
114                 .build();
115
116         builder.withChild(augmentation);
117
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());
120
121         System.out.println(builder.build());
122     }
123
124     @Test
125     public void testSchemaAware() throws Exception {
126         DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifier, ContainerNode> builder =  Builders.containerBuilder(containerNode);
127
128         LeafSchemaNode schemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "uint32");
129         LeafNode<String> leafChild = Builders.<String>leafBuilder(schemaNode)
130                 .withValue("String").build();
131         builder.withChild(leafChild);
132
133         LeafListSchemaNode leafListSchemaNode = (LeafListSchemaNode) getSchemaNode(schema, "test", "leafList");
134         LeafSetNode<Integer> leafList = Builders.<Integer>leafSetBuilder(leafListSchemaNode)
135                 .withChildValue(1)
136                 .withChild(Builders.<Integer>leafSetEntryBuilder(leafListSchemaNode).withValue(3).build())
137                 .build();
138         builder.withChild(leafList);
139
140         ListSchemaNode listSchema = (ListSchemaNode) getSchemaNode(schema, "test", "list");
141         LeafSchemaNode uint32InListSchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "uint32InList");
142         ContainerSchemaNode containerInListSchemaNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "containerInList");
143
144         MapEntryNode listChild1 = Builders.mapEntryBuilder(listSchema)
145                 .withChild(
146                         Builders.<Integer>leafBuilder(uint32InListSchemaNode).withValue(1).build())
147                 .withChild(
148                         Builders.containerBuilder(containerInListSchemaNode).build())
149                 .build();
150
151         MapNode list = ImmutableMapNodeSchemaAwareBuilder.create(listSchema).withChild(listChild1).build();
152         builder.withChild(list);
153
154         LeafSchemaNode augmentUint32SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentUint32");
155         AugmentationSchema augmentationSchema = getAugmentationSchemaForChild(containerNode, augmentUint32SchemaNode.getQName());
156
157         AugmentationNode augmentation = Builders.augmentationBuilder(augmentationSchema).withChild(
158                 Builders.<Integer>leafBuilder(augmentUint32SchemaNode).withValue(11).build())
159                 .build();
160
161         builder.withChild(augmentation);
162
163         // This should fail with schema, since the leaf comes from augmentation
164 //        builder.withChild(ImmutableLeafNodeSchemaAwareBuilder.<Integer>get(augmentUint32SchemaNode).withValue(11).build());
165
166         LeafSchemaNode augumentString1SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentString1");
167         LeafSchemaNode augumentString2SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentString2");
168
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")
172                         .build())
173                         // This should fail, since child node belongs to different case
174 //                .withChild(Builders.<String>leafBuilder(augumentString2SchemaNode).withValue("case2")
175 //                        .build())
176                 .build();
177
178 ;        builder.withChild(choice);
179
180         // This should fail, child from case
181 //        builder.withChild(Builders.<String>leafBuilder(augumentString1SchemaNode).withValue("case1")
182 //                .build());
183
184         System.out.println(builder.build());
185     }
186
187     private AugmentationSchema getAugmentationSchemaForChild(ContainerSchemaNode containerNode, QName qName) {
188         for (AugmentationSchema augmentationSchema : containerNode.getAvailableAugmentations()) {
189             if(augmentationSchema.getDataChildByName(qName) != null) {
190                 return augmentationSchema;
191             }
192         }
193         throw new IllegalStateException("Unable to find child augmentation in " + containerNode);
194     }
195
196     private InstanceIdentifier.NodeWithValue getNodeWithValueIdentifier(String localName, Object value) {
197         return new InstanceIdentifier.NodeWithValue(getQName(localName), value);
198     }
199
200     private QName getQName(String localName) {
201         String namespace = "namespace";
202         return new QName(URI.create(namespace), localName);
203     }
204
205     private InstanceIdentifier.NodeWithValue getNodeWithValueIdentifier(QName q, Object value) {
206         return new InstanceIdentifier.NodeWithValue(q, value);
207     }
208
209     private InstanceIdentifier.NodeIdentifier getNodeIdentifier(String localName) {
210         return new InstanceIdentifier.NodeIdentifier(getQName(localName));
211     }
212
213     private InstanceIdentifier.NodeIdentifier getNodeIdentifier(QName q) {
214         return new InstanceIdentifier.NodeIdentifier(q);
215     }
216
217     private Document loadDocument(String xmlPath) throws Exception {
218         InputStream resourceAsStream = getClass().getResourceAsStream(xmlPath);
219
220         Document currentConfigElement = readXmlToDocument(resourceAsStream);
221         Preconditions.checkNotNull(currentConfigElement);
222         return currentConfigElement;
223     }
224
225     private static final DocumentBuilderFactory BUILDERFACTORY;
226
227     static {
228         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
229         factory.setNamespaceAware(true);
230         factory.setCoalescing(true);
231         factory.setIgnoringElementContentWhitespace(true);
232         factory.setIgnoringComments(true);
233         BUILDERFACTORY = factory;
234     }
235
236     private Document readXmlToDocument(InputStream xmlContent) throws IOException, SAXException {
237         DocumentBuilder dBuilder;
238         try {
239             dBuilder = BUILDERFACTORY.newDocumentBuilder();
240         } catch (ParserConfigurationException e) {
241             throw new RuntimeException("Failed to parse XML document", e);
242         }
243         Document doc = dBuilder.parse(xmlContent);
244
245         doc.getDocumentElement().normalize();
246         return doc;
247     }
248
249     public static String toString(Element xml) {
250         try {
251             Transformer transformer = TransformerFactory.newInstance().newTransformer();
252             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
253
254             StreamResult result = new StreamResult(new StringWriter());
255             DOMSource source = new DOMSource(xml);
256             transformer.transform(source, result);
257
258             return result.getWriter().toString();
259         } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
260             throw new RuntimeException("Unable to serialize xml element " + xml, e);
261         }
262     }
263
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);
269                 return found;
270             }
271         }
272         throw new IllegalStateException("Unable to find child node " + childNodeName);
273     }
274
275     DataSchemaNode findChildNode(Set<DataSchemaNode> children, String name) {
276         List<DataNodeContainer> containers = Lists.newArrayList();
277
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());
285             }
286         }
287
288         for (DataNodeContainer container : containers) {
289             DataSchemaNode retVal = findChildNode(container.getChildNodes(), name);
290             if(retVal != null) {
291                 return retVal;
292             }
293         }
294
295         return null;
296     }
297 }