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