Convert to using requireNonNull()
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / listeners / ListenerAdapter.java
1 /*
2  * Copyright (c) 2014, 2016 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.restconf.nb.rfc8040.streams.listeners;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.base.MoreObjects;
15 import java.io.IOException;
16 import java.time.Instant;
17 import java.util.Collection;
18 import java.util.Map.Entry;
19 import java.util.Optional;
20 import javax.xml.stream.XMLStreamException;
21 import javax.xml.transform.dom.DOMResult;
22 import org.json.XML;
23 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
24 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
35 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
36 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
37 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Document;
44 import org.w3c.dom.Element;
45 import org.w3c.dom.Node;
46
47 /**
48  * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source.
49  */
50 public class ListenerAdapter extends AbstractCommonSubscriber implements ClusteredDOMDataTreeChangeListener {
51
52     private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class);
53
54     private final YangInstanceIdentifier path;
55     private final String streamName;
56     private final NotificationOutputType outputType;
57
58     /**
59      * Creates new {@link ListenerAdapter} listener specified by path and stream name and register for subscribing.
60      *
61      * @param path       Path to data in data store.
62      * @param streamName The name of the stream.
63      * @param outputType Type of output on notification (JSON, XML).
64      */
65     ListenerAdapter(final YangInstanceIdentifier path, final String streamName,
66             final NotificationOutputType outputType) {
67         setLocalNameOfPath(path.getLastPathArgument().getNodeType().getLocalName());
68
69         this.outputType = requireNonNull(outputType);
70         this.path = requireNonNull(path);
71         this.streamName = requireNonNull(streamName);
72         checkArgument(!streamName.isEmpty());
73     }
74
75     @Override
76     public void onDataTreeChanged(final Collection<DataTreeCandidate> dataTreeCandidates) {
77         final Instant now = Instant.now();
78         if (!checkStartStop(now, this)) {
79             return;
80         }
81
82         final String xml = prepareXml(dataTreeCandidates);
83         if (checkFilter(xml)) {
84             prepareAndPostData(xml);
85         }
86     }
87
88     /**
89      * Gets the name of the stream.
90      *
91      * @return The name of the stream.
92      */
93     @Override
94     public String getStreamName() {
95         return this.streamName;
96     }
97
98     @Override
99     public String getOutputType() {
100         return this.outputType.getName();
101     }
102
103     /**
104      * Get path pointed to data in data store.
105      *
106      * @return Path pointed to data in data store.
107      */
108     public YangInstanceIdentifier getPath() {
109         return this.path;
110     }
111
112     /**
113      * Prepare data of notification and data to client.
114      *
115      * @param xml XML-formatted data.
116      */
117     private void prepareAndPostData(final String xml) {
118         if (this.outputType.equals(NotificationOutputType.JSON)) {
119             post(XML.toJSONObject(xml).toString());
120         } else {
121             post(xml);
122         }
123     }
124
125     /**
126      * Prepare data in printable form and transform it to String.
127      *
128      * @param dataTreeCandidates Data-tree candidates to be transformed.
129      * @return Data in printable form.
130      */
131     private String prepareXml(final Collection<DataTreeCandidate> dataTreeCandidates) {
132         final SchemaContext schemaContext = schemaHandler.get();
133         final DataSchemaContextTree dataContextTree = DataSchemaContextTree.from(schemaContext);
134         final Document doc = createDocument();
135         final Element notificationElement = basePartDoc(doc);
136
137         final Element dataChangedNotificationEventElement = doc.createElementNS(
138                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "data-changed-notification");
139
140         addValuesToDataChangedNotificationEventElement(doc, dataChangedNotificationEventElement, dataTreeCandidates,
141                 schemaContext, dataContextTree);
142         notificationElement.appendChild(dataChangedNotificationEventElement);
143         return transformDoc(doc);
144     }
145
146     /**
147      * Adds values to data changed notification event element.
148      */
149     @SuppressWarnings("checkstyle:hiddenField")
150     private void addValuesToDataChangedNotificationEventElement(final Document doc,
151             final Element dataChangedNotificationEventElement, final Collection<DataTreeCandidate> dataTreeCandidates,
152             final SchemaContext schemaContext, final DataSchemaContextTree dataSchemaContextTree) {
153
154         for (DataTreeCandidate dataTreeCandidate : dataTreeCandidates) {
155             DataTreeCandidateNode candidateNode = dataTreeCandidate.getRootNode();
156             if (candidateNode == null) {
157                 continue;
158             }
159             YangInstanceIdentifier yiid = dataTreeCandidate.getRootPath();
160             addNodeToDataChangeNotificationEventElement(doc, dataChangedNotificationEventElement, candidateNode,
161                     yiid.getParent(), schemaContext, dataSchemaContextTree);
162         }
163     }
164
165     private void addNodeToDataChangeNotificationEventElement(final Document doc,
166             final Element dataChangedNotificationEventElement, final DataTreeCandidateNode candidateNode,
167             final YangInstanceIdentifier parentYiid, final SchemaContext schemaContext,
168             final DataSchemaContextTree dataSchemaContextTree) {
169
170         Optional<NormalizedNode<?, ?>> optionalNormalizedNode = Optional.empty();
171         switch (candidateNode.getModificationType()) {
172             case APPEARED:
173             case SUBTREE_MODIFIED:
174             case WRITE:
175                 optionalNormalizedNode = candidateNode.getDataAfter();
176                 break;
177             case DELETE:
178             case DISAPPEARED:
179                 optionalNormalizedNode = candidateNode.getDataBefore();
180                 break;
181             case UNMODIFIED:
182             default:
183                 break;
184         }
185
186         if (!optionalNormalizedNode.isPresent()) {
187             LOG.error("No node present in notification for {}", candidateNode);
188             return;
189         }
190
191         NormalizedNode<?, ?> normalizedNode = optionalNormalizedNode.get();
192         YangInstanceIdentifier yiid = YangInstanceIdentifier.builder(parentYiid)
193                 .append(normalizedNode.getIdentifier()).build();
194
195         final Optional<DataSchemaContextNode<?>> childrenSchemaNode = dataSchemaContextTree.findChild(yiid);
196         checkState(childrenSchemaNode.isPresent());
197         boolean isNodeMixin = childrenSchemaNode.get().isMixin();
198         boolean isSkippedNonLeaf = getLeafNodesOnly() && !(normalizedNode instanceof LeafNode);
199         if (!isNodeMixin && !isSkippedNonLeaf) {
200             Node node = null;
201             switch (candidateNode.getModificationType()) {
202                 case APPEARED:
203                 case SUBTREE_MODIFIED:
204                 case WRITE:
205                     Operation op = candidateNode.getDataBefore().isPresent() ? Operation.UPDATED : Operation.CREATED;
206                     node = createCreatedChangedDataChangeEventElement(doc, yiid, normalizedNode, op,
207                             schemaContext, dataSchemaContextTree);
208                     break;
209                 case DELETE:
210                 case DISAPPEARED:
211                     node = createDataChangeEventElement(doc, yiid, schemaContext);
212                     break;
213                 case UNMODIFIED:
214                 default:
215                     break;
216             }
217             if (node != null) {
218                 dataChangedNotificationEventElement.appendChild(node);
219             }
220         }
221
222         for (DataTreeCandidateNode childNode : candidateNode.getChildNodes()) {
223             addNodeToDataChangeNotificationEventElement(
224                     doc, dataChangedNotificationEventElement, childNode, yiid, schemaContext, dataSchemaContextTree);
225         }
226     }
227
228     /**
229      * Creates data-changed event element from data.
230      *
231      * @param doc           {@link Document}
232      * @param schemaContext Schema context.
233      * @return {@link Node} represented by changed event element.
234      */
235     private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier eventPath,
236             final SchemaContext schemaContext) {
237         final Element dataChangeEventElement = doc.createElement("data-change-event");
238         final Element pathElement = doc.createElement("path");
239         addPathAsValueToElement(eventPath, pathElement, schemaContext);
240         dataChangeEventElement.appendChild(pathElement);
241
242         final Element operationElement = doc.createElement("operation");
243         operationElement.setTextContent(Operation.DELETED.value);
244         dataChangeEventElement.appendChild(operationElement);
245
246         return dataChangeEventElement;
247     }
248
249     private Node createCreatedChangedDataChangeEventElement(final Document doc, final YangInstanceIdentifier eventPath,
250             final NormalizedNode<?, ?> normalized, final Operation operation, final SchemaContext schemaContext,
251             final DataSchemaContextTree dataSchemaContextTree) {
252         final Element dataChangeEventElement = doc.createElement("data-change-event");
253         final Element pathElement = doc.createElement("path");
254         addPathAsValueToElement(eventPath, pathElement, schemaContext);
255         dataChangeEventElement.appendChild(pathElement);
256
257         final Element operationElement = doc.createElement("operation");
258         operationElement.setTextContent(operation.value);
259         dataChangeEventElement.appendChild(operationElement);
260
261         try {
262             SchemaPath nodePath;
263             final Optional<DataSchemaContextNode<?>> childrenSchemaNode = dataSchemaContextTree.findChild(eventPath);
264             checkState(childrenSchemaNode.isPresent());
265             if (normalized instanceof MapEntryNode || normalized instanceof UnkeyedListEntryNode) {
266                 nodePath = childrenSchemaNode.get().getDataSchemaNode().getPath();
267             } else {
268                 nodePath = childrenSchemaNode.get().getDataSchemaNode().getPath().getParent();
269             }
270             final DOMResult domResult = writeNormalizedNode(normalized, schemaContext, nodePath);
271             final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
272             final Element dataElement = doc.createElement("data");
273             dataElement.appendChild(result);
274             dataChangeEventElement.appendChild(dataElement);
275         } catch (final IOException e) {
276             LOG.error("Error in writer ", e);
277         } catch (final XMLStreamException e) {
278             LOG.error("Error processing stream", e);
279         }
280
281         return dataChangeEventElement;
282     }
283
284     /**
285      * Adds path as value to element.
286      *
287      * @param eventPath     Path to data in data store.
288      * @param element       {@link Element}
289      * @param schemaContext Schema context.
290      */
291     @SuppressWarnings("rawtypes")
292     private void addPathAsValueToElement(final YangInstanceIdentifier eventPath, final Element element,
293             final SchemaContext schemaContext) {
294         final StringBuilder textContent = new StringBuilder();
295
296         for (final PathArgument pathArgument : eventPath.getPathArguments()) {
297             if (pathArgument instanceof YangInstanceIdentifier.AugmentationIdentifier) {
298                 continue;
299             }
300             textContent.append("/");
301             writeIdentifierWithNamespacePrefix(textContent, pathArgument.getNodeType(), schemaContext);
302             if (pathArgument instanceof NodeIdentifierWithPredicates) {
303                 for (final Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) pathArgument).entrySet()) {
304                     final QName keyValue = entry.getKey();
305                     final String predicateValue = String.valueOf(entry.getValue());
306                     textContent.append("[");
307                     writeIdentifierWithNamespacePrefix(textContent, keyValue, schemaContext);
308                     textContent.append("='");
309                     textContent.append(predicateValue);
310                     textContent.append("'");
311                     textContent.append("]");
312                 }
313             } else if (pathArgument instanceof NodeWithValue) {
314                 textContent.append("[.='");
315                 textContent.append(((NodeWithValue) pathArgument).getValue());
316                 textContent.append("'");
317                 textContent.append("]");
318             }
319         }
320         element.setTextContent(textContent.toString());
321     }
322
323     /**
324      * Writes identifier that consists of prefix and QName.
325      *
326      * @param textContent   Text builder that should be supplemented by QName and its modules name.
327      * @param qualifiedName QName of the element.
328      * @param schemaContext Schema context that holds modules which should contain module specified in QName.
329      */
330     private static void writeIdentifierWithNamespacePrefix(final StringBuilder textContent, final QName qualifiedName,
331             final SchemaContext schemaContext) {
332         final Optional<Module> module = schemaContext.findModule(qualifiedName.getModule());
333         if (module.isPresent()) {
334             textContent.append(module.get().getName());
335             textContent.append(":");
336             textContent.append(qualifiedName.getLocalName());
337         } else {
338             LOG.error("Cannot write identifier with namespace prefix in data-change listener adapter: "
339                     + "Cannot find module in schema context for input QName {}.", qualifiedName);
340             throw new IllegalStateException(String.format("Cannot find module in schema context for input QName %s.",
341                     qualifiedName));
342         }
343     }
344
345     /**
346      * Consists of three types {@link Operation#CREATED}, {@link Operation#UPDATED} and {@link Operation#DELETED}.
347      */
348     private enum Operation {
349         CREATED("created"),
350         UPDATED("updated"),
351         DELETED("deleted");
352
353         private final String value;
354
355         Operation(final String value) {
356             this.value = value;
357         }
358     }
359
360     @Override
361     public String toString() {
362         return MoreObjects.toStringHelper(this)
363                 .add("path", path)
364                 .add("stream-name", streamName)
365                 .add("output-type", outputType)
366                 .toString();
367     }
368 }