Migrate getDataChildByName() users
[yangtools.git] / yang / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / CompositeNodeDataWithSchema.java
1 /*
2  * Copyright (c) 2016 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.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.ArrayListMultimap;
14 import com.google.common.collect.Multimap;
15 import java.io.IOException;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Deque;
19 import java.util.List;
20 import java.util.Map.Entry;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyxmlSchemaNode;
23 import org.opendaylight.yangtools.rfc7952.data.api.StreamWriterMetadataExtension;
24 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
25 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
29 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
36
37 /**
38  * Utility class used for tracking parser state as needed by a StAX-like parser.
39  * This class is to be used only by respective XML and JSON parsers in yang-data-codec-xml and yang-data-codec-gson.
40  *
41  * <p>
42  * Represents a node which is composed of multiple simpler nodes.
43  */
44 public class CompositeNodeDataWithSchema<T extends DataSchemaNode> extends AbstractNodeDataWithSchema<T> {
45     /**
46      * Policy on how child nodes should be treated when an attempt is made to add them multiple times.
47      */
48     @Beta
49     public enum ChildReusePolicy {
50         /**
51          * Do not consider any existing nodes at all, just perform a straight append. Multiple occurrences of a child
52          * will result in multiple children being emitted. This is almost certainly the wrong policy unless the caller
53          * prevents such a situation from arising via some different mechanism.
54          */
55         NOOP,
56         /**
57          * Do not allow duplicate definition of a child node. This would typically be used when a child cannot be
58          * encountered multiple times, but the caller does not make any provision to detect such a conflict. If a child
59          * node would end up being defined a second time, {@link DuplicateChildNodeRejectedException} is reported.
60          */
61         REJECT {
62             @Override
63             AbstractNodeDataWithSchema<?> appendChild(final Collection<AbstractNodeDataWithSchema<?>> view,
64                     final AbstractNodeDataWithSchema<?> newChild) {
65                 final DataSchemaNode childSchema = newChild.getSchema();
66                 final AbstractNodeDataWithSchema<?> existing = findExistingChild(view, childSchema);
67                 if (existing != null) {
68                     throw new DuplicateChildNodeRejectedException("Duplicate child " + childSchema.getQName());
69                 }
70                 return super.appendChild(view, newChild);
71             }
72         },
73         /**
74          * Reuse previously-defined child node. This is most appropriate when a child may be visited multiple times
75          * and the intent is to append content of each visit. A typical usage is list elements with RFC7950 XML
76          * encoding, where there is no encapsulating element and hence list entries may be interleaved with other
77          * children.
78          */
79         REUSE {
80             @Override
81             AbstractNodeDataWithSchema<?> appendChild(final Collection<AbstractNodeDataWithSchema<?>> view,
82                     final AbstractNodeDataWithSchema<?> newChild) {
83                 final AbstractNodeDataWithSchema<?> existing = findExistingChild(view, newChild.getSchema());
84                 return existing != null ? existing : super.appendChild(view, newChild);
85             }
86         };
87
88         AbstractNodeDataWithSchema<?> appendChild(final Collection<AbstractNodeDataWithSchema<?>> view,
89                 final AbstractNodeDataWithSchema<?> newChild) {
90             view.add(newChild);
91             return newChild;
92         }
93
94         static @Nullable AbstractNodeDataWithSchema<?> findExistingChild(
95                 final Collection<AbstractNodeDataWithSchema<?>> view, final DataSchemaNode childSchema) {
96             for (AbstractNodeDataWithSchema<?> existing : view) {
97                 if (childSchema.equals(existing.getSchema())) {
98                     return existing;
99                 }
100             }
101             return null;
102         }
103     }
104
105     /**
106      * nodes which were added to schema via augmentation and are present in data input.
107      */
108     private final Multimap<AugmentationSchemaNode, AbstractNodeDataWithSchema<?>> augmentationsToChild =
109         ArrayListMultimap.create();
110
111     /**
112      * remaining data nodes (which aren't added via augment). Every of one them should have the same QName.
113      */
114     private final List<AbstractNodeDataWithSchema<?>> children = new ArrayList<>();
115
116     public CompositeNodeDataWithSchema(final T schema) {
117         super(schema);
118     }
119
120     void addChild(final AbstractNodeDataWithSchema<?> newChild) {
121         children.add(newChild);
122     }
123
124     public final AbstractNodeDataWithSchema<?> addChild(final Deque<DataSchemaNode> schemas,
125             final ChildReusePolicy policy) {
126         checkArgument(!schemas.isEmpty(), "Expecting at least one schema");
127
128         // Pop the first node...
129         final DataSchemaNode schema = schemas.pop();
130         if (schemas.isEmpty()) {
131             // Simple, direct node
132             return addChild(schema, policy);
133         }
134
135         // The choice/case mess, reuse what we already popped
136         final DataSchemaNode choiceCandidate = schema;
137         checkArgument(choiceCandidate instanceof ChoiceSchemaNode, "Expected node of type ChoiceNode but was %s",
138             choiceCandidate.getClass());
139         final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) choiceCandidate;
140
141         final DataSchemaNode caseCandidate = schemas.pop();
142         checkArgument(caseCandidate instanceof CaseSchemaNode, "Expected node of type ChoiceCaseNode but was %s",
143             caseCandidate.getClass());
144         final CaseSchemaNode caseNode = (CaseSchemaNode) caseCandidate;
145
146         final AugmentationSchemaNode augSchema;
147         if (choiceCandidate.isAugmenting()) {
148             augSchema = findCorrespondingAugment(getSchema(), choiceCandidate);
149         } else {
150             augSchema = null;
151         }
152
153         // looking for existing choice
154         final Collection<AbstractNodeDataWithSchema<?>> childNodes;
155         if (augSchema != null) {
156             childNodes = augmentationsToChild.get(augSchema);
157         } else {
158             childNodes = children;
159         }
160
161         CompositeNodeDataWithSchema<?> caseNodeDataWithSchema = findChoice(childNodes, choiceCandidate, caseCandidate);
162         if (caseNodeDataWithSchema == null) {
163             ChoiceNodeDataWithSchema choiceNodeDataWithSchema = new ChoiceNodeDataWithSchema(choiceNode);
164             childNodes.add(choiceNodeDataWithSchema);
165             caseNodeDataWithSchema = choiceNodeDataWithSchema.addCompositeChild(caseNode, ChildReusePolicy.NOOP);
166         }
167
168         return caseNodeDataWithSchema.addChild(schemas, policy);
169     }
170
171     private AbstractNodeDataWithSchema<?> addChild(final DataSchemaNode schema, final ChildReusePolicy policy) {
172         AbstractNodeDataWithSchema<?> newChild = addSimpleChild(schema, policy);
173         return newChild == null ? addCompositeChild(schema, policy) : newChild;
174     }
175
176     private AbstractNodeDataWithSchema<?> addSimpleChild(final DataSchemaNode schema, final ChildReusePolicy policy) {
177         final SimpleNodeDataWithSchema<?> newChild;
178         if (schema instanceof LeafSchemaNode) {
179             newChild = new LeafNodeDataWithSchema((LeafSchemaNode) schema);
180         } else if (schema instanceof AnyxmlSchemaNode) {
181             // YangModeledAnyxmlSchemaNode is handled by addCompositeChild method.
182             if (schema instanceof YangModeledAnyxmlSchemaNode) {
183                 return null;
184             }
185             newChild = new AnyXmlNodeDataWithSchema((AnyxmlSchemaNode) schema);
186         } else if (schema instanceof AnydataSchemaNode) {
187             newChild = new AnydataNodeDataWithSchema((AnydataSchemaNode) schema);
188         } else {
189             return null;
190         }
191
192         final AugmentationSchemaNode augSchema;
193         if (schema.isAugmenting()) {
194             augSchema = findCorrespondingAugment(getSchema(), schema);
195         } else {
196             augSchema = null;
197         }
198
199         // FIXME: 7.0.0: use policy to determine if we should reuse or replace the child
200
201         if (augSchema != null) {
202             augmentationsToChild.put(augSchema, newChild);
203         } else {
204             addChild(newChild);
205         }
206         return newChild;
207     }
208
209     private static CaseNodeDataWithSchema findChoice(final Collection<AbstractNodeDataWithSchema<?>> childNodes,
210             final DataSchemaNode choiceCandidate, final DataSchemaNode caseCandidate) {
211         if (childNodes != null) {
212             for (AbstractNodeDataWithSchema<?> nodeDataWithSchema : childNodes) {
213                 if (nodeDataWithSchema instanceof ChoiceNodeDataWithSchema
214                         && nodeDataWithSchema.getSchema().getQName().equals(choiceCandidate.getQName())) {
215                     CaseNodeDataWithSchema casePrevious = ((ChoiceNodeDataWithSchema) nodeDataWithSchema).getCase();
216
217                     checkArgument(casePrevious.getSchema().getQName().equals(caseCandidate.getQName()),
218                         "Data from case %s are specified but other data from case %s were specified earlier."
219                         + " Data aren't from the same case.", caseCandidate.getQName(),
220                         casePrevious.getSchema().getQName());
221
222                     return casePrevious;
223                 }
224             }
225         }
226         return null;
227     }
228
229     AbstractNodeDataWithSchema<?> addCompositeChild(final DataSchemaNode schema, final ChildReusePolicy policy) {
230         final CompositeNodeDataWithSchema<?> newChild;
231
232         if (schema instanceof ListSchemaNode) {
233             newChild = new ListNodeDataWithSchema((ListSchemaNode) schema);
234         } else if (schema instanceof LeafListSchemaNode) {
235             newChild = new LeafListNodeDataWithSchema((LeafListSchemaNode) schema);
236         } else if (schema instanceof ContainerLike) {
237             newChild = new ContainerNodeDataWithSchema((ContainerLike) schema);
238         } else if (schema instanceof YangModeledAnyxmlSchemaNode) {
239             newChild = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyxmlSchemaNode)schema);
240         } else {
241             newChild = new CompositeNodeDataWithSchema<>(schema);
242         }
243
244         return addCompositeChild(newChild, policy);
245     }
246
247     final AbstractNodeDataWithSchema<?> addCompositeChild(final CompositeNodeDataWithSchema<?> newChild,
248             final ChildReusePolicy policy) {
249         final AugmentationSchemaNode augSchema = findCorrespondingAugment(getSchema(), newChild.getSchema());
250         final Collection<AbstractNodeDataWithSchema<?>> view = augSchema == null ? children
251                 : augmentationsToChild.get(augSchema);
252
253         return policy.appendChild(view, newChild);
254     }
255
256     /**
257      * Return a hint about how may children we are going to generate.
258      * @return Size of currently-present node list.
259      */
260     protected final int childSizeHint() {
261         return children.size();
262     }
263
264     @Override
265     public void write(final NormalizedNodeStreamWriter writer, final StreamWriterMetadataExtension metaWriter)
266             throws IOException {
267         for (AbstractNodeDataWithSchema<?> child : children) {
268             child.write(writer, metaWriter);
269         }
270         for (Entry<AugmentationSchemaNode, Collection<AbstractNodeDataWithSchema<?>>> augmentationToChild
271                 : augmentationsToChild.asMap().entrySet()) {
272             final Collection<AbstractNodeDataWithSchema<?>> childsFromAgumentation = augmentationToChild.getValue();
273             if (!childsFromAgumentation.isEmpty()) {
274                 // FIXME: can we get the augmentation schema?
275                 writer.startAugmentationNode(DataSchemaContextNode.augmentationIdentifierFrom(
276                     augmentationToChild.getKey()));
277
278                 for (AbstractNodeDataWithSchema<?> nodeDataWithSchema : childsFromAgumentation) {
279                     nodeDataWithSchema.write(writer, metaWriter);
280                 }
281
282                 writer.endNode();
283             }
284         }
285     }
286
287     /**
288      * Tries to find in {@code parent} which is dealed as augmentation target node with QName as {@code child}. If such
289      * node is found then it is returned, else null.
290      *
291      * @param parent parent node
292      * @param child child node
293      * @return augmentation schema
294      */
295     private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
296             final DataSchemaNode child) {
297         if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
298             for (AugmentationSchemaNode augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
299                 DataSchemaNode childInAugmentation = augmentation.dataChildByName(child.getQName());
300                 if (childInAugmentation != null) {
301                     return augmentation;
302                 }
303             }
304         }
305         return null;
306     }
307 }