Refactoring of web-sockets in RESTCONF RFC-8040
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / listeners / NotificationListenerAdapter.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040.streams.listeners;
9
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;
36
37 /**
38  * {@link NotificationListenerAdapter} is responsible to track events on notifications.
39  */
40 public class NotificationListenerAdapter extends AbstractCommonSubscriber implements DOMNotificationListener {
41
42     private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
43
44     private final String streamName;
45     private final SchemaPath path;
46     private final String outputType;
47
48     /**
49      * Set path of listener and stream name, register event bus.
50      *
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).
54      */
55     NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType) {
56         register(this);
57         setLocalNameOfPath(path.getLastComponent().getLocalName());
58
59         this.outputType = Preconditions.checkNotNull(outputType);
60         this.path = Preconditions.checkNotNull(path);
61         Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
62         this.streamName = streamName;
63     }
64
65     /**
66      * Get output type of this listener.
67      *
68      * @return The configured output type (JSON or XML).
69      */
70     @Override
71     public String getOutputType() {
72         return this.outputType;
73     }
74
75     @Override
76     public void onNotification(final DOMNotification notification) {
77         final Instant now = Instant.now();
78         if (!checkStartStop(now, this)) {
79             return;
80         }
81
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);
86         }
87     }
88
89     /**
90      * Get stream name of this listener.
91      *
92      * @return The configured stream name.
93      */
94     @Override
95     public String getStreamName() {
96         return this.streamName;
97     }
98
99     /**
100      * Get schema path of notification.
101      *
102      * @return The configured schema path that points to observing YANG notification schema node.
103      */
104     public SchemaPath getSchemaPath() {
105         return this.path;
106     }
107
108     /**
109      * Prepare data of notification and data to client.
110      *
111      * @param data JSON or XML data that holds notification data.
112      */
113     private void prepareAndPostData(final String data) {
114         final Event event = new Event(EventType.NOTIFY);
115         event.setData(data);
116         post(event);
117     }
118
119     /**
120      * Creation of JSON from notification data.
121      *
122      * @return Transformed notification data in JSON format.
123      */
124     @VisibleForTesting
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();
131     }
132
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);
139         try {
140             nodeWriter.write(notification.getBody());
141             nodeWriter.close();
142         } catch (final IOException e) {
143             throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
144         }
145         return writer.toString();
146     }
147
148     /**
149      * Creation of XML from notification data.
150      *
151      * @return Transformed notification data in XML format.
152      */
153     private String prepareXml(final SchemaContext schemaContext, final DOMNotification notification) {
154         final Document doc = createDocument();
155         final Element notificationElement = basePartDoc(doc);
156
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);
161
162         return transformDoc(doc);
163     }
164
165     private void addValuesToNotificationEventElement(final Document doc, final Element element,
166             final SchemaContext schemaContext, final DOMNotification notification) {
167         try {
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);
177         }
178     }
179
180     @Override
181     public String toString() {
182         return MoreObjects.toStringHelper(this)
183                 .add("path", path)
184                 .add("stream-name", streamName)
185                 .add("output-type", outputType)
186                 .toString();
187     }
188 }