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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.MoreObjects;
15 import com.google.gson.JsonObject;
16 import com.google.gson.JsonParser;
17 import java.io.IOException;
18 import java.io.StringWriter;
19 import java.io.Writer;
20 import java.time.Instant;
21 import javax.xml.stream.XMLStreamException;
22 import javax.xml.transform.dom.DOMResult;
23 import org.opendaylight.mdsal.dom.api.DOMNotification;
24 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
25 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
26 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
27 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
28 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
29 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
31 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.w3c.dom.Document;
36 import org.w3c.dom.Element;
37 import org.w3c.dom.Node;
40 * {@link NotificationListenerAdapter} is responsible to track events on notifications.
42 public class NotificationListenerAdapter extends AbstractCommonSubscriber implements DOMNotificationListener {
44 private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
46 private final String streamName;
47 private final Absolute path;
48 private final String outputType;
51 * Set path of listener and stream name.
53 * @param path Schema path of YANG notification.
54 * @param streamName Name of the stream.
55 * @param outputType Type of output on notification (JSON or XML).
57 NotificationListenerAdapter(final Absolute path, final String streamName, final String outputType) {
58 setLocalNameOfPath(path.lastNodeIdentifier().getLocalName());
60 this.outputType = requireNonNull(outputType);
61 this.path = requireNonNull(path);
62 this.streamName = requireNonNull(streamName);
63 checkArgument(!streamName.isEmpty());
67 * Get output type of this listener.
69 * @return The configured output type (JSON or XML).
72 public String getOutputType() {
73 return this.outputType;
77 public void onNotification(final DOMNotification notification) {
78 final Instant now = Instant.now();
79 if (!checkStartStop(now, this)) {
83 final EffectiveModelContext schemaContext = schemaHandler.get();
84 final String xml = prepareXml(schemaContext, notification);
85 if (checkFilter(xml)) {
86 post(outputType.equals("JSON") ? prepareJson(schemaContext, notification) : xml);
91 * Get stream name of this listener.
93 * @return The configured stream name.
96 public String getStreamName() {
97 return this.streamName;
101 * Get schema path of notification.
103 * @return The configured schema path that points to observing YANG notification schema node.
105 public Absolute getSchemaPath() {
110 * Creation of JSON from notification data.
112 * @return Transformed notification data in JSON format.
115 String prepareJson(final EffectiveModelContext schemaContext, final DOMNotification notification) {
116 final JsonParser jsonParser = new JsonParser();
117 final JsonObject json = new JsonObject();
118 json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString(schemaContext, notification)));
119 json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
120 return json.toString();
123 private static String writeBodyToString(final EffectiveModelContext schemaContext,
124 final DOMNotification notification) {
125 final Writer writer = new StringWriter();
126 final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
127 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
128 notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
129 final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
131 nodeWriter.write(notification.getBody());
133 } catch (final IOException e) {
134 throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
136 return writer.toString();
140 * Creation of XML from notification data.
142 * @return Transformed notification data in XML format.
144 private String prepareXml(final EffectiveModelContext schemaContext, final DOMNotification notification) {
145 final Document doc = createDocument();
146 final Element notificationElement = basePartDoc(doc);
148 final Element notificationEventElement = doc.createElementNS(
149 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
150 addValuesToNotificationEventElement(doc, notificationEventElement, schemaContext, notification);
151 notificationElement.appendChild(notificationEventElement);
153 return transformDoc(doc);
156 private void addValuesToNotificationEventElement(final Document doc, final Element element,
157 final EffectiveModelContext schemaContext, final DOMNotification notification) {
159 final DOMResult domResult = writeNormalizedNode(notification.getBody(), schemaContext, path.asSchemaPath());
160 final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
161 final Element dataElement = doc.createElement("notification");
162 dataElement.appendChild(result);
163 element.appendChild(dataElement);
164 } catch (final IOException e) {
165 LOG.error("Error in writer ", e);
166 } catch (final XMLStreamException e) {
167 LOG.error("Error processing stream", e);
172 public String toString() {
173 return MoreObjects.toStringHelper(this)
175 .add("stream-name", streamName)
176 .add("output-type", outputType)