BUG 2413 - tracking in yang grouping
[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.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * Utility class for tracking the underlying state of the underlying
47  * schema node.
48  */
49 @Beta
50 public final class SchemaTracker {
51     private static final Logger LOG = LoggerFactory.getLogger(SchemaTracker.class);
52     private final Deque<Object> schemaStack = new ArrayDeque<>();
53     private final DataNodeContainer root;
54
55     private SchemaTracker(final SchemaContext context, final SchemaPath path) {
56         SchemaNode current = Preconditions.checkNotNull(context);
57         for (final QName qname : path.getPathFromRoot()) {
58             SchemaNode child;
59             if(current instanceof DataNodeContainer) {
60                 child = ((DataNodeContainer) current).getDataChildByName(qname);
61
62                 if (child == null && current instanceof SchemaContext) {
63                     child = tryFindGroupings((SchemaContext) current, qname).orNull();
64                 }
65
66                 if(child == null && current instanceof SchemaContext) {
67                     child = tryFindNotification((SchemaContext) current, qname)
68                             .orNull();
69                 }
70             } else if (current instanceof ChoiceNode) {
71                 child = ((ChoiceNode) current).getCaseNodeByName(qname);
72             } else {
73                 throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", current));
74             }
75             current = child;
76         }
77         Preconditions.checkArgument(current instanceof DataNodeContainer,"Schema path must point to container or list. Supplied path %s pointed to: %s",path,current);
78         root = (DataNodeContainer) current;
79     }
80
81     private Optional<SchemaNode> tryFindGroupings(final SchemaContext ctx, final QName qname) {
82         return Optional.<SchemaNode> fromNullable(Iterables.find(ctx.getGroupings(), new SchemaNodePredicate(qname), null));
83     }
84
85     private Optional<SchemaNode> tryFindNotification(final SchemaContext ctx, final QName qname) {
86         return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getNotifications(), new SchemaNodePredicate(qname), null));
87     }
88
89     /**
90      * Create a new writer with the specified context as its root.
91      *
92      * @param context Associated {@link SchemaContext}.
93      * @return A new {@link NormalizedNodeStreamWriter}
94      */
95     public static SchemaTracker create(final SchemaContext context) {
96         return create(context, SchemaPath.ROOT);
97     }
98
99     /**
100      * Create a new writer with the specified context and rooted in the specified schema path
101      *
102      * @param context Associated {@link SchemaContext}
103      * @param path schema path
104      *
105      * @return A new {@link NormalizedNodeStreamWriter}
106      */
107     public static SchemaTracker create(final SchemaContext context, final SchemaPath path) {
108         return new SchemaTracker(context, path);
109     }
110
111     public Object getParent() {
112         if (schemaStack.isEmpty()) {
113             return root;
114         }
115         return schemaStack.peek();
116     }
117
118     private SchemaNode getSchema(final PathArgument name) {
119         final Object parent = getParent();
120         SchemaNode schema = null;
121         final QName qname = name.getNodeType();
122         if(parent instanceof DataNodeContainer) {
123             schema = ((DataNodeContainer)parent).getDataChildByName(qname);
124
125             if(schema == null && parent instanceof GroupingDefinition) {
126                 schema = ((GroupingDefinition) parent);
127             }
128
129             if(schema == null && parent instanceof NotificationDefinition) {
130                 schema = ((NotificationDefinition) parent);
131             }
132         } else if(parent instanceof ChoiceNode) {
133             for(final ChoiceCaseNode caze : ((ChoiceNode) parent).getCases()) {
134                 final DataSchemaNode potential = caze.getDataChildByName(qname);
135                 if(potential != null) {
136                     schema = potential;
137                     break;
138                 }
139             }
140         } else {
141             throw new IllegalStateException("Unsupported schema type "+ parent.getClass() +" on stack.");
142         }
143         Preconditions.checkArgument(schema != null, "Could not find schema for node %s in %s", qname, parent);
144         return schema;
145     }
146
147     public void startList(final PathArgument name) {
148         final SchemaNode schema = getSchema(name);
149         Preconditions.checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
150         schemaStack.push(schema);
151     }
152
153     public void startListItem(final PathArgument name) throws IOException {
154         final Object schema = getParent();
155         Preconditions.checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
156         schemaStack.push(schema);
157     }
158
159     public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
160         final SchemaNode schema = getSchema(name);
161
162         Preconditions.checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema.getPath());
163         return (LeafSchemaNode) schema;
164     }
165
166     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
167         final SchemaNode schema = getSchema(name);
168
169         Preconditions.checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema.getPath());
170         schemaStack.push(schema);
171         return (LeafListSchemaNode)schema;
172     }
173
174     public LeafListSchemaNode leafSetEntryNode() {
175         final Object parent = getParent();
176
177         Preconditions.checkArgument(parent instanceof LeafListSchemaNode, "Not currently in a leaf-list");
178         return (LeafListSchemaNode) parent;
179     }
180
181     public ChoiceNode startChoiceNode(final NodeIdentifier name) {
182         LOG.debug("Enter choice {}", name);
183         final SchemaNode schema = getSchema(name);
184
185         Preconditions.checkArgument(schema instanceof ChoiceNode, "Node %s is not a choice", schema.getPath());
186         schemaStack.push(schema);
187         return (ChoiceNode)schema;
188     }
189
190     public SchemaNode startContainerNode(final NodeIdentifier name) {
191         LOG.debug("Enter container {}", name);
192         final SchemaNode schema = getSchema(name);
193
194         boolean isAllowed = schema instanceof ContainerSchemaNode;
195         isAllowed |= schema instanceof NotificationDefinition;
196
197         Preconditions.checkArgument(isAllowed, "Node %s is not a container nor a notification", schema.getPath());
198         schemaStack.push(schema);
199         return schema;
200     }
201
202     public AugmentationSchema startAugmentationNode(final AugmentationIdentifier identifier) {
203         LOG.debug("Enter augmentation {}", identifier);
204         final Object parent = getParent();
205
206         Preconditions.checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
207         Preconditions.checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer",parent);
208         final AugmentationSchema schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent, identifier.getPossibleChildNames());
209         final HashSet<DataSchemaNode> realChildSchemas = new HashSet<>();
210         for(final DataSchemaNode child : schema.getChildNodes()) {
211             realChildSchemas.add(((DataNodeContainer) parent).getDataChildByName(child.getQName()));
212         }
213         final AugmentationSchema resolvedSchema = new AugmentationSchemaProxy(schema, realChildSchemas);
214         schemaStack.push(resolvedSchema);
215         return resolvedSchema;
216     }
217
218     public AnyXmlSchemaNode anyxmlNode(final NodeIdentifier name) {
219         final SchemaNode schema = getSchema(name);
220
221         Preconditions.checkArgument(schema instanceof AnyXmlSchemaNode, "Node %s is not anyxml", schema.getPath());
222         return (AnyXmlSchemaNode)schema;
223     }
224
225     public Object endNode() {
226         return schemaStack.pop();
227     }
228
229     private static final class SchemaNodePredicate implements Predicate<SchemaNode> {
230         private final QName qname;
231
232         public SchemaNodePredicate(final QName qname) {
233             this.qname = qname;
234         }
235
236         @Override
237         public boolean apply(final SchemaNode input) {
238             return input.getQName().equals(qname);
239         }
240     }
241 }