Fix adapters retaining state
[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.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 ControllerContext controllerContext;
47     private final String streamName;
48     private final SchemaPath path;
49     private final String outputType;
50
51     /**
52      * Set path of listener and stream name, register event bus.
53      *
54      * @param path
55      *             path of notification
56      * @param streamName
57      *             stream name of listener
58      * @param outputType
59      *             type of output on notification (JSON, XML)
60      */
61     NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType,
62             final ControllerContext controllerContext) {
63         register(this);
64         this.outputType = Preconditions.checkNotNull(outputType);
65         this.path = Preconditions.checkNotNull(path);
66         Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
67         this.streamName = streamName;
68         this.controllerContext = controllerContext;
69     }
70
71     /**
72      * Get outputType of listener.
73      *
74      * @return the outputType
75      */
76     @Override
77     public String getOutputType() {
78         return this.outputType;
79     }
80
81     @Override
82     public void onNotification(final DOMNotification notification) {
83         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
84         final String xml = prepareXml(schemaContext, notification);
85         if (checkQueryParams(xml, this)) {
86             prepareAndPostData(outputType.equals("JSON") ? prepareJson(schemaContext, notification) : xml);
87         }
88     }
89
90     /**
91      * Get stream name of this listener.
92      *
93      * @return {@link String}
94      */
95     @Override
96     public String getStreamName() {
97         return this.streamName;
98     }
99
100     /**
101      * Get schema path of notification.
102      *
103      * @return {@link SchemaPath}
104      */
105     public SchemaPath getSchemaPath() {
106         return this.path;
107     }
108
109     /**
110      * Prepare data of notification and data to client.
111      *
112      * @param data   data
113      */
114     private void prepareAndPostData(final String data) {
115         final Event event = new Event(EventType.NOTIFY);
116         event.setData(data);
117         post(event);
118     }
119
120     /**
121      * Prepare json from notification data.
122      *
123      * @return json as {@link String}
124      */
125     @VisibleForTesting
126     String prepareJson(final SchemaContext schemaContext, final DOMNotification notification) {
127         final JsonParser jsonParser = new JsonParser();
128         final JsonObject json = new JsonObject();
129         json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString(schemaContext, notification)));
130         json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
131         return json.toString();
132     }
133
134     private static String writeBodyToString(final SchemaContext schemaContext, final DOMNotification notification) {
135         final Writer writer = new StringWriter();
136         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
137             JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
138             notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
139         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
140         try {
141             nodeWriter.write(notification.getBody());
142             nodeWriter.close();
143         } catch (final IOException e) {
144             throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
145         }
146         return writer.toString();
147     }
148
149     private String prepareXml(final SchemaContext schemaContext, final DOMNotification notification) {
150         final Document doc = createDocument();
151         final Element notificationElement = basePartDoc(doc);
152
153         final Element notificationEventElement = doc.createElementNS(
154                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
155         addValuesToNotificationEventElement(doc, notificationEventElement, schemaContext, notification);
156         notificationElement.appendChild(notificationEventElement);
157
158         return transformDoc(doc);
159     }
160
161     private void addValuesToNotificationEventElement(final Document doc, final Element element,
162             final SchemaContext schemaContext, final DOMNotification notification) {
163         try {
164
165             final DOMResult domResult = writeNormalizedNode(notification.getBody(), schemaContext, this.path);
166             final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
167             final Element dataElement = doc.createElement("notification");
168             dataElement.appendChild(result);
169             element.appendChild(dataElement);
170         } catch (final IOException e) {
171             LOG.error("Error in writer ", e);
172         } catch (final XMLStreamException e) {
173             LOG.error("Error processing stream", e);
174         }
175     }
176 }