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