BUG-2062: use newly-introduced ordered leaf-list methods
[netconf.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / netconf / util / OrderedNormalizedNodeWriter.java
1 /*
2  * Copyright (c) 2015 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
9 package org.opendaylight.netconf.util;
10
11 import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
12
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Predicate;
16 import com.google.common.collect.ArrayListMultimap;
17 import com.google.common.collect.Iterables;
18
19 import java.io.Closeable;
20 import java.io.Flushable;
21 import java.io.IOException;
22 import java.util.Collection;
23 import java.util.List;
24 import java.util.Objects;
25
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamAttributeWriter;
43 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
45 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
53
54 //TODO this does not extend NormalizedNodeWriter from yangtools due to api freeze, make this inherit common methods to avoid code duplication
55 //TODO move this to yangtools, since this is in netconf-util due to api freeze in lithium
56 public class OrderedNormalizedNodeWriter implements Closeable, Flushable{
57
58     private final SchemaContext schemaContext;
59     private final SchemaNode root;
60     private final NormalizedNodeStreamWriter writer;
61
62     public OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer,final SchemaContext schemaContext,final SchemaPath path) {
63         this.writer = writer;
64         this.schemaContext = schemaContext;
65         this.root = findParentSchemaOnPath(schemaContext, path);
66     }
67
68     public OrderedNormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
69         if (Objects.equals(root, schemaContext)) {
70             return write(node, schemaContext.getDataChildByName(node.getNodeType()));
71         }
72
73         return write(node, root);
74     }
75
76     public OrderedNormalizedNodeWriter write(final Collection<DataContainerChild<?,?>> nodes) throws IOException {
77         if (writeChildren(nodes, root, false)) {
78             return this;
79         }
80
81         throw new IllegalStateException("It wasn't possible to serialize nodes " + nodes);
82
83     }
84
85     private OrderedNormalizedNodeWriter write(final NormalizedNode<?, ?> node, final SchemaNode dataSchemaNode) throws IOException {
86         if (node == null) {
87             return this;
88         }
89
90         if (wasProcessedAsCompositeNode(node, dataSchemaNode)) {
91             return this;
92         }
93
94         if (wasProcessAsSimpleNode(node)) {
95             return this;
96         }
97
98         throw new IllegalStateException("It wasn't possible to serialize node " + node);
99     }
100
101     private void write(final List<NormalizedNode<?, ?>> nodes, final SchemaNode dataSchemaNode) throws IOException {
102         for (NormalizedNode<?, ?> node : nodes) {
103             write(node, dataSchemaNode);
104         }
105     }
106
107     private OrderedNormalizedNodeWriter writeLeaf(final NormalizedNode<?, ?> node) throws IOException {
108         if (wasProcessAsSimpleNode(node)) {
109             return this;
110         }
111
112         throw new IllegalStateException("It wasn't possible to serialize node " + node);
113     }
114
115     private boolean writeChildren(final Iterable<? extends NormalizedNode<?, ?>> children, final SchemaNode parentSchemaNode, boolean endParent) throws IOException {
116         //Augmentations cannot be gotten with node.getChild so create our own structure with augmentations resolved
117         ArrayListMultimap<QName, NormalizedNode<?, ?>> qNameToNodes = ArrayListMultimap.create();
118         for (NormalizedNode<?, ?> child : children) {
119             if (child instanceof AugmentationNode) {
120                 qNameToNodes.putAll(resolveAugmentations(child));
121             } else {
122                 qNameToNodes.put(child.getNodeType(), child);
123             }
124         }
125
126         if (parentSchemaNode instanceof DataNodeContainer) {
127             if (parentSchemaNode instanceof ListSchemaNode && qNameToNodes.containsKey(parentSchemaNode.getQName())) {
128                 write(qNameToNodes.get(parentSchemaNode.getQName()), parentSchemaNode);
129             } else {
130                 for (DataSchemaNode schemaNode : ((DataNodeContainer) parentSchemaNode).getChildNodes()) {
131                     write(qNameToNodes.get(schemaNode.getQName()), schemaNode);
132                 }
133             }
134         } else if(parentSchemaNode instanceof ChoiceSchemaNode) {
135             for (ChoiceCaseNode ccNode : ((ChoiceSchemaNode) parentSchemaNode).getCases()) {
136                 for (DataSchemaNode dsn : ccNode.getChildNodes()) {
137                     if (qNameToNodes.containsKey(dsn.getQName())) {
138                         write(qNameToNodes.get(dsn.getQName()), dsn);
139                     }
140                 }
141             }
142         } else {
143             for (NormalizedNode<?, ?> child : children) {
144                 writeLeaf(child);
145             }
146         }
147         if (endParent) {
148             writer.endNode();
149         }
150         return true;
151     }
152
153     private ArrayListMultimap<QName, NormalizedNode<?, ?>> resolveAugmentations(final NormalizedNode<?, ?> child) {
154         final ArrayListMultimap<QName, NormalizedNode<?, ?>> resolvedAugs = ArrayListMultimap.create();
155         for (NormalizedNode<?, ?> node : ((AugmentationNode) child).getValue()) {
156             if (node instanceof AugmentationNode) {
157                 resolvedAugs.putAll(resolveAugmentations(node));
158             } else {
159                 resolvedAugs.put(node.getNodeType(), node);
160             }
161         }
162         return resolvedAugs;
163     }
164
165     private boolean writeMapEntryNode(final MapEntryNode node, final SchemaNode dataSchemaNode) throws IOException {
166         if(writer instanceof NormalizedNodeStreamAttributeWriter) {
167             ((NormalizedNodeStreamAttributeWriter) writer)
168                     .startMapEntryNode(node.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(node.getValue()), node.getAttributes());
169         } else {
170             writer.startMapEntryNode(node.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(node.getValue()));
171         }
172         return writeChildren(node.getValue(), dataSchemaNode, true);
173     }
174
175     private boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
176         if (node instanceof LeafSetEntryNode) {
177             final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>)node;
178             if(writer instanceof NormalizedNodeStreamAttributeWriter) {
179                 ((NormalizedNodeStreamAttributeWriter) writer).leafSetEntryNode(nodeAsLeafList.getValue(), nodeAsLeafList.getAttributes());
180             } else {
181                 writer.leafSetEntryNode(nodeAsLeafList.getValue());
182             }
183             return true;
184         } else if (node instanceof LeafNode) {
185             final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
186             if(writer instanceof NormalizedNodeStreamAttributeWriter) {
187                 ((NormalizedNodeStreamAttributeWriter) writer).leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue(), nodeAsLeaf.getAttributes());
188             } else {
189                 writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
190             }
191             return true;
192         } else if (node instanceof AnyXmlNode) {
193             final AnyXmlNode anyXmlNode = (AnyXmlNode)node;
194             writer.anyxmlNode(anyXmlNode.getIdentifier(), anyXmlNode.getValue());
195             return true;
196         }
197
198         return false;
199     }
200
201     private boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node, final SchemaNode dataSchemaNode) throws IOException {
202         if (node instanceof ContainerNode) {
203             final ContainerNode n = (ContainerNode) node;
204             if(writer instanceof NormalizedNodeStreamAttributeWriter) {
205                 ((NormalizedNodeStreamAttributeWriter) writer).startContainerNode(n.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(n.getValue()), n.getAttributes());
206             } else {
207                 writer.startContainerNode(n.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(n.getValue()));
208             }
209             return writeChildren(n.getValue(), dataSchemaNode, true);
210         }
211         if (node instanceof MapEntryNode) {
212             return writeMapEntryNode((MapEntryNode) node, dataSchemaNode);
213         }
214         if (node instanceof UnkeyedListEntryNode) {
215             final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
216             writer.startUnkeyedListItem(n.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(n.getValue()));
217             return writeChildren(n.getValue(), dataSchemaNode, true);
218         }
219         if (node instanceof ChoiceNode) {
220             final ChoiceNode n = (ChoiceNode) node;
221             writer.startChoiceNode(n.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(n.getValue()));
222             return writeChildren(n.getValue(), dataSchemaNode, true);
223         }
224         if (node instanceof AugmentationNode) {
225             final AugmentationNode n = (AugmentationNode) node;
226             writer.startAugmentationNode(n.getIdentifier());
227             return writeChildren(n.getValue(), dataSchemaNode, true);
228         }
229         if (node instanceof UnkeyedListNode) {
230             final UnkeyedListNode n = (UnkeyedListNode) node;
231             writer.startUnkeyedList(n.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(n.getValue()));
232             return writeChildren(n.getValue(), dataSchemaNode, true);
233         }
234         if (node instanceof OrderedMapNode) {
235             final OrderedMapNode n = (OrderedMapNode) node;
236             writer.startOrderedMapNode(n.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(n.getValue()));
237             return writeChildren(n.getValue(), dataSchemaNode, true);
238         }
239         if (node instanceof MapNode) {
240             final MapNode n = (MapNode) node;
241             writer.startMapNode(n.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(n.getValue()));
242             return writeChildren(n.getValue(), dataSchemaNode, true);
243         }
244         if (node instanceof LeafSetNode) {
245             final LeafSetNode<?> n = (LeafSetNode<?>) node;
246             if (node instanceof OrderedLeafSetNode) {
247                 writer.startOrderedLeafSet(n.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(n.getValue()));
248             } else {
249                 writer.startLeafSet(n.getIdentifier(), OrderedNormalizedNodeWriter.childSizeHint(n.getValue()));
250             }
251             return writeChildren(n.getValue(), dataSchemaNode, true);
252         }
253
254         return false;
255     }
256
257     private static final int childSizeHint(final Iterable<?> children) {
258         return (children instanceof Collection) ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
259     }
260
261     //TODO similar code is already present in schemaTracker, unify this when this writer is moved back to yangtools
262     private SchemaNode findParentSchemaOnPath(final SchemaContext schemaContext, final SchemaPath path) {
263         SchemaNode current = Preconditions.checkNotNull(schemaContext);
264         for (final QName qname : path.getPathFromRoot()) {
265             SchemaNode child;
266             if(current instanceof DataNodeContainer) {
267                 child = ((DataNodeContainer) current).getDataChildByName(qname);
268
269                 if (child == null && current instanceof SchemaContext) {
270                     child = tryFindGroupings((SchemaContext) current, qname).orNull();
271                 }
272
273                 if(child == null && current instanceof SchemaContext) {
274                     child = tryFindNotification((SchemaContext) current, qname)
275                             .or(tryFindRpc(((SchemaContext) current), qname)).orNull();
276                 }
277             } else if (current instanceof ChoiceSchemaNode) {
278                 child = ((ChoiceSchemaNode) current).getCaseNodeByName(qname);
279             } else if (current instanceof RpcDefinition) {
280                 switch (qname.getLocalName()) {
281                 case "input":
282                     child = ((RpcDefinition) current).getInput();
283                     break;
284                 case "output":
285                     child = ((RpcDefinition) current).getOutput();
286                     break;
287                 default:
288                     child = null;
289                     break;
290                 }
291             } else {
292                 throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", current));
293             }
294             current = child;
295         }
296         return current;
297     }
298
299     //TODO this method is already present in schemaTracker, unify this when this writer is moved back to yangtools
300     private Optional<SchemaNode> tryFindGroupings(final SchemaContext ctx, final QName qname) {
301         return Optional.<SchemaNode> fromNullable(Iterables.find(ctx.getGroupings(), new SchemaNodePredicate(qname), null));
302     }
303
304     //TODO this method is already present in schemaTracker, unify this when this writer is moved back to yangtools
305     private Optional<SchemaNode> tryFindRpc(final SchemaContext ctx, final QName qname) {
306         return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getOperations(), new SchemaNodePredicate(qname), null));
307     }
308
309     //TODO this method is already present in schemaTracker, unify this when this writer is moved back to yangtools
310     private Optional<SchemaNode> tryFindNotification(final SchemaContext ctx, final QName qname) {
311         return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getNotifications(), new SchemaNodePredicate(qname), null));
312     }
313
314     @Override
315     public void flush() throws IOException {
316         writer.flush();
317     }
318
319     @Override
320     public void close() throws IOException {
321         writer.flush();
322         writer.close();
323     }
324
325     //TODO this class is already present in schemaTracker, unify this when this writer is moved back to yangtools
326     private static final class SchemaNodePredicate implements Predicate<SchemaNode> {
327         private final QName qname;
328
329         public SchemaNodePredicate(final QName qname) {
330             this.qname = qname;
331         }
332
333         @Override
334         public boolean apply(final SchemaNode input) {
335             return input.getQName().equals(qname);
336         }
337     }
338 }