Merge "Remove unneeded build declarations in features"
[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.data.impl.schema.transform.base.AugmentationSchemaProxy;
26 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
28 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
29 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
31 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
35 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
39 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
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             for(final ChoiceCaseNode caze : ((ChoiceNode) parent).getCases()) {
151                 final DataSchemaNode potential = caze.getDataChildByName(qname);
152                 if(potential != null) {
153                     schema = potential;
154                     break;
155                 }
156             }
157         } else {
158             throw new IllegalStateException("Unsupported schema type "+ parent.getClass() +" on stack.");
159         }
160         Preconditions.checkArgument(schema != null, "Could not find schema for node %s in %s", qname, parent);
161         return schema;
162     }
163
164     public void startList(final PathArgument name) {
165         final SchemaNode schema = getSchema(name);
166         Preconditions.checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
167         schemaStack.push(schema);
168     }
169
170     public void startListItem(final PathArgument name) throws IOException {
171         final Object schema = getParent();
172         Preconditions.checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
173         schemaStack.push(schema);
174     }
175
176     public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
177         final SchemaNode schema = getSchema(name);
178
179         Preconditions.checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema.getPath());
180         return (LeafSchemaNode) schema;
181     }
182
183     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
184         final SchemaNode schema = getSchema(name);
185
186         Preconditions.checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema.getPath());
187         schemaStack.push(schema);
188         return (LeafListSchemaNode)schema;
189     }
190
191     public LeafListSchemaNode leafSetEntryNode() {
192         final Object parent = getParent();
193
194         Preconditions.checkArgument(parent instanceof LeafListSchemaNode, "Not currently in a leaf-list");
195         return (LeafListSchemaNode) parent;
196     }
197
198     public ChoiceNode startChoiceNode(final NodeIdentifier name) {
199         LOG.debug("Enter choice {}", name);
200         final SchemaNode schema = getSchema(name);
201
202         Preconditions.checkArgument(schema instanceof ChoiceNode, "Node %s is not a choice", schema.getPath());
203         schemaStack.push(schema);
204         return (ChoiceNode)schema;
205     }
206
207     public SchemaNode startContainerNode(final NodeIdentifier name) {
208         LOG.debug("Enter container {}", name);
209         final SchemaNode schema = getSchema(name);
210
211         boolean isAllowed = schema instanceof ContainerSchemaNode;
212         isAllowed |= schema instanceof NotificationDefinition;
213
214         Preconditions.checkArgument(isAllowed, "Node %s is not a container nor a notification", schema.getPath());
215         schemaStack.push(schema);
216         return schema;
217     }
218
219     public AugmentationSchema startAugmentationNode(final AugmentationIdentifier identifier) {
220         LOG.debug("Enter augmentation {}", identifier);
221         final Object parent = getParent();
222
223         Preconditions.checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
224         Preconditions.checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer",parent);
225         final AugmentationSchema schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent, identifier.getPossibleChildNames());
226         final HashSet<DataSchemaNode> realChildSchemas = new HashSet<>();
227         for(final DataSchemaNode child : schema.getChildNodes()) {
228             realChildSchemas.add(((DataNodeContainer) parent).getDataChildByName(child.getQName()));
229         }
230         final AugmentationSchema resolvedSchema = new AugmentationSchemaProxy(schema, realChildSchemas);
231         schemaStack.push(resolvedSchema);
232         return resolvedSchema;
233     }
234
235     public AnyXmlSchemaNode anyxmlNode(final NodeIdentifier name) {
236         final SchemaNode schema = getSchema(name);
237
238         Preconditions.checkArgument(schema instanceof AnyXmlSchemaNode, "Node %s is not anyxml", schema.getPath());
239         return (AnyXmlSchemaNode)schema;
240     }
241
242     public Object endNode() {
243         return schemaStack.pop();
244     }
245
246     private static final class SchemaNodePredicate implements Predicate<SchemaNode> {
247         private final QName qname;
248
249         public SchemaNodePredicate(final QName qname) {
250             this.qname = qname;
251         }
252
253         @Override
254         public boolean apply(final SchemaNode input) {
255             return input.getQName().equals(qname);
256         }
257     }
258 }