Check time expiry before attempting to format notification
[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 Instant now = Instant.now();
82         if (!checkStartStop(now, this)) {
83             return;
84         }
85
86         final SchemaContext schemaContext = schemaHandler.get();
87         final String xml = prepareXml(schemaContext, notification);
88         if (checkFilter(xml)) {
89             prepareAndPostData(outputType.equals("JSON") ? prepareJson(schemaContext, notification) : xml);
90         }
91     }
92
93     /**
94      * Get stream name of this listener.
95      *
96      * @return {@link String}
97      */
98     @Override
99     public String getStreamName() {
100         return this.streamName;
101     }
102
103     /**
104      * Get schema path of notification.
105      *
106      * @return {@link SchemaPath}
107      */
108     public SchemaPath getSchemaPath() {
109         return this.path;
110     }
111
112     /**
113      * Prepare data of notification and data to client.
114      *
115      * @param data   data
116      */
117     private void prepareAndPostData(final String data) {
118         final Event event = new Event(EventType.NOTIFY);
119         event.setData(data);
120         post(event);
121     }
122
123     /**
124      * Prepare json from notification data.
125      *
126      * @return json as {@link String}
127      */
128     @VisibleForTesting
129     String prepareJson(final SchemaContext schemaContext, final DOMNotification notification) {
130         final JsonParser jsonParser = new JsonParser();
131         final JsonObject json = new JsonObject();
132         json.add("ietf-restconf:notification", jsonParser.parse(writeBodyToString(schemaContext, notification)));
133         json.addProperty("event-time", ListenerAdapter.toRFC3339(Instant.now()));
134         return json.toString();
135     }
136
137     private static String writeBodyToString(final SchemaContext schemaContext, final DOMNotification notification) {
138         final Writer writer = new StringWriter();
139         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
140             JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext), notification.getType(),
141             null, JsonWriterFactory.createJsonWriter(writer));
142         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
143         try {
144             nodeWriter.write(notification.getBody());
145             nodeWriter.close();
146         } catch (final IOException e) {
147             throw new RestconfDocumentedException("Problem while writing body of notification to JSON. ", e);
148         }
149         return writer.toString();
150     }
151
152     private String prepareXml(final SchemaContext schemaContext, final DOMNotification notification) {
153         final Document doc = createDocument();
154         final Element notificationElement = basePartDoc(doc);
155
156         final Element notificationEventElement = doc.createElementNS(
157                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
158         addValuesToNotificationEventElement(doc, notificationEventElement, schemaContext, notification);
159         notificationElement.appendChild(notificationEventElement);
160
161         return transformDoc(doc);
162     }
163
164     private void addValuesToNotificationEventElement(final Document doc, final Element element,
165             final SchemaContext schemaContext, final DOMNotification notification) {
166         try {
167
168             final DOMResult domResult = writeNormalizedNode(notification.getBody(), schemaContext, this.path);
169             final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
170             final Element dataElement = doc.createElement("notification");
171             dataElement.appendChild(result);
172             element.appendChild(dataElement);
173         } catch (final IOException e) {
174             LOG.error("Error in writer ", e);
175         } catch (final XMLStreamException e) {
176             LOG.error("Error processing stream", e);
177         }
178     }
179 }