Clean up more Sonar warnings
[yangtools.git] / data / 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 java.io.IOException;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Deque;
17 import java.util.List;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
21 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.MetadataExtension;
22 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
27 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
31
32 /**
33  * Utility class used for tracking parser state as needed by a StAX-like parser.
34  * This class is to be used only by respective XML and JSON parsers in yang-data-codec-xml and yang-data-codec-gson.
35  *
36  * <p>
37  * Represents a node which is composed of multiple simpler nodes.
38  */
39 public sealed class CompositeNodeDataWithSchema<T extends DataSchemaNode> extends AbstractNodeDataWithSchema<T>
40         permits AbstractMountPointDataWithSchema, CaseNodeDataWithSchema, ChoiceNodeDataWithSchema,
41                 LeafListNodeDataWithSchema, ListNodeDataWithSchema {
42     /**
43      * Policy on how child nodes should be treated when an attempt is made to add them multiple times.
44      */
45     @Beta
46     public enum ChildReusePolicy {
47         /**
48          * Do not consider any existing nodes at all, just perform a straight append. Multiple occurrences of a child
49          * will result in multiple children being emitted. This is almost certainly the wrong policy unless the caller
50          * prevents such a situation from arising via some different mechanism.
51          */
52         NOOP,
53         /**
54          * Do not allow duplicate definition of a child node. This would typically be used when a child cannot be
55          * encountered multiple times, but the caller does not make any provision to detect such a conflict. If a child
56          * node would end up being defined a second time, {@link DuplicateChildNodeRejectedException} is reported.
57          */
58         REJECT {
59             @Override
60             AbstractNodeDataWithSchema<?> appendChild(final Collection<AbstractNodeDataWithSchema<?>> view,
61                     final AbstractNodeDataWithSchema<?> newChild) {
62                 final DataSchemaNode childSchema = newChild.getSchema();
63                 final AbstractNodeDataWithSchema<?> existing = findExistingChild(view, childSchema);
64                 if (existing != null) {
65                     throw new DuplicateChildNodeRejectedException("Duplicate child " + childSchema.getQName());
66                 }
67                 return super.appendChild(view, newChild);
68             }
69         },
70         /**
71          * Reuse previously-defined child node. This is most appropriate when a child may be visited multiple times
72          * and the intent is to append content of each visit. A typical usage is list elements with RFC7950 XML
73          * encoding, where there is no encapsulating element and hence list entries may be interleaved with other
74          * children.
75          */
76         REUSE {
77             @Override
78             AbstractNodeDataWithSchema<?> appendChild(final Collection<AbstractNodeDataWithSchema<?>> view,
79                     final AbstractNodeDataWithSchema<?> newChild) {
80                 final AbstractNodeDataWithSchema<?> existing = findExistingChild(view, newChild.getSchema());
81                 return existing != null ? existing : super.appendChild(view, newChild);
82             }
83         };
84
85         AbstractNodeDataWithSchema<?> appendChild(final Collection<AbstractNodeDataWithSchema<?>> view,
86                 final AbstractNodeDataWithSchema<?> newChild) {
87             view.add(newChild);
88             return newChild;
89         }
90
91         static @Nullable AbstractNodeDataWithSchema<?> findExistingChild(
92                 final Collection<AbstractNodeDataWithSchema<?>> view, final DataSchemaNode childSchema) {
93             for (AbstractNodeDataWithSchema<?> existing : view) {
94                 if (childSchema.equals(existing.getSchema())) {
95                     return existing;
96                 }
97             }
98             return null;
99         }
100     }
101
102     /**
103      * remaining data nodes (which aren't added via augment). Every of one them should have the same QName.
104      */
105     private final List<AbstractNodeDataWithSchema<?>> children = new ArrayList<>();
106
107     // FIXME: hide this when JSON codec is sane
108     public CompositeNodeDataWithSchema(final T schema) {
109         super(schema);
110     }
111
112     public static @NonNull CompositeNodeDataWithSchema<?> of(final DataSchemaNode schema) {
113         if (schema instanceof ListSchemaNode list) {
114             return new ListNodeDataWithSchema(list);
115         } else if (schema instanceof LeafListSchemaNode leafList) {
116             return new LeafListNodeDataWithSchema(leafList);
117         } else if (schema instanceof ContainerLike containerLike) {
118             return new ContainerNodeDataWithSchema(containerLike);
119         } else {
120             return new CompositeNodeDataWithSchema<>(schema);
121         }
122     }
123
124     void addChild(final AbstractNodeDataWithSchema<?> newChild) {
125         children.add(newChild);
126     }
127
128     public final AbstractNodeDataWithSchema<?> addChild(final Deque<DataSchemaNode> schemas,
129             final ChildReusePolicy policy) {
130         checkArgument(!schemas.isEmpty(), "Expecting at least one schema");
131
132         // Pop the first node...
133         final DataSchemaNode schema = schemas.pop();
134         if (schemas.isEmpty()) {
135             // Simple, direct node
136             return addChild(schema, policy);
137         }
138
139         // The choice/case mess, reuse what we already popped
140         final DataSchemaNode choiceCandidate = schema;
141         checkArgument(choiceCandidate instanceof ChoiceSchemaNode, "Expected node of type ChoiceNode but was %s",
142             choiceCandidate.getClass());
143         final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) choiceCandidate;
144
145         final DataSchemaNode caseCandidate = schemas.pop();
146         checkArgument(caseCandidate instanceof CaseSchemaNode, "Expected node of type ChoiceCaseNode but was %s",
147             caseCandidate.getClass());
148         final CaseSchemaNode caseNode = (CaseSchemaNode) caseCandidate;
149
150         CompositeNodeDataWithSchema<?> caseNodeDataWithSchema = findChoice(children, choiceCandidate, caseCandidate);
151         if (caseNodeDataWithSchema == null) {
152             ChoiceNodeDataWithSchema choiceNodeDataWithSchema = new ChoiceNodeDataWithSchema(choiceNode);
153             children.add(choiceNodeDataWithSchema);
154             caseNodeDataWithSchema = choiceNodeDataWithSchema.addCompositeChild(caseNode, ChildReusePolicy.NOOP);
155         }
156
157         return caseNodeDataWithSchema.addChild(schemas, policy);
158     }
159
160     private AbstractNodeDataWithSchema<?> addChild(final DataSchemaNode schema, final ChildReusePolicy policy) {
161         AbstractNodeDataWithSchema<?> newChild = addSimpleChild(schema, policy);
162         return newChild == null ? addCompositeChild(schema, policy) : newChild;
163     }
164
165     private AbstractNodeDataWithSchema<?> addSimpleChild(final DataSchemaNode schema, final ChildReusePolicy policy) {
166         final SimpleNodeDataWithSchema<?> newChild;
167         if (schema instanceof LeafSchemaNode leaf) {
168             newChild = new LeafNodeDataWithSchema(leaf);
169         } else if (schema instanceof AnyxmlSchemaNode anyxml) {
170             newChild = new AnyXmlNodeDataWithSchema(anyxml);
171         } else if (schema instanceof AnydataSchemaNode anydata) {
172             newChild = new AnydataNodeDataWithSchema(anydata);
173         } else {
174             return null;
175         }
176
177         // FIXME: 7.0.0: use policy to determine if we should reuse or replace the child
178         addChild(newChild);
179         return newChild;
180     }
181
182     private static CaseNodeDataWithSchema findChoice(final Collection<AbstractNodeDataWithSchema<?>> childNodes,
183             final DataSchemaNode choiceCandidate, final DataSchemaNode caseCandidate) {
184         if (childNodes != null) {
185             for (AbstractNodeDataWithSchema<?> nodeDataWithSchema : childNodes) {
186                 if (nodeDataWithSchema instanceof ChoiceNodeDataWithSchema childChoice
187                         && nodeDataWithSchema.getSchema().getQName().equals(choiceCandidate.getQName())) {
188                     CaseNodeDataWithSchema casePrevious = childChoice.getCase();
189
190                     checkArgument(casePrevious.getSchema().getQName().equals(caseCandidate.getQName()),
191                         "Data from case %s are specified but other data from case %s were specified earlier."
192                         + " Data aren't from the same case.", caseCandidate.getQName(),
193                         casePrevious.getSchema().getQName());
194
195                     return casePrevious;
196                 }
197             }
198         }
199         return null;
200     }
201
202     AbstractNodeDataWithSchema<?> addCompositeChild(final DataSchemaNode schema, final ChildReusePolicy policy) {
203         return addCompositeChild(of(schema), policy);
204     }
205
206     final AbstractNodeDataWithSchema<?> addCompositeChild(final CompositeNodeDataWithSchema<?> newChild,
207             final ChildReusePolicy policy) {
208         return policy.appendChild(children, newChild);
209     }
210
211     /**
212      * Return a hint about how may children we are going to generate.
213      * @return Size of currently-present node list.
214      */
215     protected final int childSizeHint() {
216         return children.size();
217     }
218
219     @Override
220     public void write(final NormalizedNodeStreamWriter writer, final MetadataExtension metaWriter) throws IOException {
221         // FIXME: we probably want to emit children with the same namespace first
222         for (var child : children) {
223             child.write(writer, metaWriter);
224         }
225     }
226 }