Remove Augmentation{Identifier,Node}
[yangtools.git] / data / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / ImmutableNormalizedNodeStreamWriter.java
1 /*
2  * Copyright (c) 2014 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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import java.io.IOException;
15 import java.util.ArrayDeque;
16 import java.util.Deque;
17 import javax.xml.transform.dom.DOMSource;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
25 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
26 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
27 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
28 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
29 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder;
30 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
31 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
32 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListNodeBuilder;
33 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUserLeafSetNodeBuilder;
34 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUserMapNodeBuilder;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36
37 /**
38  * Implementation of {@link NormalizedNodeStreamWriter}, which constructs immutable instances of
39  * {@link NormalizedNode}s.
40  *
41  * <p>
42  * This writer supports two modes of behaviour one is using {@link #from(NormalizedNodeResult)} where resulting
43  * NormalizedNode will be stored in supplied result object.
44  *
45  * <p>
46  * Other mode of operation is using {@link #from(NormalizedNodeContainerBuilder)}, where all created nodes will be
47  * written to this builder.
48  *
49  * <p>
50  * This class is not final for purposes of customization, normal users should not need to subclass it.
51  */
52 public class ImmutableNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
53     @SuppressWarnings("rawtypes")
54     private final Deque<NormalizedNodeBuilder> builders = new ArrayDeque<>();
55
56     private DataSchemaNode nextSchema;
57
58     @SuppressWarnings("rawtypes")
59     protected ImmutableNormalizedNodeStreamWriter(final NormalizedNodeBuilder topLevelBuilder) {
60         builders.push(topLevelBuilder);
61     }
62
63     protected ImmutableNormalizedNodeStreamWriter(final NormalizationResultHolder holder) {
64         this(new NormalizationResultBuilder(holder));
65     }
66
67     /**
68      * Creates a {@link NormalizedNodeStreamWriter} which creates instances of supplied {@link NormalizedNode}s
69      * and writes them to supplied builder as child nodes.
70      *
71      * <p>
72      * Type of supplied {@link NormalizedNodeContainerBuilder} affects, which events could be emitted in order
73      * to ensure proper construction of data.
74      *
75      * @param builder Builder to which data will be written.
76      * @return {@link NormalizedNodeStreamWriter} which writes data
77      */
78     public static @NonNull NormalizedNodeStreamWriter from(final NormalizedNodeContainerBuilder<?, ?, ?, ?> builder) {
79         return new ImmutableNormalizedNodeStreamWriter(builder);
80     }
81
82     /**
83      * Creates a {@link NormalizedNodeStreamWriter} which creates one instance of top-level {@link NormalizedNode}
84      * (type of NormalizedNode) is determined by first start event.
85      *
86      * <p>
87      * Result is built when {@link #endNode()} associated with that start event is emitted.
88      *
89      * <p>
90      * Writer properly creates also nested {@link NormalizedNode} instances, if their are supported inside the scope
91      * of the first event.
92      *
93      * <p>
94      * This method is useful for clients, which knows there will be one top-level node written, but does not know which
95      * type of {@link NormalizedNode} will be written.
96      *
97      * @param holder {@link NormalizationResultHolder} object which will hold result value.
98      * @return {@link NormalizedNodeStreamWriter} which will write item to supplied result holder.
99      */
100     public static @NonNull NormalizedNodeStreamWriter from(final NormalizationResultHolder holder) {
101         return new ImmutableMetadataNormalizedNodeStreamWriter(holder);
102     }
103
104     @Override
105     public void startLeafNode(final NodeIdentifier name) {
106         checkDataNodeContainer();
107         enter(name, leafNodeBuilder(nextSchema));
108         nextSchema = null;
109     }
110
111     @Override
112     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) {
113         checkDataNodeContainer();
114         enter(name, UNKNOWN_SIZE == childSizeHint ? InterningLeafSetNodeBuilder.create(nextSchema)
115                 : InterningLeafSetNodeBuilder.create(nextSchema, childSizeHint));
116     }
117
118     @Override
119     public void startLeafSetEntryNode(final NodeWithValue<?> name) {
120         final NormalizedNodeBuilder<?, ?, ?> current = current();
121         checkArgument(current instanceof ImmutableLeafSetNodeBuilder
122             || current instanceof ImmutableUserLeafSetNodeBuilder || current instanceof NormalizationResultBuilder,
123             "LeafSetEntryNode is not valid for parent %s", current);
124         enter(name, leafsetEntryNodeBuilder());
125         nextSchema = null;
126     }
127
128     @Override
129     public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) {
130         checkDataNodeContainer();
131         enter(name, Builders.orderedLeafSetBuilder());
132     }
133
134     @Override
135     public boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) {
136         checkDataNodeContainer();
137         if (DOMSource.class.isAssignableFrom(objectModel)) {
138             enter(name, Builders.anyXmlBuilder());
139             nextSchema = null;
140             return true;
141         }
142         return false;
143     }
144
145     @Override
146     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) {
147         checkDataNodeContainer();
148         enter(name, UNKNOWN_SIZE == childSizeHint ? Builders.containerBuilder()
149             : Builders.containerBuilder(childSizeHint));
150     }
151
152     @Override
153     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
154         checkDataNodeContainer();
155         enter(name, UNKNOWN_SIZE == childSizeHint ? Builders.unkeyedListBuilder()
156             : Builders.unkeyedListBuilder(childSizeHint));
157     }
158
159     @Override
160     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) {
161         final NormalizedNodeBuilder<?, ?, ?> current = current();
162         checkArgument(current instanceof ImmutableUnkeyedListNodeBuilder
163             || current instanceof NormalizationResultBuilder);
164         enter(name, UNKNOWN_SIZE == childSizeHint ? Builders.unkeyedListEntryBuilder()
165             : Builders.unkeyedListEntryBuilder(childSizeHint));
166     }
167
168     @Override
169     public void startMapNode(final NodeIdentifier name, final int childSizeHint) {
170         checkDataNodeContainer();
171         enter(name, UNKNOWN_SIZE == childSizeHint ? Builders.mapBuilder() : Builders.mapBuilder(childSizeHint));
172     }
173
174     @Override
175     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint) {
176         final NormalizedNodeBuilder<?, ?, ?> current = current();
177         checkArgument(current instanceof ImmutableMapNodeBuilder || current instanceof ImmutableUserMapNodeBuilder
178             || current instanceof NormalizationResultBuilder);
179
180         enter(identifier, UNKNOWN_SIZE == childSizeHint ? Builders.mapEntryBuilder()
181             : Builders.mapEntryBuilder(childSizeHint));
182     }
183
184     @Override
185     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
186         checkDataNodeContainer();
187         enter(name, UNKNOWN_SIZE == childSizeHint ? Builders.orderedMapBuilder()
188             : Builders.orderedMapBuilder(childSizeHint));
189     }
190
191     @Override
192     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
193         checkDataNodeContainer();
194         enter(name, UNKNOWN_SIZE == childSizeHint ? Builders.choiceBuilder() : Builders.choiceBuilder(childSizeHint));
195     }
196
197     @Override
198     public void flush() {
199         // no-op
200     }
201
202     @Override
203     public void close() {
204         // no-op
205     }
206
207     @Override
208     public void nextDataSchemaNode(final DataSchemaNode schema) {
209         nextSchema = requireNonNull(schema);
210     }
211
212     @Override
213     public void scalarValue(final Object value) {
214         currentScalar().withValue(value);
215     }
216
217     @Override
218     public void domSourceValue(final DOMSource value) {
219         currentScalar().withValue(value);
220     }
221
222     @Override
223     @SuppressWarnings("rawtypes")
224     public void endNode() {
225         final NormalizedNodeBuilder finishedBuilder = builders.poll();
226         checkState(finishedBuilder != null, "Node which should be closed does not exists.");
227         final NormalizedNode product = finishedBuilder.build();
228         nextSchema = null;
229
230         writeChild(product);
231     }
232
233     @Override
234     public boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
235         checkDataNodeContainer();
236         enter(name, Builders.anydataBuilder(objectModel));
237         // We support all object models
238         return true;
239     }
240
241     /**
242      * Add a child not to the currently-open builder.
243      *
244      * @param child A new child
245      * @throws NullPointerException if {@code child} is null
246      * @throws IllegalStateException if there is no open builder
247      */
248     @SuppressWarnings({ "rawtypes", "unchecked" })
249     protected final void writeChild(final NormalizedNode child) {
250         final NormalizedNodeContainerBuilder current = currentContainer();
251         checkState(current != null, "Reached top level node, which could not be closed in this writer.");
252         current.addChild(requireNonNull(child));
253     }
254
255     // Exposed for ImmutableMetadataNormalizedNodeStreamWriter
256     @SuppressWarnings("rawtypes")
257     void enter(final PathArgument identifier, final NormalizedNodeBuilder next) {
258         builders.push(next.withNodeIdentifier(identifier));
259         nextSchema = null;
260     }
261
262     // Exposed for ImmutableMetadataNormalizedNodeStreamWriter
263     protected final NormalizedNodeBuilder popBuilder() {
264         return builders.pop();
265     }
266
267     final void reset(final NormalizationResultBuilder builder) {
268         nextSchema = null;
269         builders.clear();
270         builders.push(builder);
271     }
272
273     private <T> ImmutableLeafNodeBuilder<T> leafNodeBuilder(final DataSchemaNode schema) {
274         final InterningLeafNodeBuilder<T> interning = InterningLeafNodeBuilder.forSchema(schema);
275         return interning != null ? interning : leafNodeBuilder();
276     }
277
278     <T> ImmutableLeafNodeBuilder<T> leafNodeBuilder() {
279         return new ImmutableLeafNodeBuilder<>();
280     }
281
282     <T> ImmutableLeafSetEntryNodeBuilder<T> leafsetEntryNodeBuilder() {
283         return ImmutableLeafSetEntryNodeBuilder.create();
284     }
285
286     private void checkDataNodeContainer() {
287         @SuppressWarnings("rawtypes")
288         final NormalizedNodeContainerBuilder current = currentContainer();
289         if (!(current instanceof NormalizationResultBuilder)) {
290             checkArgument(current instanceof DataContainerNodeBuilder<?, ?>, "Invalid nesting of data.");
291         }
292     }
293
294     @SuppressWarnings("rawtypes")
295     private NormalizedNodeBuilder current() {
296         return builders.peek();
297     }
298
299     @SuppressWarnings("rawtypes")
300     private NormalizedNodeContainerBuilder currentContainer() {
301         final NormalizedNodeBuilder current = current();
302         if (current == null) {
303             return null;
304         }
305         checkState(current instanceof NormalizedNodeContainerBuilder, "%s is not a node container", current);
306         return (NormalizedNodeContainerBuilder) current;
307     }
308
309     @SuppressWarnings("rawtypes")
310     private NormalizedNodeBuilder currentScalar() {
311         final NormalizedNodeBuilder current = current();
312         checkState(!(current instanceof NormalizedNodeContainerBuilder), "Unexpected node container %s", current);
313         return current;
314     }
315 }