Remove explicit default super-constructor calls
[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.controller.md.sal.dom.api.DOMNotification;
22 import org.opendaylight.controller.md.sal.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.JSONCodecFactory;
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     public void onNotification(final DOMNotification notification) {
89         this.schemaContext = schemaHandler.get();
90         this.notification = notification;
91
92         final String xml = prepareXml();
93         if (checkQueryParams(xml, this)) {
94             prepareAndPostData(xml);
95         }
96     }
97
98     /**
99      * Get stream name of this listener.
100      *
101      * @return {@link String}
102      */
103     @Override
104     public String getStreamName() {
105         return this.streamName;
106     }
107
108     /**
109      * Get schema path of notification.
110      *
111      * @return {@link SchemaPath}
112      */
113     public SchemaPath getSchemaPath() {
114         return this.path;
115     }
116
117     /**
118      * Prepare data of notification and data to client.
119      *
120      * @param xml   data
121      */
122     private void prepareAndPostData(final String xml) {
123         final Event event = new Event(EventType.NOTIFY);
124         if (this.outputType.equals("JSON")) {
125             event.setData(prepareJson());
126         } else {
127             event.setData(xml);
128         }
129         post(event);
130     }
131
132     /**
133      * Prepare json from notification data.
134      *
135      * @return json as {@link String}
136      */
137     @VisibleForTesting
138     String prepareJson() {
139         final JsonParser jsonParser = new JsonParser();
140         final JsonObject json = new JsonObject();
141         json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString()));
142         json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
143         return json.toString();
144     }
145
146     @VisibleForTesting
147     void setNotification(final DOMNotification notification) {
148         this.notification = Preconditions.checkNotNull(notification);
149     }
150
151     @VisibleForTesting
152     void setSchemaContext(final SchemaContext schemaContext) {
153         this.schemaContext = Preconditions.checkNotNull(schemaContext);
154     }
155
156     private String writeBodyToString() {
157         final Writer writer = new StringWriter();
158         final NormalizedNodeStreamWriter jsonStream =
159                 JSONNormalizedNodeStreamWriter.createExclusiveWriter(JSONCodecFactory.getShared(this.schemaContext),
160                         this.notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
161         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
162         try {
163             nodeWriter.write(this.notification.getBody());
164             nodeWriter.close();
165         } catch (final IOException e) {
166             throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
167         }
168         return writer.toString();
169     }
170
171     private String prepareXml() {
172         final Document doc = createDocument();
173         final Element notificationElement = basePartDoc(doc);
174
175         final Element notificationEventElement = doc.createElementNS(
176                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
177         addValuesToNotificationEventElement(doc, notificationEventElement, this.notification, this.schemaContext);
178         notificationElement.appendChild(notificationEventElement);
179
180         return transformDoc(doc);
181     }
182
183     private void addValuesToNotificationEventElement(final Document doc, final Element element,
184             final DOMNotification notification, final SchemaContext schemaContext) {
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 }