9ce039cd1a4e93260dc646007d6dec6d697eb9f0
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / transformer / AbstractNormalizedNodePruner.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 package org.opendaylight.controller.cluster.datastore.node.utils.transformer;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import java.util.ArrayDeque;
14 import java.util.Deque;
15 import java.util.NoSuchElementException;
16 import java.util.Optional;
17 import javax.xml.transform.dom.DOMSource;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
25 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
29 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
30 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
31 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
32 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * The NormalizedNodePruner removes all nodes from the input NormalizedNode that do not have a corresponding
39  * schema element in the passed in SchemaContext.
40  */
41 abstract class AbstractNormalizedNodePruner implements NormalizedNodeStreamWriter {
42     enum State {
43         UNITIALIZED,
44         OPEN,
45         CLOSED;
46     }
47
48     private static final Logger LOG = LoggerFactory.getLogger(AbstractNormalizedNodePruner.class);
49
50     private final Deque<NormalizedNodeBuilderWrapper> stack = new ArrayDeque<>();
51     private final DataSchemaContextTree tree;
52
53     private DataSchemaContextNode<?> nodePathSchemaNode;
54     private State state = State.UNITIALIZED;
55
56     // FIXME: package-private to support unguarded NormalizedNodePruner access
57     NormalizedNode<?, ?> normalizedNode;
58
59     AbstractNormalizedNodePruner(final DataSchemaContextTree tree) {
60         this.tree = requireNonNull(tree);
61     }
62
63     AbstractNormalizedNodePruner(final SchemaContext schemaContext) {
64         this(DataSchemaContextTree.from(schemaContext));
65     }
66
67     final DataSchemaContextTree getTree() {
68         return tree;
69     }
70
71     final void initialize(final YangInstanceIdentifier nodePath) {
72         nodePathSchemaNode = tree.findChild(nodePath).orElse(null);
73         normalizedNode = null;
74         stack.clear();
75         state = State.OPEN;
76     }
77
78     @SuppressWarnings("unchecked")
79     @Override
80     public void leafNode(final NodeIdentifier nodeIdentifier, final Object value) {
81         checkNotSealed();
82
83         NormalizedNodeBuilderWrapper parent = stack.peek();
84         LeafNode<Object> leafNode = Builders.leafBuilder().withNodeIdentifier(nodeIdentifier).withValue(value).build();
85         if (parent != null) {
86             if (hasValidSchema(nodeIdentifier.getNodeType(), parent)) {
87                 parent.builder().addChild(leafNode);
88             }
89         } else {
90             // If there's no parent node then this is a stand alone LeafNode.
91             if (nodePathSchemaNode != null) {
92                 this.normalizedNode = leafNode;
93             }
94
95             state = State.CLOSED;
96         }
97     }
98
99     @Override
100     public void startLeafSet(final NodeIdentifier nodeIdentifier, final int count) {
101         addBuilder(Builders.leafSetBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier);
102     }
103
104     @Override
105     public void startOrderedLeafSet(final NodeIdentifier nodeIdentifier, final int str) {
106         addBuilder(Builders.orderedLeafSetBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier);
107     }
108
109     @SuppressWarnings("unchecked")
110     @Override
111     public void leafSetEntryNode(final QName name, final Object value) {
112         checkNotSealed();
113
114         NormalizedNodeBuilderWrapper parent = stack.peek();
115         if (parent != null) {
116             if (hasValidSchema(name, parent)) {
117                 parent.builder().addChild(Builders.leafSetEntryBuilder().withValue(value)
118                         .withNodeIdentifier(new NodeWithValue<>(parent.nodeType(), value))
119                         .build());
120             }
121         } else {
122             // If there's no parent LeafSetNode then this is a stand alone
123             // LeafSetEntryNode.
124             if (nodePathSchemaNode != null) {
125                 this.normalizedNode = Builders.leafSetEntryBuilder().withValue(value).withNodeIdentifier(
126                         new NodeWithValue<>(name, value)).build();
127             }
128
129             state = State.CLOSED;
130         }
131     }
132
133     @Override
134     public void startContainerNode(final NodeIdentifier nodeIdentifier, final int count) {
135         addBuilder(Builders.containerBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier);
136     }
137
138     @Override
139     public void startYangModeledAnyXmlNode(final NodeIdentifier nodeIdentifier, final int count) {
140         throw new UnsupportedOperationException("Not implemented yet");
141     }
142
143     @Override
144     public void startUnkeyedList(final NodeIdentifier nodeIdentifier, final int count) {
145         addBuilder(Builders.unkeyedListBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier);
146     }
147
148     @Override
149     public void startUnkeyedListItem(final NodeIdentifier nodeIdentifier, final int count) {
150         addBuilder(Builders.unkeyedListEntryBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier);
151     }
152
153     @Override
154     public void startMapNode(final NodeIdentifier nodeIdentifier, final int count) {
155         addBuilder(Builders.mapBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier);
156     }
157
158     @Override
159     public void startMapEntryNode(final NodeIdentifierWithPredicates nodeIdentifierWithPredicates, final int count) {
160         addBuilder(Builders.mapEntryBuilder().withNodeIdentifier(nodeIdentifierWithPredicates),
161                 nodeIdentifierWithPredicates);
162     }
163
164     @Override
165     public void startOrderedMapNode(final NodeIdentifier nodeIdentifier, final int count) {
166         addBuilder(Builders.orderedMapBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier);
167     }
168
169     @Override
170     public void startChoiceNode(final NodeIdentifier nodeIdentifier, final int count) {
171         addBuilder(Builders.choiceBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier);
172     }
173
174     @Override
175     public void startAugmentationNode(final AugmentationIdentifier augmentationIdentifier) {
176         addBuilder(Builders.augmentationBuilder().withNodeIdentifier(augmentationIdentifier), augmentationIdentifier);
177     }
178
179     @SuppressWarnings("unchecked")
180     @Override
181     public void anyxmlNode(final NodeIdentifier nodeIdentifier, final Object value) {
182         checkNotSealed();
183
184         NormalizedNodeBuilderWrapper parent = stack.peek();
185         AnyXmlNode anyXmlNode = Builders.anyXmlBuilder().withNodeIdentifier(nodeIdentifier).withValue((DOMSource) value)
186                 .build();
187         if (parent != null) {
188             if (hasValidSchema(nodeIdentifier.getNodeType(), parent)) {
189                 parent.builder().addChild(anyXmlNode);
190             }
191         } else {
192             // If there's no parent node then this is a stand alone AnyXmlNode.
193             if (nodePathSchemaNode != null) {
194                 this.normalizedNode = anyXmlNode;
195             }
196
197             state = State.CLOSED;
198         }
199     }
200
201     @SuppressWarnings("unchecked")
202     @Override
203     public void endNode() {
204         checkNotSealed();
205
206         final NormalizedNodeBuilderWrapper child;
207         try {
208             child = stack.pop();
209         } catch (NoSuchElementException e) {
210             throw new IllegalStateException("endNode called on an empty stack", e);
211         }
212
213         if (child.getSchema() == null) {
214             LOG.debug("Schema not found for {}", child.identifier());
215             if (stack.isEmpty()) {
216                 normalizedNode = null;
217                 state = State.CLOSED;
218             }
219             return;
220         }
221
222         final NormalizedNode<?, ?> newNode = child.builder().build();
223         final NormalizedNodeBuilderWrapper parent = stack.peek();
224         if (parent == null) {
225             normalizedNode = newNode;
226             state = State.CLOSED;
227         } else {
228             parent.builder().addChild(newNode);
229         }
230     }
231
232     @Override
233     public void close() {
234         state = State.CLOSED;
235         stack.clear();
236     }
237
238     @Override
239     public void flush() {
240         // No-op
241     }
242
243     /**
244      * Return the resulting normalized node.
245      *
246      * @return Resulting node for the path, if it was not pruned
247      * @throws IllegalStateException if this pruner has not been closed
248      */
249     public final Optional<NormalizedNode<?, ?>> getResult() {
250         checkState(state == State.CLOSED, "Cannot get result in state %s", state);
251         return Optional.ofNullable(normalizedNode);
252     }
253
254     private void checkNotSealed() {
255         checkState(state == State.OPEN, "Illegal operation in state %s", state);
256     }
257
258     private static boolean hasValidSchema(final QName name, final NormalizedNodeBuilderWrapper parent) {
259         final DataSchemaContextNode<?> parentSchema = parent.getSchema();
260         final boolean valid = parentSchema != null && parentSchema.getChild(name) != null;
261         if (!valid) {
262             LOG.debug("Schema not found for {}", name);
263         }
264
265         return valid;
266     }
267
268     private NormalizedNodeBuilderWrapper addBuilder(final NormalizedNodeContainerBuilder<?, ?, ?, ?> builder,
269             final PathArgument identifier) {
270         checkNotSealed();
271
272         final DataSchemaContextNode<?> schemaNode;
273         final NormalizedNodeBuilderWrapper parent = stack.peek();
274         if (parent != null) {
275             final DataSchemaContextNode<?> parentSchema = parent.getSchema();
276             schemaNode = parentSchema == null ? null : parentSchema.getChild(identifier);
277         } else {
278             schemaNode = nodePathSchemaNode;
279         }
280
281         NormalizedNodeBuilderWrapper wrapper = new NormalizedNodeBuilderWrapper(builder, identifier, schemaNode);
282         stack.push(wrapper);
283         return wrapper;
284     }
285 }