Fix various warnings
[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 java.io.IOException;
13 import java.io.StringWriter;
14 import java.io.Writer;
15 import java.time.Instant;
16 import java.util.Collection;
17 import javax.xml.stream.XMLStreamException;
18 import javax.xml.transform.dom.DOMResult;
19 import org.json.JSONObject;
20 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
21 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationListener;
22 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
23 import org.opendaylight.netconf.sal.restconf.impl.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         super();
69         register(this);
70         setLocalNameOfPath(path.getLastComponent().getLocalName());
71
72         this.outputType = Preconditions.checkNotNull(outputType);
73         this.path = Preconditions.checkNotNull(path);
74         Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
75         this.streamName = streamName;
76     }
77
78     /**
79      * Get outputType of listener.
80      *
81      * @return the outputType
82      */
83     @Override
84     public String getOutputType() {
85         return this.outputType;
86     }
87
88     @Override
89     public void onNotification(final DOMNotification notification) {
90         this.schemaContext = ControllerContext.getInstance().getGlobalSchema();
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 JSONObject json = new JSONObject();
141         json.put("ietf-restconf:notification",
142                 new JSONObject(writeBodyToString()).put("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 }