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