Eliminate AbstractQueryParams
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / listeners / NotificationListenerAdapter.java
index bbfad3127c369cc6eddeb74b324aaaf5dc60e222..866bd45d81c72faa02bfb69be187a3db01500cad 100644 (file)
@@ -7,32 +7,27 @@
  */
 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.MoreObjects;
-import com.google.common.base.Preconditions;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.Writer;
 import java.time.Instant;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.transform.dom.DOMResult;
+import java.util.Optional;
+import javax.xml.xpath.XPathExpressionException;
+import org.eclipse.jdt.annotation.Nullable;
 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.stream.NormalizedNodeStreamWriter;
-import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
+import org.opendaylight.mdsal.dom.api.DOMNotificationService;
+import org.opendaylight.restconf.common.formatters.JSONNotificationFormatter;
+import org.opendaylight.restconf.common.formatters.NotificationFormatter;
+import org.opendaylight.restconf.common.formatters.NotificationFormatterFactory;
+import org.opendaylight.restconf.common.formatters.XMLNotificationFormatter;
+import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
 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.stmt.SchemaNodeIdentifier.Absolute;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
 
 /**
  * {@link NotificationListenerAdapter} is responsible to track events on notifications.
@@ -40,10 +35,15 @@ import org.w3c.dom.Node;
 public class NotificationListenerAdapter extends AbstractCommonSubscriber implements DOMNotificationListener {
 
     private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
+    private static final NotificationFormatterFactory JSON_FORMATTER_FACTORY = JSONNotificationFormatter.createFactory(
+            JSONCodecFactorySupplier.RFC7951);
 
     private final String streamName;
-    private final SchemaPath path;
-    private final String outputType;
+    private final Absolute path;
+    private final NotificationOutputType outputType;
+
+    @VisibleForTesting NotificationFormatter formatter;
+
 
     /**
      * Set path of listener and stream name.
@@ -52,13 +52,33 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem
      * @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) {
-        setLocalNameOfPath(path.getLastComponent().getLocalName());
+    NotificationListenerAdapter(final Absolute path, final String streamName, final String outputType) {
+        setLocalNameOfPath(path.lastNodeIdentifier().getLocalName());
+
+        this.outputType = NotificationOutputType.forName(requireNonNull(outputType)).get();
+        this.path = requireNonNull(path);
+        this.streamName = requireNonNull(streamName);
+        checkArgument(!streamName.isEmpty());
+        formatter = getFormatterFactory().getFormatter();
 
-        this.outputType = Preconditions.checkNotNull(outputType);
-        this.path = Preconditions.checkNotNull(path);
-        Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
-        this.streamName = streamName;
+        LOG.debug("output type: {}, {}", outputType, this.outputType);
+    }
+
+    private NotificationFormatterFactory getFormatterFactory() {
+        switch (outputType) {
+            case JSON:
+                return JSON_FORMATTER_FACTORY;
+            case XML:
+                return XMLNotificationFormatter.FACTORY;
+            default:
+                throw new IllegalArgumentException("Unsupported outputType " + outputType);
+        }
+    }
+
+    @Override
+    final void setFilter(final @Nullable String filter) throws XPathExpressionException {
+        final NotificationFormatterFactory factory = getFormatterFactory();
+        formatter = filter == null || filter.isEmpty() ? factory.getFormatter() : factory.getFormatter(filter);
     }
 
     /**
@@ -68,20 +88,27 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem
      */
     @Override
     public String getOutputType() {
-        return this.outputType;
+        return outputType.getName();
     }
 
     @Override
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public void onNotification(final DOMNotification notification) {
         final Instant now = Instant.now();
-        if (!checkStartStop(now, this)) {
+        if (!checkStartStop(now)) {
             return;
         }
 
-        final SchemaContext schemaContext = schemaHandler.get();
-        final String xml = prepareXml(schemaContext, notification);
-        if (checkFilter(xml)) {
-            post(outputType.equals("JSON") ? prepareJson(schemaContext, notification) : xml);
+        final Optional<String> maybeOutput;
+        try {
+            maybeOutput = formatter.eventData(schemaHandler.get(), notification, now, getLeafNodesOnly(),
+                    isSkipNotificationData());
+        } catch (Exception e) {
+            LOG.error("Failed to process notification {}", notification, e);
+            return;
+        }
+        if (maybeOutput.isPresent()) {
+            post(maybeOutput.get());
         }
     }
 
@@ -92,7 +119,7 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem
      */
     @Override
     public String getStreamName() {
-        return this.streamName;
+        return streamName;
     }
 
     /**
@@ -100,68 +127,13 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem
      *
      * @return The configured schema path that points to observing YANG notification schema node.
      */
-    public SchemaPath getSchemaPath() {
-        return this.path;
-    }
-
-    /**
-     * Creation of JSON from notification data.
-     *
-     * @return Transformed notification data in JSON format.
-     */
-    @VisibleForTesting
-    String prepareJson(final SchemaContext schemaContext, final DOMNotification notification) {
-        final JsonParser jsonParser = new JsonParser();
-        final JsonObject json = new JsonObject();
-        json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString(schemaContext, notification)));
-        json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
-        return json.toString();
-    }
-
-    private static String writeBodyToString(final SchemaContext schemaContext, final DOMNotification notification) {
-        final Writer writer = new StringWriter();
-        final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
-                JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
-                notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
-        final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
-        try {
-            nodeWriter.write(notification.getBody());
-            nodeWriter.close();
-        } catch (final IOException e) {
-            throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
-        }
-        return writer.toString();
+    public Absolute getSchemaPath() {
+        return path;
     }
 
-    /**
-     * Creation of XML from notification data.
-     *
-     * @return Transformed notification data in XML format.
-     */
-    private String prepareXml(final SchemaContext 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, schemaContext, notification);
-        notificationElement.appendChild(notificationEventElement);
-
-        return transformDoc(doc);
-    }
-
-    private void addValuesToNotificationEventElement(final Document doc, final Element element,
-            final SchemaContext schemaContext, final DOMNotification notification) {
-        try {
-            final DOMResult domResult = writeNormalizedNode(notification.getBody(), schemaContext, this.path);
-            final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
-            final Element dataElement = doc.createElement("notification");
-            dataElement.appendChild(result);
-            element.appendChild(dataElement);
-        } catch (final IOException e) {
-            LOG.error("Error in writer ", e);
-        } catch (final XMLStreamException e) {
-            LOG.error("Error processing stream", e);
+    public final synchronized void listen(final DOMNotificationService notificationService) {
+        if (!isListening()) {
+            setRegistration(notificationService.registerNotificationListener(this, getSchemaPath()));
         }
     }