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