Convert to using requireNonNull()
[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.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 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 SchemaPath 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 SchemaPath path, final String streamName, final String outputType) {
58         setLocalNameOfPath(path.getLastComponent().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 SchemaContext 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 SchemaPath 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 SchemaContext 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 SchemaContext schemaContext, final DOMNotification notification) {
124         final Writer writer = new StringWriter();
125         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
126                 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
127                 notification.getType(), null, JsonWriterFactory.createJsonWriter(writer));
128         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
129         try {
130             nodeWriter.write(notification.getBody());
131             nodeWriter.close();
132         } catch (final IOException e) {
133             throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
134         }
135         return writer.toString();
136     }
137
138     /**
139      * Creation of XML from notification data.
140      *
141      * @return Transformed notification data in XML format.
142      */
143     private String prepareXml(final SchemaContext schemaContext, final DOMNotification notification) {
144         final Document doc = createDocument();
145         final Element notificationElement = basePartDoc(doc);
146
147         final Element notificationEventElement = doc.createElementNS(
148                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
149         addValuesToNotificationEventElement(doc, notificationEventElement, schemaContext, notification);
150         notificationElement.appendChild(notificationEventElement);
151
152         return transformDoc(doc);
153     }
154
155     private void addValuesToNotificationEventElement(final Document doc, final Element element,
156             final SchemaContext schemaContext, final DOMNotification notification) {
157         try {
158             final DOMResult domResult = writeNormalizedNode(notification.getBody(), schemaContext, this.path);
159             final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
160             final Element dataElement = doc.createElement("notification");
161             dataElement.appendChild(result);
162             element.appendChild(dataElement);
163         } catch (final IOException e) {
164             LOG.error("Error in writer ", e);
165         } catch (final XMLStreamException e) {
166             LOG.error("Error processing stream", e);
167         }
168     }
169
170     @Override
171     public String toString() {
172         return MoreObjects.toStringHelper(this)
173                 .add("path", path)
174                 .add("stream-name", streamName)
175                 .add("output-type", outputType)
176                 .toString();
177     }
178 }