AnyXml NormalizedNode wraps a DOMSource value
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / SchemaTracker.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.codec;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicate;
14 import com.google.common.collect.Iterables;
15 import java.io.IOException;
16 import java.util.ArrayDeque;
17 import java.util.Deque;
18 import java.util.HashSet;
19 import org.opendaylight.yangtools.yang.common.QName;
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.PathArgument;
23 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
24 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
25 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
27 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
28 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
29 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
30 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
34 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
38 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * Utility class for tracking the underlying state of the underlying
48  * schema node.
49  */
50 @Beta
51 public final class SchemaTracker {
52     private static final Logger LOG = LoggerFactory.getLogger(SchemaTracker.class);
53     private final Deque<Object> schemaStack = new ArrayDeque<>();
54     private final DataNodeContainer root;
55
56     private SchemaTracker(final SchemaContext context, final SchemaPath path) {
57         SchemaNode current = Preconditions.checkNotNull(context);
58         for (final QName qname : path.getPathFromRoot()) {
59             SchemaNode child;
60             if(current instanceof DataNodeContainer) {
61                 child = ((DataNodeContainer) current).getDataChildByName(qname);
62
63                 if (child == null && current instanceof SchemaContext) {
64                     child = tryFindGroupings((SchemaContext) current, qname).orNull();
65                 }
66
67                 if(child == null && current instanceof SchemaContext) {
68                     child = tryFindNotification((SchemaContext) current, qname)
69                             .or(tryFindRpc(((SchemaContext) current), qname)).orNull();
70                 }
71             } else if (current instanceof ChoiceNode) {
72                 child = ((ChoiceNode) current).getCaseNodeByName(qname);
73             } else if (current instanceof RpcDefinition) {
74                 switch (qname.getLocalName()) {
75                     case "input":
76                         child = ((RpcDefinition) current).getInput();
77                         break;
78                     case "output":
79                         child = ((RpcDefinition) current).getOutput();
80                         break;
81                     default:
82                         child = null;
83                         break;
84                 }
85             } else {
86                 throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", current));
87             }
88             current = child;
89         }
90         Preconditions.checkArgument(current instanceof DataNodeContainer,"Schema path must point to container or list or an rpc input/output. Supplied path %s pointed to: %s",path,current);
91         root = (DataNodeContainer) current;
92     }
93
94     private Optional<SchemaNode> tryFindGroupings(final SchemaContext ctx, final QName qname) {
95         return Optional.<SchemaNode> fromNullable(Iterables.find(ctx.getGroupings(), new SchemaNodePredicate(qname), null));
96     }
97
98     private Optional<SchemaNode> tryFindRpc(final SchemaContext ctx, final QName qname) {
99         return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getOperations(), new SchemaNodePredicate(qname), null));
100     }
101
102     private Optional<SchemaNode> tryFindNotification(final SchemaContext ctx, final QName qname) {
103         return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getNotifications(), new SchemaNodePredicate(qname), null));
104     }
105
106     /**
107      * Create a new writer with the specified context as its root.
108      *
109      * @param context Associated {@link SchemaContext}.
110      * @return A new {@link NormalizedNodeStreamWriter}
111      */
112     public static SchemaTracker create(final SchemaContext context) {
113         return create(context, SchemaPath.ROOT);
114     }
115
116     /**
117      * Create a new writer with the specified context and rooted in the specified schema path
118      *
119      * @param context Associated {@link SchemaContext}
120      * @param path schema path
121      *
122      * @return A new {@link NormalizedNodeStreamWriter}
123      */
124     public static SchemaTracker create(final SchemaContext context, final SchemaPath path) {
125         return new SchemaTracker(context, path);
126     }
127
128     public Object getParent() {
129         if (schemaStack.isEmpty()) {
130             return root;
131         }
132         return schemaStack.peek();
133     }
134
135     private SchemaNode getSchema(final PathArgument name) {
136         final Object parent = getParent();
137         SchemaNode schema = null;
138         final QName qname = name.getNodeType();
139         if(parent instanceof DataNodeContainer) {
140             schema = ((DataNodeContainer)parent).getDataChildByName(qname);
141
142             if(schema == null && parent instanceof GroupingDefinition) {
143                 schema = ((GroupingDefinition) parent);
144             }
145
146             if(schema == null && parent instanceof NotificationDefinition) {
147                 schema = ((NotificationDefinition) parent);
148             }
149         } else if(parent instanceof ChoiceNode) {
150             schema = findChildInCases((ChoiceNode) parent, qname);
151         } else {
152             throw new IllegalStateException("Unsupported schema type "+ parent.getClass() +" on stack.");
153         }
154         Preconditions.checkArgument(schema != null, "Could not find schema for node %s in %s", qname, parent);
155         return schema;
156     }
157
158     private SchemaNode findChildInCases(final ChoiceNode parent, final QName qname) {
159         DataSchemaNode schema = null;
160         for(final ChoiceCaseNode caze : parent.getCases()) {
161             final DataSchemaNode potential = caze.getDataChildByName(qname);
162             if(potential != null) {
163                 schema = potential;
164                 break;
165             }
166         }
167         return schema;
168     }
169
170     private SchemaNode findCaseByChild(final ChoiceNode parent, final QName qname) {
171         DataSchemaNode schema = null;
172         for(final ChoiceCaseNode caze : parent.getCases()) {
173             final DataSchemaNode potential = caze.getDataChildByName(qname);
174             if(potential != null) {
175                 schema = caze;
176                 break;
177             }
178         }
179         return schema;
180     }
181
182     public void startList(final PathArgument name) {
183         final SchemaNode schema = getSchema(name);
184         Preconditions.checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
185         schemaStack.push(schema);
186     }
187
188     public void startListItem(final PathArgument name) throws IOException {
189         final Object schema = getParent();
190         Preconditions.checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
191         schemaStack.push(schema);
192     }
193
194     public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
195         final SchemaNode schema = getSchema(name);
196
197         Preconditions.checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema.getPath());
198         return (LeafSchemaNode) schema;
199     }
200
201     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
202         final SchemaNode schema = getSchema(name);
203
204         Preconditions.checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema.getPath());
205         schemaStack.push(schema);
206         return (LeafListSchemaNode)schema;
207     }
208
209     public LeafListSchemaNode leafSetEntryNode() {
210         final Object parent = getParent();
211
212         Preconditions.checkArgument(parent instanceof LeafListSchemaNode, "Not currently in a leaf-list");
213         return (LeafListSchemaNode) parent;
214     }
215
216     public ChoiceNode startChoiceNode(final NodeIdentifier name) {
217         LOG.debug("Enter choice {}", name);
218         final SchemaNode schema = getSchema(name);
219
220         Preconditions.checkArgument(schema instanceof ChoiceNode, "Node %s is not a choice", schema.getPath());
221         schemaStack.push(schema);
222         return (ChoiceNode)schema;
223     }
224
225     public SchemaNode startContainerNode(final NodeIdentifier name) {
226         LOG.debug("Enter container {}", name);
227         final SchemaNode schema = getSchema(name);
228
229         boolean isAllowed = schema instanceof ContainerSchemaNode;
230         isAllowed |= schema instanceof NotificationDefinition;
231
232         Preconditions.checkArgument(isAllowed, "Node %s is not a container nor a notification", schema.getPath());
233         schemaStack.push(schema);
234         return schema;
235     }
236
237     public AugmentationSchema startAugmentationNode(final AugmentationIdentifier identifier) {
238         LOG.debug("Enter augmentation {}", identifier);
239         Object parent = getParent();
240
241         Preconditions.checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
242         if(parent instanceof ChoiceNode) {
243             final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
244             parent = findCaseByChild((ChoiceNode) parent, name);
245         }
246         Preconditions.checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer",parent);
247         final AugmentationSchema schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent, identifier.getPossibleChildNames());
248         final HashSet<DataSchemaNode> realChildSchemas = new HashSet<>();
249         for(final DataSchemaNode child : schema.getChildNodes()) {
250             realChildSchemas.add(((DataNodeContainer) parent).getDataChildByName(child.getQName()));
251         }
252         final AugmentationSchema resolvedSchema = new EffectiveAugmentationSchema(schema, realChildSchemas);
253         schemaStack.push(resolvedSchema);
254         return resolvedSchema;
255     }
256
257     public AnyXmlSchemaNode anyxmlNode(final NodeIdentifier name) {
258         final SchemaNode schema = getSchema(name);
259
260         Preconditions.checkArgument(schema instanceof AnyXmlSchemaNode, "Node %s is not anyxml", schema.getPath());
261         return (AnyXmlSchemaNode)schema;
262     }
263
264     public Object endNode() {
265         return schemaStack.pop();
266     }
267
268     private static final class SchemaNodePredicate implements Predicate<SchemaNode> {
269         private final QName qname;
270
271         public SchemaNodePredicate(final QName qname) {
272             this.qname = qname;
273         }
274
275         @Override
276         public boolean apply(final SchemaNode input) {
277             return input.getQName().equals(qname);
278         }
279     }
280 }