Apply modernizations
[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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.gson.JsonObject;
15 import com.google.gson.JsonParser;
16 import java.io.IOException;
17 import java.io.StringWriter;
18 import java.io.Writer;
19 import java.time.Instant;
20 import javax.xml.stream.XMLStreamException;
21 import javax.xml.transform.dom.DOMResult;
22 import org.opendaylight.mdsal.dom.api.DOMNotification;
23 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
24 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
25 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
26 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
27 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
28 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
29 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
32 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.w3c.dom.Document;
36 import org.w3c.dom.Element;
37 import org.w3c.dom.Node;
38
39 /**
40  * {@link NotificationListenerAdapter} is responsible to track events on
41  * notifications.
42  *
43  */
44 public class NotificationListenerAdapter extends AbstractCommonSubscriber implements DOMNotificationListener {
45
46     private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
47
48     private final ControllerContext controllerContext;
49     private final String streamName;
50     private final SchemaPath path;
51     private final String outputType;
52
53     /**
54      * Set path of listener and stream name, register event bus.
55      *
56      * @param path
57      *             path of notification
58      * @param streamName
59      *             stream name of listener
60      * @param outputType
61      *             type of output on notification (JSON, XML)
62      */
63     NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType,
64             final ControllerContext controllerContext) {
65         register(this);
66         this.outputType = requireNonNull(outputType);
67         this.path = requireNonNull(path);
68         checkArgument(streamName != null && !streamName.isEmpty());
69         this.streamName = streamName;
70         this.controllerContext = controllerContext;
71     }
72
73     /**
74      * Get outputType of listener.
75      *
76      * @return the outputType
77      */
78     @Override
79     public String getOutputType() {
80         return this.outputType;
81     }
82
83     @Override
84     public void onNotification(final DOMNotification notification) {
85         final Instant now = Instant.now();
86         if (!checkStartStop(now, this)) {
87             return;
88         }
89
90         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
91         final String xml = prepareXml(schemaContext, notification);
92         if (checkFilter(xml)) {
93             prepareAndPostData(outputType.equals("JSON") ? prepareJson(schemaContext, notification) : 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 data   data
120      */
121     private void prepareAndPostData(final String data) {
122         final Event event = new Event(EventType.NOTIFY);
123         event.setData(data);
124         post(event);
125     }
126
127     /**
128      * Prepare json from notification data.
129      *
130      * @return json as {@link String}
131      */
132     @VisibleForTesting
133     String prepareJson(final SchemaContext schemaContext, final DOMNotification notification) {
134         final JsonParser jsonParser = new JsonParser();
135         final JsonObject json = new JsonObject();
136         json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString(schemaContext, notification)));
137         json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
138         return json.toString();
139     }
140
141     private static String writeBodyToString(final SchemaContext schemaContext, final DOMNotification notification) {
142         final Writer writer = new StringWriter();
143         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
144             JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
145             notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
146         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
147         try {
148             nodeWriter.write(notification.getBody());
149             nodeWriter.close();
150         } catch (final IOException e) {
151             throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
152         }
153         return writer.toString();
154     }
155
156     private String prepareXml(final SchemaContext schemaContext, final DOMNotification notification) {
157         final Document doc = createDocument();
158         final Element notificationElement = basePartDoc(doc);
159
160         final Element notificationEventElement = doc.createElementNS(
161                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
162         addValuesToNotificationEventElement(doc, notificationEventElement, schemaContext, notification);
163         notificationElement.appendChild(notificationEventElement);
164
165         return transformDoc(doc);
166     }
167
168     private void addValuesToNotificationEventElement(final Document doc, final Element element,
169             final SchemaContext schemaContext, final DOMNotification notification) {
170         try {
171
172             final DOMResult domResult = writeNormalizedNode(notification.getBody(), schemaContext, this.path);
173             final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
174             final Element dataElement = doc.createElement("notification");
175             dataElement.appendChild(result);
176             element.appendChild(dataElement);
177         } catch (final IOException e) {
178             LOG.error("Error in writer ", e);
179         } catch (final XMLStreamException e) {
180             LOG.error("Error processing stream", e);
181         }
182     }
183 }