2 * Copyright (c) 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.annotations.VisibleForTesting;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.Preconditions;
13 import com.google.gson.JsonObject;
14 import com.google.gson.JsonParser;
15 import java.io.IOException;
16 import java.io.StringWriter;
17 import java.io.Writer;
18 import java.time.Instant;
19 import javax.xml.stream.XMLStreamException;
20 import javax.xml.transform.dom.DOMResult;
21 import org.opendaylight.mdsal.dom.api.DOMNotification;
22 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
23 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
24 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
25 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
26 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
27 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
28 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.w3c.dom.Document;
34 import org.w3c.dom.Element;
35 import org.w3c.dom.Node;
38 * {@link NotificationListenerAdapter} is responsible to track events on notifications.
40 public class NotificationListenerAdapter extends AbstractCommonSubscriber implements DOMNotificationListener {
42 private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
44 private final String streamName;
45 private final SchemaPath path;
46 private final String outputType;
49 * Set path of listener and stream name, register event bus.
51 * @param path Schema path of YANG notification.
52 * @param streamName Name of the stream.
53 * @param outputType Type of output on notification (JSON or XML).
55 NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType) {
57 setLocalNameOfPath(path.getLastComponent().getLocalName());
59 this.outputType = Preconditions.checkNotNull(outputType);
60 this.path = Preconditions.checkNotNull(path);
61 Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
62 this.streamName = streamName;
66 * Get output type of this listener.
68 * @return The configured output type (JSON or XML).
71 public String getOutputType() {
72 return this.outputType;
76 public void onNotification(final DOMNotification notification) {
77 final Instant now = Instant.now();
78 if (!checkStartStop(now, this)) {
82 final SchemaContext schemaContext = schemaHandler.get();
83 final String xml = prepareXml(schemaContext, notification);
84 if (checkFilter(xml)) {
85 prepareAndPostData(outputType.equals("JSON") ? prepareJson(schemaContext, notification) : xml);
90 * Get stream name of this listener.
92 * @return The configured stream name.
95 public String getStreamName() {
96 return this.streamName;
100 * Get schema path of notification.
102 * @return The configured schema path that points to observing YANG notification schema node.
104 public SchemaPath getSchemaPath() {
109 * Prepare data of notification and data to client.
111 * @param data JSON or XML data that holds notification data.
113 private void prepareAndPostData(final String data) {
114 final Event event = new Event(EventType.NOTIFY);
120 * Creation of JSON from notification data.
122 * @return Transformed notification data in JSON format.
125 String prepareJson(final SchemaContext schemaContext, final DOMNotification notification) {
126 final JsonParser jsonParser = new JsonParser();
127 final JsonObject json = new JsonObject();
128 json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString(schemaContext, notification)));
129 json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
130 return json.toString();
133 private static String writeBodyToString(final SchemaContext schemaContext, final DOMNotification notification) {
134 final Writer writer = new StringWriter();
135 final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
136 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
137 notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
138 final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
140 nodeWriter.write(notification.getBody());
142 } catch (final IOException e) {
143 throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
145 return writer.toString();
149 * Creation of XML from notification data.
151 * @return Transformed notification data in XML format.
153 private String prepareXml(final SchemaContext schemaContext, final DOMNotification notification) {
154 final Document doc = createDocument();
155 final Element notificationElement = basePartDoc(doc);
157 final Element notificationEventElement = doc.createElementNS(
158 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
159 addValuesToNotificationEventElement(doc, notificationEventElement, schemaContext, notification);
160 notificationElement.appendChild(notificationEventElement);
162 return transformDoc(doc);
165 private void addValuesToNotificationEventElement(final Document doc, final Element element,
166 final SchemaContext schemaContext, final DOMNotification notification) {
168 final DOMResult domResult = writeNormalizedNode(notification.getBody(), schemaContext, this.path);
169 final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
170 final Element dataElement = doc.createElement("notification");
171 dataElement.appendChild(result);
172 element.appendChild(dataElement);
173 } catch (final IOException e) {
174 LOG.error("Error in writer ", e);
175 } catch (final XMLStreamException e) {
176 LOG.error("Error processing stream", e);
181 public String toString() {
182 return MoreObjects.toStringHelper(this)
184 .add("stream-name", streamName)
185 .add("output-type", outputType)