bbfad3127c369cc6eddeb74b324aaaf5dc60e222
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / 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.restconf.nb.rfc8040.streams.listeners;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.Preconditions;
13 import com.google.gson.JsonObject;
14 import com.google.gson.JsonParser;
15 import java.io.IOException;
16 import java.io.StringWriter;
17 import java.io.Writer;
18 import java.time.Instant;
19 import javax.xml.stream.XMLStreamException;
20 import javax.xml.transform.dom.DOMResult;
21 import org.opendaylight.mdsal.dom.api.DOMNotification;
22 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
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 notifications.
39  */
40 public class NotificationListenerAdapter extends AbstractCommonSubscriber implements DOMNotificationListener {
41
42     private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
43
44     private final String streamName;
45     private final SchemaPath path;
46     private final String outputType;
47
48     /**
49      * Set path of listener and stream name.
50      *
51      * @param path       Schema path of YANG notification.
52      * @param streamName Name of the stream.
53      * @param outputType Type of output on notification (JSON or XML).
54      */
55     NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType) {
56         setLocalNameOfPath(path.getLastComponent().getLocalName());
57
58         this.outputType = Preconditions.checkNotNull(outputType);
59         this.path = Preconditions.checkNotNull(path);
60         Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
61         this.streamName = streamName;
62     }
63
64     /**
65      * Get output type of this listener.
66      *
67      * @return The configured output type (JSON or XML).
68      */
69     @Override
70     public String getOutputType() {
71         return this.outputType;
72     }
73
74     @Override
75     public void onNotification(final DOMNotification notification) {
76         final Instant now = Instant.now();
77         if (!checkStartStop(now, this)) {
78             return;
79         }
80
81         final SchemaContext schemaContext = schemaHandler.get();
82         final String xml = prepareXml(schemaContext, notification);
83         if (checkFilter(xml)) {
84             post(outputType.equals("JSON") ? prepareJson(schemaContext, notification) : xml);
85         }
86     }
87
88     /**
89      * Get stream name of this listener.
90      *
91      * @return The configured stream name.
92      */
93     @Override
94     public String getStreamName() {
95         return this.streamName;
96     }
97
98     /**
99      * Get schema path of notification.
100      *
101      * @return The configured schema path that points to observing YANG notification schema node.
102      */
103     public SchemaPath getSchemaPath() {
104         return this.path;
105     }
106
107     /**
108      * Creation of JSON from notification data.
109      *
110      * @return Transformed notification data in JSON format.
111      */
112     @VisibleForTesting
113     String prepareJson(final SchemaContext schemaContext, final DOMNotification notification) {
114         final JsonParser jsonParser = new JsonParser();
115         final JsonObject json = new JsonObject();
116         json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString(schemaContext, notification)));
117         json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
118         return json.toString();
119     }
120
121     private static String writeBodyToString(final SchemaContext schemaContext, final DOMNotification notification) {
122         final Writer writer = new StringWriter();
123         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
124                 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
125                 notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
126         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
127         try {
128             nodeWriter.write(notification.getBody());
129             nodeWriter.close();
130         } catch (final IOException e) {
131             throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
132         }
133         return writer.toString();
134     }
135
136     /**
137      * Creation of XML from notification data.
138      *
139      * @return Transformed notification data in XML format.
140      */
141     private String prepareXml(final SchemaContext schemaContext, final DOMNotification notification) {
142         final Document doc = createDocument();
143         final Element notificationElement = basePartDoc(doc);
144
145         final Element notificationEventElement = doc.createElementNS(
146                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
147         addValuesToNotificationEventElement(doc, notificationEventElement, schemaContext, notification);
148         notificationElement.appendChild(notificationEventElement);
149
150         return transformDoc(doc);
151     }
152
153     private void addValuesToNotificationEventElement(final Document doc, final Element element,
154             final SchemaContext schemaContext, final DOMNotification notification) {
155         try {
156             final DOMResult domResult = writeNormalizedNode(notification.getBody(), schemaContext, this.path);
157             final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
158             final Element dataElement = doc.createElement("notification");
159             dataElement.appendChild(result);
160             element.appendChild(dataElement);
161         } catch (final IOException e) {
162             LOG.error("Error in writer ", e);
163         } catch (final XMLStreamException e) {
164             LOG.error("Error processing stream", e);
165         }
166     }
167
168     @Override
169     public String toString() {
170         return MoreObjects.toStringHelper(this)
171                 .add("path", path)
172                 .add("stream-name", streamName)
173                 .add("output-type", outputType)
174                 .toString();
175     }
176 }