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