2 * Copyright (c) 2014 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.controller.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.OutputStreamWriter;
20 import java.io.UnsupportedEncodingException;
21 import java.text.SimpleDateFormat;
22 import java.util.Collection;
23 import java.util.Date;
24 import java.util.HashMap;
26 import java.util.Random;
28 import java.util.concurrent.Executors;
29 import java.util.regex.Pattern;
30 import javax.xml.parsers.DocumentBuilder;
31 import javax.xml.parsers.DocumentBuilderFactory;
32 import javax.xml.parsers.ParserConfigurationException;
33 import javax.xml.transform.OutputKeys;
34 import javax.xml.transform.Transformer;
35 import javax.xml.transform.TransformerException;
36 import javax.xml.transform.TransformerFactory;
37 import javax.xml.transform.dom.DOMSource;
38 import javax.xml.transform.stream.StreamResult;
39 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
40 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
41 import org.opendaylight.controller.sal.rest.impl.XmlMapper;
42 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
43 import org.opendaylight.yangtools.concepts.ListenerRegistration;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.w3c.dom.Document;
53 import org.w3c.dom.Element;
54 import org.w3c.dom.Node;
57 * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source.
59 public class ListenerAdapter implements DOMDataChangeListener {
61 private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class);
62 private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();
63 private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
64 private static final Pattern RFC3339_PATTERN = Pattern.compile("(\\d\\d)(\\d\\d)$");
66 private final XmlMapper xmlMapper = new XmlMapper();
67 private final SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
69 private final YangInstanceIdentifier path;
70 private ListenerRegistration<DOMDataChangeListener> registration;
71 private final String streamName;
72 private Set<Channel> subscribers = new ConcurrentSet<>();
73 private final EventBus eventBus;
74 private final EventBusChangeRecorder eventBusChangeRecorder;
77 * Creates new {@link ListenerAdapter} listener specified by path and stream name.
80 * Path to data in data store.
82 * The name of the stream.
84 ListenerAdapter(final YangInstanceIdentifier path, final String streamName) {
85 Preconditions.checkNotNull(path);
86 Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
88 this.streamName = streamName;
89 eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor());
90 eventBusChangeRecorder = new EventBusChangeRecorder();
91 eventBus.register(eventBusChangeRecorder);
95 public void onDataChanged(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
96 // TODO Auto-generated method stub
98 if (!change.getCreatedData().isEmpty() || !change.getUpdatedData().isEmpty()
99 || !change.getRemovedPaths().isEmpty()) {
100 final String xml = prepareXmlFrom(change);
101 final Event event = new Event(EventType.NOTIFY);
103 eventBus.post(event);
108 * Tracks events of data change by customer.
110 private final class EventBusChangeRecorder {
112 public void recordCustomerChange(final Event event) {
113 if (event.getType() == EventType.REGISTER) {
114 final Channel subscriber = event.getSubscriber();
115 if (!subscribers.contains(subscriber)) {
116 subscribers.add(subscriber);
118 } else if (event.getType() == EventType.DEREGISTER) {
119 subscribers.remove(event.getSubscriber());
120 Notificator.removeListenerIfNoSubscriberExists(ListenerAdapter.this);
121 } else if (event.getType() == EventType.NOTIFY) {
122 for (final Channel subscriber : subscribers) {
123 if (subscriber.isActive()) {
124 LOG.debug("Data are sent to subscriber {}:", subscriber.remoteAddress());
125 subscriber.writeAndFlush(new TextWebSocketFrame(event.getData()));
127 LOG.debug("Subscriber {} is removed - channel is not active yet.", subscriber.remoteAddress());
128 subscribers.remove(subscriber);
136 * Represents event of specific {@link EventType} type, holds data and {@link Channel} subscriber.
138 private final class Event {
139 private final EventType type;
140 private Channel subscriber;
144 * Creates new event specified by {@link EventType} type.
149 public Event(final EventType type) {
154 * Gets the {@link Channel} subscriber.
158 public Channel getSubscriber() {
163 * Sets subscriber for event.
168 public void setSubscriber(final Channel subscriber) {
169 this.subscriber = subscriber;
175 * @return String representation of event data.
177 public String getData() {
184 * @param data String.
186 public void setData(final String data) {
193 * @return The type of the event.
195 public EventType getType() {
203 private enum EventType {
210 * Prepare data in printable form and transform it to String.
214 * @return Data in printable form.
216 private String prepareXmlFrom(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
217 final Document doc = createDocument();
218 final Element notificationElement = doc.createElementNS("urn:ietf:params:xml:ns:netconf:notification:1.0",
220 doc.appendChild(notificationElement);
222 final Element eventTimeElement = doc.createElement("eventTime");
223 eventTimeElement.setTextContent(toRFC3339(new Date()));
224 notificationElement.appendChild(eventTimeElement);
226 final Element dataChangedNotificationEventElement = doc.createElementNS(
227 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "data-changed-notification");
228 addValuesToDataChangedNotificationEventElement(doc, dataChangedNotificationEventElement, change);
229 notificationElement.appendChild(dataChangedNotificationEventElement);
232 final ByteArrayOutputStream out = new ByteArrayOutputStream();
233 final Transformer transformer = FACTORY.newTransformer();
234 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
235 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
236 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
237 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
238 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
239 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, Charsets.UTF_8)));
240 final byte[] charData = out.toByteArray();
241 return new String(charData, "UTF-8");
242 } catch (TransformerException | UnsupportedEncodingException e) {
243 final String msg = "Error during transformation of Document into String";
250 * Formats data specified by RFC3339.
254 * @return Data specified by RFC3339.
256 private String toRFC3339(final Date d) {
257 return RFC3339_PATTERN.matcher(rfc3339.format(d)).replaceAll("$1:$2");
261 * Creates {@link Document} document.
262 * @return {@link Document} document.
264 private Document createDocument() {
265 final DocumentBuilder bob;
267 bob = DBF.newDocumentBuilder();
268 } catch (final ParserConfigurationException e) {
271 return bob.newDocument();
275 * Adds values to data changed notification event element.
279 * @param dataChangedNotificationEventElement
282 * {@link AsyncDataChangeEvent}
284 private void addValuesToDataChangedNotificationEventElement(final Document doc,
285 final Element dataChangedNotificationEventElement,
286 final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
287 addValuesFromDataToElement(doc, change.getCreatedData().keySet(), dataChangedNotificationEventElement,
289 if (change.getCreatedData().isEmpty()) {
290 addValuesFromDataToElement(doc, change.getUpdatedData().keySet(), dataChangedNotificationEventElement,
293 addValuesFromDataToElement(doc, change.getRemovedPaths(), dataChangedNotificationEventElement,
298 * Adds values from data to element.
303 * Set of {@link YangInstanceIdentifier}.
309 private void addValuesFromDataToElement(final Document doc, final Set<YangInstanceIdentifier> data, final Element element,
310 final Operation operation) {
311 if (data == null || data.isEmpty()) {
314 for (final YangInstanceIdentifier path : data) {
315 if (!ControllerContext.getInstance().isNodeMixin(path)) {
316 final Node node = createDataChangeEventElement(doc, path, operation);
317 element.appendChild(node);
324 * Creates changed event element from data.
329 * Path to data in data store.
332 * @return {@link Node} node represented by changed event element.
334 private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier path, final Operation operation) {
335 final Element dataChangeEventElement = doc.createElement("data-change-event");
336 final Element pathElement = doc.createElement("path");
337 addPathAsValueToElement(path, pathElement);
338 dataChangeEventElement.appendChild(pathElement);
340 final Element operationElement = doc.createElement("operation");
341 operationElement.setTextContent(operation.value);
342 dataChangeEventElement.appendChild(operationElement);
344 return dataChangeEventElement;
349 * Adds path as value to element.
352 * Path to data in data store.
356 private void addPathAsValueToElement(final YangInstanceIdentifier path, final Element element) {
357 // Map< key = namespace, value = prefix>
358 final Map<String, String> prefixes = new HashMap<>();
359 final YangInstanceIdentifier normalizedPath = ControllerContext.getInstance().toXpathRepresentation(path);
360 final StringBuilder textContent = new StringBuilder();
362 // FIXME: BUG-1281: this is duplicated code from yangtools (BUG-1275)
363 for (final PathArgument pathArgument : normalizedPath.getPathArguments()) {
364 if (pathArgument instanceof YangInstanceIdentifier.AugmentationIdentifier) {
367 textContent.append("/");
368 writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
369 if (pathArgument instanceof NodeIdentifierWithPredicates) {
370 final Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
371 for (final QName keyValue : predicates.keySet()) {
372 final String predicateValue = String.valueOf(predicates.get(keyValue));
373 textContent.append("[");
374 writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
375 textContent.append("='");
376 textContent.append(predicateValue);
377 textContent.append("'");
378 textContent.append("]");
380 } else if (pathArgument instanceof NodeWithValue) {
381 textContent.append("[.='");
382 textContent.append(((NodeWithValue) pathArgument).getValue());
383 textContent.append("'");
384 textContent.append("]");
387 element.setTextContent(textContent.toString());
391 * Writes identifier that consists of prefix and QName.
400 * Map of namespaces and prefixes.
402 private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
403 final QName qName, final Map<String, String> prefixes) {
404 final String namespace = qName.getNamespace().toString();
405 String prefix = prefixes.get(namespace);
406 if (prefix == null) {
407 prefix = generateNewPrefix(prefixes.values());
410 element.setAttribute("xmlns:" + prefix, namespace);
411 textContent.append(prefix);
412 prefixes.put(namespace, prefix);
414 textContent.append(":");
415 textContent.append(qName.getLocalName());
419 * Generates new prefix which consists of four random characters <a-z>.
422 * Collection of prefixes.
423 * @return New prefix which consists of four random characters <a-z>.
425 private static String generateNewPrefix(final Collection<String> prefixes) {
426 StringBuilder result = null;
427 final Random random = new Random();
429 result = new StringBuilder();
430 for (int i = 0; i < 4; i++) {
431 final int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
432 result.append(Character.toChars(randomNumber));
434 } while (prefixes.contains(result.toString()));
436 return result.toString();
440 * Gets path pointed to data in data store.
442 * @return Path pointed to data in data store.
444 public YangInstanceIdentifier getPath() {
449 * Sets {@link ListenerRegistration} registration.
451 * @param registration
452 * ListenerRegistration<DataChangeListener>
454 public void setRegistration(final ListenerRegistration<DOMDataChangeListener> registration) {
455 this.registration = registration;
459 * Gets the name of the stream.
461 * @return The name of the stream.
463 public String getStreamName() {
468 * Removes all subscribers and unregisters event bus change recorder form event bus.
470 public void close() throws Exception {
471 subscribers = new ConcurrentSet<>();
472 registration.close();
474 eventBus.unregister(eventBusChangeRecorder);
478 * Checks if {@link ListenerRegistration} registration exist.
480 * @return True if exist, false otherwise.
482 public boolean isListening() {
483 return registration == null ? false : true;
487 * Creates event of type {@link EventType#REGISTER}, set {@link Channel} subscriber to the event and post event into
493 public void addSubscriber(final Channel subscriber) {
494 if (!subscriber.isActive()) {
495 LOG.debug("Channel is not active between websocket server and subscriber {}" + subscriber.remoteAddress());
497 final Event event = new Event(EventType.REGISTER);
498 event.setSubscriber(subscriber);
499 eventBus.post(event);
503 * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel} subscriber to the event and posts event
508 public void removeSubscriber(final Channel subscriber) {
509 LOG.debug("Subscriber {} is removed.", subscriber.remoteAddress());
510 final Event event = new Event(EventType.DEREGISTER);
511 event.setSubscriber(subscriber);
512 eventBus.post(event);
516 * Checks if exists at least one {@link Channel} subscriber.
518 * @return True if exist at least one {@link Channel} subscriber, false otherwise.
520 public boolean hasSubscribers() {
521 return !subscribers.isEmpty();
525 * Consists of two types {@link Store#CONFIG} and {@link Store#OPERATION}.
527 private static enum Store {
529 OPERATION("operation");
531 private final String value;
533 private Store(final String value) {
539 * Consists of three types {@link Operation#CREATED}, {@link Operation#UPDATED} and {@link Operation#DELETED}.
541 private static enum Operation {
546 private final String value;
548 private Operation(final String value) {