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