Bump upstreams for Silicon
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / listeners / NotificationListenerAdapter.java
index 1a3e1e209389a9bbe239d81750a9f11c088cd281..c1cbdd98f80ac53ac1e8dc4904fb2d48b7218c35 100644 (file)
@@ -7,8 +7,11 @@
  */
 package org.opendaylight.restconf.nb.rfc8040.streams.listeners;
 
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Objects.requireNonNull;
+
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
+import com.google.common.base.MoreObjects;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;
 import java.io.IOException;
@@ -20,14 +23,13 @@ import javax.xml.transform.dom.DOMResult;
 import org.opendaylight.mdsal.dom.api.DOMNotification;
 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
+import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
@@ -35,45 +37,36 @@ import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
 /**
- * {@link NotificationListenerAdapter} is responsible to track events on
- * notifications.
- *
+ * {@link NotificationListenerAdapter} is responsible to track events on notifications.
  */
 public class NotificationListenerAdapter extends AbstractCommonSubscriber implements DOMNotificationListener {
 
     private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
 
     private final String streamName;
-    private final SchemaPath path;
+    private final Absolute path;
     private final String outputType;
 
-    private SchemaContext schemaContext;
-    private DOMNotification notification;
-
     /**
-     * Set path of listener and stream name, register event bus.
+     * Set path of listener and stream name.
      *
-     * @param path
-     *             path of notification
-     * @param streamName
-     *             stream name of listener
-     * @param outputType
-     *             type of output on notification (JSON, XML)
+     * @param path       Schema path of YANG notification.
+     * @param streamName Name of the stream.
+     * @param outputType Type of output on notification (JSON or XML).
      */
-    NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType) {
-        register(this);
-        setLocalNameOfPath(path.getLastComponent().getLocalName());
-
-        this.outputType = Preconditions.checkNotNull(outputType);
-        this.path = Preconditions.checkNotNull(path);
-        Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
-        this.streamName = streamName;
+    NotificationListenerAdapter(final Absolute path, final String streamName, final String outputType) {
+        setLocalNameOfPath(path.lastNodeIdentifier().getLocalName());
+
+        this.outputType = requireNonNull(outputType);
+        this.path = requireNonNull(path);
+        this.streamName = requireNonNull(streamName);
+        checkArgument(!streamName.isEmpty());
     }
 
     /**
-     * Get outputType of listener.
+     * Get output type of this listener.
      *
-     * @return the outputType
+     * @return The configured output type (JSON or XML).
      */
     @Override
     public String getOutputType() {
@@ -81,21 +74,23 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem
     }
 
     @Override
-    @SuppressWarnings("checkstyle:hiddenField")
     public void onNotification(final DOMNotification notification) {
-        this.schemaContext = schemaHandler.get();
-        this.notification = notification;
+        final Instant now = Instant.now();
+        if (!checkStartStop(now, this)) {
+            return;
+        }
 
-        final String xml = prepareXml();
-        if (checkQueryParams(xml, this)) {
-            prepareAndPostData(xml);
+        final EffectiveModelContext schemaContext = schemaHandler.get();
+        final String xml = prepareXml(schemaContext, notification);
+        if (checkFilter(xml)) {
+            post(outputType.equals("JSON") ? prepareJson(schemaContext, notification) : xml);
         }
     }
 
     /**
      * Get stream name of this listener.
      *
-     * @return {@link String}
+     * @return The configured stream name.
      */
     @Override
     public String getStreamName() {
@@ -105,59 +100,35 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem
     /**
      * Get schema path of notification.
      *
-     * @return {@link SchemaPath}
+     * @return The configured schema path that points to observing YANG notification schema node.
      */
-    public SchemaPath getSchemaPath() {
+    public Absolute getSchemaPath() {
         return this.path;
     }
 
     /**
-     * Prepare data of notification and data to client.
-     *
-     * @param xml   data
-     */
-    private void prepareAndPostData(final String xml) {
-        final Event event = new Event(EventType.NOTIFY);
-        if (this.outputType.equals("JSON")) {
-            event.setData(prepareJson());
-        } else {
-            event.setData(xml);
-        }
-        post(event);
-    }
-
-    /**
-     * Prepare json from notification data.
+     * Creation of JSON from notification data.
      *
-     * @return json as {@link String}
+     * @return Transformed notification data in JSON format.
      */
     @VisibleForTesting
-    String prepareJson() {
+    String prepareJson(final EffectiveModelContext schemaContext, final DOMNotification notification) {
         final JsonParser jsonParser = new JsonParser();
         final JsonObject json = new JsonObject();
-        json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString()));
+        json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString(schemaContext, notification)));
         json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
         return json.toString();
     }
 
-    @VisibleForTesting
-    void setNotification(final DOMNotification notification) {
-        this.notification = Preconditions.checkNotNull(notification);
-    }
-
-    @VisibleForTesting
-    void setSchemaContext(final SchemaContext schemaContext) {
-        this.schemaContext = Preconditions.checkNotNull(schemaContext);
-    }
-
-    private String writeBodyToString() {
+    private static String writeBodyToString(final EffectiveModelContext schemaContext,
+            final DOMNotification notification) {
         final Writer writer = new StringWriter();
         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
-            JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(this.schemaContext),
-            this.notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
+                JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
+                notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
         try {
-            nodeWriter.write(this.notification.getBody());
+            nodeWriter.write(notification.getBody());
             nodeWriter.close();
         } catch (final IOException e) {
             throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
@@ -165,27 +136,27 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem
         return writer.toString();
     }
 
-    private String prepareXml() {
+    /**
+     * Creation of XML from notification data.
+     *
+     * @return Transformed notification data in XML format.
+     */
+    private String prepareXml(final EffectiveModelContext schemaContext, final DOMNotification notification) {
         final Document doc = createDocument();
         final Element notificationElement = basePartDoc(doc);
 
         final Element notificationEventElement = doc.createElementNS(
                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
-        addValuesToNotificationEventElement(doc, notificationEventElement);
+        addValuesToNotificationEventElement(doc, notificationEventElement, schemaContext, notification);
         notificationElement.appendChild(notificationEventElement);
 
         return transformDoc(doc);
     }
 
-    private void addValuesToNotificationEventElement(final Document doc, final Element element) {
-        if (notification == null) {
-            return;
-        }
-
-        final ContainerNode body = notification.getBody();
+    private void addValuesToNotificationEventElement(final Document doc, final Element element,
+            final EffectiveModelContext schemaContext, final DOMNotification notification) {
         try {
-
-            final DOMResult domResult = writeNormalizedNode(body, schemaContext, this.path);
+            final DOMResult domResult = writeNormalizedNode(notification.getBody(), schemaContext, path.asSchemaPath());
             final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
             final Element dataElement = doc.createElement("notification");
             dataElement.appendChild(result);
@@ -196,4 +167,13 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem
             LOG.error("Error processing stream", e);
         }
     }
+
+    @Override
+    public String toString() {
+        return MoreObjects.toStringHelper(this)
+                .add("path", path)
+                .add("stream-name", streamName)
+                .add("output-type", outputType)
+                .toString();
+    }
 }