2 * Copyright (c) 2014, 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.streams.listeners;
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;
16 import java.util.Map.Entry;
17 import java.util.Optional;
18 import javax.xml.stream.XMLStreamException;
19 import javax.xml.transform.dom.DOMResult;
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;
46 * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source.
48 public class ListenerAdapter extends AbstractCommonSubscriber implements ClusteredDOMDataTreeChangeListener {
50 private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class);
52 private final YangInstanceIdentifier path;
53 private final String streamName;
54 private final NotificationOutputType outputType;
57 * Creates new {@link ListenerAdapter} listener specified by path and stream name and register for subscribing.
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).
63 ListenerAdapter(final YangInstanceIdentifier path, final String streamName,
64 final NotificationOutputType outputType) {
65 setLocalNameOfPath(path.getLastPathArgument().getNodeType().getLocalName());
67 this.outputType = Preconditions.checkNotNull(outputType);
68 this.path = Preconditions.checkNotNull(path);
69 Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
70 this.streamName = streamName;
74 public void onDataTreeChanged(final Collection<DataTreeCandidate> dataTreeCandidates) {
75 final Instant now = Instant.now();
76 if (!checkStartStop(now, this)) {
80 final String xml = prepareXml(dataTreeCandidates);
81 if (checkFilter(xml)) {
82 prepareAndPostData(xml);
87 * Gets the name of the stream.
89 * @return The name of the stream.
92 public String getStreamName() {
93 return this.streamName;
97 public String getOutputType() {
98 return this.outputType.getName();
102 * Get path pointed to data in data store.
104 * @return Path pointed to data in data store.
106 public YangInstanceIdentifier getPath() {
111 * Prepare data of notification and data to client.
113 * @param xml XML-formatted data.
115 private void prepareAndPostData(final String xml) {
116 if (this.outputType.equals(NotificationOutputType.JSON)) {
117 post(XML.toJSONObject(xml).toString());
124 * Prepare data in printable form and transform it to String.
126 * @param dataTreeCandidates Data-tree candidates to be transformed.
127 * @return Data in printable form.
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);
135 final Element dataChangedNotificationEventElement = doc.createElementNS(
136 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "data-changed-notification");
138 addValuesToDataChangedNotificationEventElement(doc, dataChangedNotificationEventElement, dataTreeCandidates,
139 schemaContext, dataContextTree);
140 notificationElement.appendChild(dataChangedNotificationEventElement);
141 return transformDoc(doc);
145 * Adds values to data changed notification event element.
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) {
152 for (DataTreeCandidate dataTreeCandidate : dataTreeCandidates) {
153 DataTreeCandidateNode candidateNode = dataTreeCandidate.getRootNode();
154 if (candidateNode == null) {
157 YangInstanceIdentifier yiid = dataTreeCandidate.getRootPath();
158 addNodeToDataChangeNotificationEventElement(doc, dataChangedNotificationEventElement, candidateNode,
159 yiid.getParent(), schemaContext, dataSchemaContextTree);
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) {
168 Optional<NormalizedNode<?, ?>> optionalNormalizedNode = Optional.empty();
169 switch (candidateNode.getModificationType()) {
171 case SUBTREE_MODIFIED:
173 optionalNormalizedNode = candidateNode.getDataAfter();
177 optionalNormalizedNode = candidateNode.getDataBefore();
184 if (!optionalNormalizedNode.isPresent()) {
185 LOG.error("No node present in notification for {}", candidateNode);
189 NormalizedNode<?, ?> normalizedNode = optionalNormalizedNode.get();
190 YangInstanceIdentifier yiid = YangInstanceIdentifier.builder(parentYiid)
191 .append(normalizedNode.getIdentifier()).build();
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) {
199 switch (candidateNode.getModificationType()) {
201 case SUBTREE_MODIFIED:
203 Operation op = candidateNode.getDataBefore().isPresent() ? Operation.UPDATED : Operation.CREATED;
204 node = createCreatedChangedDataChangeEventElement(doc, yiid, normalizedNode, op,
205 schemaContext, dataSchemaContextTree);
209 node = createDataChangeEventElement(doc, yiid, schemaContext);
216 dataChangedNotificationEventElement.appendChild(node);
220 for (DataTreeCandidateNode childNode : candidateNode.getChildNodes()) {
221 addNodeToDataChangeNotificationEventElement(
222 doc, dataChangedNotificationEventElement, childNode, yiid, schemaContext, dataSchemaContextTree);
227 * Creates data-changed event element from data.
229 * @param doc {@link Document}
230 * @param schemaContext Schema context.
231 * @return {@link Node} represented by changed event element.
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);
240 final Element operationElement = doc.createElement("operation");
241 operationElement.setTextContent(Operation.DELETED.value);
242 dataChangeEventElement.appendChild(operationElement);
244 return dataChangeEventElement;
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);
255 final Element operationElement = doc.createElement("operation");
256 operationElement.setTextContent(operation.value);
257 dataChangeEventElement.appendChild(operationElement);
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();
266 nodePath = childrenSchemaNode.get().getDataSchemaNode().getPath().getParent();
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);
279 return dataChangeEventElement;
283 * Adds path as value to element.
285 * @param eventPath Path to data in data store.
286 * @param element {@link Element}
287 * @param schemaContext Schema context.
289 @SuppressWarnings("rawtypes")
290 private void addPathAsValueToElement(final YangInstanceIdentifier eventPath, final Element element,
291 final SchemaContext schemaContext) {
292 final StringBuilder textContent = new StringBuilder();
294 for (final PathArgument pathArgument : eventPath.getPathArguments()) {
295 if (pathArgument instanceof YangInstanceIdentifier.AugmentationIdentifier) {
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("]");
312 } else if (pathArgument instanceof NodeWithValue) {
313 textContent.append("[.='");
314 textContent.append(((NodeWithValue) pathArgument).getValue());
315 textContent.append("'");
316 textContent.append("]");
319 element.setTextContent(textContent.toString());
323 * Writes identifier that consists of prefix and QName.
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.
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());
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.",
345 * Consists of three types {@link Operation#CREATED}, {@link Operation#UPDATED} and {@link Operation#DELETED}.
347 private enum Operation {
352 private final String value;
354 Operation(final String value) {
360 public String toString() {
361 return MoreObjects.toStringHelper(this)
363 .add("stream-name", streamName)
364 .add("output-type", outputType)