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