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