2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.streams.listeners;
10 import com.google.common.base.Charsets;
11 import com.google.common.base.Preconditions;
12 import com.google.common.eventbus.AsyncEventBus;
13 import com.google.common.eventbus.EventBus;
14 import com.google.common.eventbus.Subscribe;
15 import io.netty.channel.Channel;
16 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
17 import io.netty.util.internal.ConcurrentSet;
18 import java.io.ByteArrayOutputStream;
19 import java.io.IOException;
20 import java.io.OutputStreamWriter;
21 import java.io.UnsupportedEncodingException;
22 import java.util.Collection;
23 import java.util.Date;
25 import java.util.concurrent.Executors;
26 import javax.xml.stream.XMLOutputFactory;
27 import javax.xml.stream.XMLStreamException;
28 import javax.xml.stream.XMLStreamWriter;
29 import javax.xml.transform.OutputKeys;
30 import javax.xml.transform.Transformer;
31 import javax.xml.transform.TransformerException;
32 import javax.xml.transform.TransformerFactory;
33 import javax.xml.transform.dom.DOMResult;
34 import javax.xml.transform.dom.DOMSource;
35 import javax.xml.transform.stream.StreamResult;
36 import org.json.JSONObject;
38 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
39 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationListener;
40 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
41 import org.opendaylight.yangtools.concepts.ListenerRegistration;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
49 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
50 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
51 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
52 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Document;
56 import org.w3c.dom.Element;
57 import org.w3c.dom.Node;
60 * {@link NotificationListenerAdapter} is responsible to track events on
64 public class NotificationListenerAdapter implements DOMNotificationListener {
66 private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
67 private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
69 private final String streamName;
70 private ListenerRegistration<DOMNotificationListener> registration;
71 private Set<Channel> subscribers = new ConcurrentSet<>();
72 private final EventBus eventBus;
73 private final EventBusChangeRecorder eventBusChangeRecorder;
75 private final SchemaPath path;
76 private final String outputType;
79 * Set path of listener and stream name, register event bus.
82 * - path of notification
84 * - stream name of listener
86 * - type of output on notification (JSON, XML)
88 NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType) {
89 this.outputType = outputType;
90 Preconditions.checkArgument((streamName != null) && !streamName.isEmpty());
91 Preconditions.checkArgument(path != null);
93 this.streamName = streamName;
94 this.eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor());
95 this.eventBusChangeRecorder = new EventBusChangeRecorder();
96 this.eventBus.register(this.eventBusChangeRecorder);
100 public void onNotification(final DOMNotification notification) {
101 final String xml = prepareXmlFrom(notification);
102 final Event event = new Event(EventType.NOTIFY);
103 if (this.outputType.equals("JSON")) {
104 final JSONObject jsonObject = XML.toJSONObject(xml);
105 event.setData(jsonObject.toString());
109 this.eventBus.post(event);
113 * Checks if exists at least one {@link Channel} subscriber.
115 * @return True if exist at least one {@link Channel} subscriber, false
118 public boolean hasSubscribers() {
119 return !this.subscribers.isEmpty();
123 * Reset lists, close registration and unregister bus event.
125 public void close() {
126 this.subscribers = new ConcurrentSet<>();
127 this.registration.close();
128 this.registration = null;
129 this.eventBus.unregister(this.eventBusChangeRecorder);
133 * Get stream name of this listener
135 * @return {@link String}
137 public String getStreamName() {
138 return this.streamName;
142 * Check if is this listener registered.
144 * @return - true if is registered, otherwise null
146 public boolean isListening() {
147 return this.registration == null ? false : true;
151 * Get schema path of notification
153 * @return {@link SchemaPath}
155 public SchemaPath getSchemaPath() {
160 * Set registration for close after closing connection and check if this
161 * listener is registered
163 * @param registration
164 * - registered listener
166 public void setRegistration(final ListenerRegistration<DOMNotificationListener> registration) {
167 Preconditions.checkNotNull(registration);
168 this.registration = registration;
172 * Creates event of type {@link EventType#REGISTER}, set {@link Channel}
173 * subscriber to the event and post event into event bus.
178 public void addSubscriber(final Channel subscriber) {
179 if (!subscriber.isActive()) {
180 LOG.debug("Channel is not active between websocket server and subscriber {}" + subscriber.remoteAddress());
182 final Event event = new Event(EventType.REGISTER);
183 event.setSubscriber(subscriber);
184 this.eventBus.post(event);
188 * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel}
189 * subscriber to the event and posts event into event bus.
193 public void removeSubscriber(final Channel subscriber) {
194 LOG.debug("Subscriber {} is removed.", subscriber.remoteAddress());
195 final Event event = new Event(EventType.DEREGISTER);
196 event.setSubscriber(subscriber);
197 this.eventBus.post(event);
200 private String prepareXmlFrom(final DOMNotification notification) {
201 final SchemaContext schemaContext = ControllerContext.getInstance().getGlobalSchema();
202 final Document doc = ListenerAdapter.createDocument();
203 final Element notificationElement = doc.createElementNS("urn:ietf:params:xml:ns:yang:ietf-restconf",
205 doc.appendChild(notificationElement);
207 final Element eventTimeElement = doc.createElement("eventTime");
208 eventTimeElement.setTextContent(ListenerAdapter.toRFC3339(new Date()));
209 notificationElement.appendChild(eventTimeElement);
210 final String notificationNamespace = notification.getType().getLastComponent().getNamespace().toString();
211 final Element notificationEventElement = doc.createElementNS(
212 notificationNamespace, "event");
213 addValuesToNotificationEventElement(doc, notificationEventElement, notification, schemaContext);
214 notificationElement.appendChild(notificationEventElement);
217 final ByteArrayOutputStream out = new ByteArrayOutputStream();
218 final Transformer transformer = FACTORY.newTransformer();
219 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
220 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
221 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
222 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
223 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
224 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, Charsets.UTF_8)));
225 final byte[] charData = out.toByteArray();
226 return new String(charData, "UTF-8");
227 } catch (TransformerException | UnsupportedEncodingException e) {
228 final String msg = "Error during transformation of Document into String";
234 private void addValuesToNotificationEventElement(final Document doc, final Element element,
235 final DOMNotification notification, final SchemaContext schemaContext) {
236 if (notification == null) {
240 final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> body = notification
243 final DOMResult domResult = writeNormalizedNode(body,
244 YangInstanceIdentifier.create(body.getIdentifier()), schemaContext);
245 final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
246 element.appendChild(result);
247 } catch (final IOException e) {
248 LOG.error("Error in writer ", e);
249 } catch (final XMLStreamException e) {
250 LOG.error("Error processing stream", e);
254 private DOMResult writeNormalizedNode(final NormalizedNode<?, ?> normalized, final YangInstanceIdentifier path,
255 final SchemaContext context) throws IOException, XMLStreamException {
256 final XMLOutputFactory XML_FACTORY = XMLOutputFactory.newFactory();
257 final Document doc = XmlDocumentUtils.getDocument();
258 final DOMResult result = new DOMResult(doc);
259 NormalizedNodeWriter normalizedNodeWriter = null;
260 NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
261 XMLStreamWriter writer = null;
264 writer = XML_FACTORY.createXMLStreamWriter(result);
265 normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context,
266 this.getSchemaPath());
267 normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
269 normalizedNodeWriter.write(normalized);
271 normalizedNodeWriter.flush();
273 if (normalizedNodeWriter != null) {
274 normalizedNodeWriter.close();
276 if (normalizedNodeStreamWriter != null) {
277 normalizedNodeStreamWriter.close();
279 if (writer != null) {
288 * Tracks events of data change by customer.
290 private final class EventBusChangeRecorder {
292 public void recordCustomerChange(final Event event) {
293 if (event.getType() == EventType.REGISTER) {
294 final Channel subscriber = event.getSubscriber();
295 if (!NotificationListenerAdapter.this.subscribers.contains(subscriber)) {
296 NotificationListenerAdapter.this.subscribers.add(subscriber);
298 } else if (event.getType() == EventType.DEREGISTER) {
299 NotificationListenerAdapter.this.subscribers.remove(event.getSubscriber());
300 Notificator.removeNotificationListenerIfNoSubscriberExists(NotificationListenerAdapter.this);
301 } else if (event.getType() == EventType.NOTIFY) {
302 for (final Channel subscriber : NotificationListenerAdapter.this.subscribers) {
303 if (subscriber.isActive()) {
304 LOG.debug("Data are sent to subscriber {}:", subscriber.remoteAddress());
305 subscriber.writeAndFlush(new TextWebSocketFrame(event.getData()));
307 LOG.debug("Subscriber {} is removed - channel is not active yet.", subscriber.remoteAddress());
308 NotificationListenerAdapter.this.subscribers.remove(subscriber);
316 * Represents event of specific {@link EventType} type, holds data and
317 * {@link Channel} subscriber.
319 private final class Event {
320 private final EventType type;
321 private Channel subscriber;
325 * Creates new event specified by {@link EventType} type.
330 public Event(final EventType type) {
335 * Gets the {@link Channel} subscriber.
339 public Channel getSubscriber() {
340 return this.subscriber;
344 * Sets subscriber for event.
349 public void setSubscriber(final Channel subscriber) {
350 this.subscriber = subscriber;
356 * @return String representation of event data.
358 public String getData() {
368 public void setData(final String data) {
375 * @return The type of the event.
377 public EventType getType() {
385 private enum EventType {
386 REGISTER, DEREGISTER, NOTIFY