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