Merge "Migrate XML output to yang-data-codec-xml"
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / netconf / sal / 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.netconf.sal.streams.listeners;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.gson.JsonObject;
13 import com.google.gson.JsonParser;
14 import java.io.IOException;
15 import java.io.StringWriter;
16 import java.io.Writer;
17 import java.time.Instant;
18 import java.util.Collection;
19 import javax.xml.stream.XMLStreamException;
20 import javax.xml.transform.dom.DOMResult;
21 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
22 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationListener;
23 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
24 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
27 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
28 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
31 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
32 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
33 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.Element;
40 import org.w3c.dom.Node;
41
42 /**
43  * {@link NotificationListenerAdapter} is responsible to track events on
44  * notifications.
45  *
46  */
47 public class NotificationListenerAdapter extends AbstractCommonSubscriber implements DOMNotificationListener {
48
49     private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
50
51     private final String streamName;
52     private final SchemaPath path;
53     private final String outputType;
54
55     private SchemaContext schemaContext;
56     private DOMNotification notification;
57
58     /**
59      * Set path of listener and stream name, register event bus.
60      *
61      * @param path
62      *             path of notification
63      * @param streamName
64      *             stream name of listener
65      * @param outputType
66      *             type of output on notification (JSON, XML)
67      */
68     NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType) {
69         super();
70         register(this);
71         setLocalNameOfPath(path.getLastComponent().getLocalName());
72
73         this.outputType = Preconditions.checkNotNull(outputType);
74         this.path = Preconditions.checkNotNull(path);
75         Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
76         this.streamName = streamName;
77     }
78
79     /**
80      * Get outputType of listener.
81      *
82      * @return the outputType
83      */
84     @Override
85     public String getOutputType() {
86         return this.outputType;
87     }
88
89     @Override
90     public void onNotification(final DOMNotification notification) {
91         this.schemaContext = ControllerContext.getInstance().getGlobalSchema();
92         this.notification = notification;
93
94         final String xml = prepareXml();
95         if (checkQueryParams(xml, this)) {
96             prepareAndPostData(xml);
97         }
98     }
99
100     /**
101      * Get stream name of this listener.
102      *
103      * @return {@link String}
104      */
105     @Override
106     public String getStreamName() {
107         return this.streamName;
108     }
109
110     /**
111      * Get schema path of notification.
112      *
113      * @return {@link SchemaPath}
114      */
115     public SchemaPath getSchemaPath() {
116         return this.path;
117     }
118
119     /**
120      * Prepare data of notification and data to client.
121      *
122      * @param xml   data
123      */
124     private void prepareAndPostData(final String xml) {
125         final Event event = new Event(EventType.NOTIFY);
126         if (this.outputType.equals("JSON")) {
127             event.setData(prepareJson());
128         } else {
129             event.setData(xml);
130         }
131         post(event);
132     }
133
134     /**
135      * Prepare json from notification data.
136      *
137      * @return json as {@link String}
138      */
139     @VisibleForTesting
140     String prepareJson() {
141         JsonParser jsonParser = new JsonParser();
142         JsonObject json = new JsonObject();
143         json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString()));
144         json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
145         return json.toString();
146     }
147
148     @VisibleForTesting
149     void setNotification(final DOMNotification notification) {
150         this.notification = Preconditions.checkNotNull(notification);
151     }
152
153     @VisibleForTesting
154     void setSchemaContext(final SchemaContext schemaContext) {
155         this.schemaContext = Preconditions.checkNotNull(schemaContext);
156     }
157
158     private String writeBodyToString() {
159         final Writer writer = new StringWriter();
160         final NormalizedNodeStreamWriter jsonStream =
161                 JSONNormalizedNodeStreamWriter.createExclusiveWriter(JSONCodecFactory.getShared(this.schemaContext),
162                         this.notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
163         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
164         try {
165             nodeWriter.write(this.notification.getBody());
166             nodeWriter.close();
167         } catch (final IOException e) {
168             throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
169         }
170         return writer.toString();
171     }
172
173     private String prepareXml() {
174         final Document doc = createDocument();
175         final Element notificationElement = basePartDoc(doc);
176
177         final Element notificationEventElement = doc.createElementNS(
178                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
179         addValuesToNotificationEventElement(doc, notificationEventElement, this.notification, this.schemaContext);
180         notificationElement.appendChild(notificationEventElement);
181
182         return transformDoc(doc);
183     }
184
185     private void addValuesToNotificationEventElement(final Document doc, final Element element,
186             final DOMNotification notification, final SchemaContext schemaContext) {
187         if (notification == null) {
188             return;
189         }
190
191         final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> body =
192                 notification.getBody();
193         try {
194
195             final DOMResult domResult = writeNormalizedNode(body, schemaContext, this.path);
196             final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
197             final Element dataElement = doc.createElement("notification");
198             dataElement.appendChild(result);
199             element.appendChild(dataElement);
200         } catch (final IOException e) {
201             LOG.error("Error in writer ", e);
202         } catch (final XMLStreamException e) {
203             LOG.error("Error processing stream", e);
204         }
205     }
206 }