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;
16 import io.netty.channel.Channel;
17 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
18 import io.netty.util.internal.ConcurrentSet;
20 import java.io.ByteArrayOutputStream;
21 import java.io.OutputStreamWriter;
22 import java.io.UnsupportedEncodingException;
23 import java.text.SimpleDateFormat;
24 import java.util.Collection;
25 import java.util.Date;
26 import java.util.HashMap;
28 import java.util.Map.Entry;
29 import java.util.Random;
31 import java.util.concurrent.Executors;
32 import java.util.regex.Pattern;
34 import javax.activation.UnsupportedDataTypeException;
35 import javax.xml.parsers.DocumentBuilder;
36 import javax.xml.parsers.DocumentBuilderFactory;
37 import javax.xml.parsers.ParserConfigurationException;
38 import javax.xml.transform.OutputKeys;
39 import javax.xml.transform.Transformer;
40 import javax.xml.transform.TransformerException;
41 import javax.xml.transform.TransformerFactory;
42 import javax.xml.transform.dom.DOMSource;
43 import javax.xml.transform.stream.StreamResult;
45 import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent;
46 import org.opendaylight.controller.sal.core.api.data.DataChangeListener;
47 import org.opendaylight.controller.sal.rest.impl.XmlMapper;
48 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
49 import org.opendaylight.yangtools.concepts.ListenerRegistration;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
52 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
54 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
55 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
56 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Document;
60 import org.w3c.dom.Element;
61 import org.w3c.dom.Node;
64 * {@link ListenerAdapter} is responsible to track events, which occurred by
65 * changing data in data source.
67 public class ListenerAdapter implements DataChangeListener {
69 private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class);
70 private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();
71 private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
72 private static final Pattern RFC3339_PATTERN = Pattern.compile("(\\d\\d)(\\d\\d)$");
74 private final XmlMapper xmlMapper = new XmlMapper();
75 private final SimpleDateFormat rfc3339 = new SimpleDateFormat(
76 "yyyy-MM-dd'T'hh:mm:ssZ");
78 private final InstanceIdentifier path;
79 private ListenerRegistration<DataChangeListener> registration;
80 private final String streamName;
81 private Set<Channel> subscribers = new ConcurrentSet<>();
82 private final EventBus eventBus;
83 private final EventBusChangeRecorder eventBusChangeRecorder;
87 * Creates new {@link ListenerAdapter} listener specified by path and stream
91 * Path to data in data store.
93 * The name of the stream.
95 ListenerAdapter(final InstanceIdentifier path, final String streamName) {
96 Preconditions.checkNotNull(path);
98 .checkArgument(streamName != null && !streamName.isEmpty());
100 this.streamName = streamName;
101 eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor());
102 eventBusChangeRecorder = new EventBusChangeRecorder();
103 eventBus.register(eventBusChangeRecorder);
107 public void onDataChanged(
108 final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
109 if (!change.getCreatedConfigurationData().isEmpty()
110 || !change.getCreatedOperationalData().isEmpty()
111 || !change.getUpdatedConfigurationData().isEmpty()
112 || !change.getUpdatedOperationalData().isEmpty()
113 || !change.getRemovedConfigurationData().isEmpty()
114 || !change.getRemovedOperationalData().isEmpty()) {
115 String xml = prepareXmlFrom(change);
116 Event event = new Event(EventType.NOTIFY);
118 eventBus.post(event);
123 * Tracks events of data change by customer.
125 private final class EventBusChangeRecorder {
127 public void recordCustomerChange(final Event event) {
128 if (event.getType() == EventType.REGISTER) {
129 Channel subscriber = event.getSubscriber();
130 if (!subscribers.contains(subscriber)) {
131 subscribers.add(subscriber);
133 } else if (event.getType() == EventType.DEREGISTER) {
134 subscribers.remove(event.getSubscriber());
136 .removeListenerIfNoSubscriberExists(ListenerAdapter.this);
137 } else if (event.getType() == EventType.NOTIFY) {
138 for (Channel subscriber : subscribers) {
139 if (subscriber.isActive()) {
140 LOG.debug("Data are sent to subscriber {}:",
141 subscriber.remoteAddress());
142 subscriber.writeAndFlush(new TextWebSocketFrame(event
146 "Subscriber {} is removed - channel is not active yet.",
147 subscriber.remoteAddress());
148 subscribers.remove(subscriber);
156 * Represents event of specific {@link EventType} type, holds data and
157 * {@link Channel} subscriber.
159 private final class Event {
160 private final EventType type;
161 private Channel subscriber;
165 * Creates new event specified by {@link EventType} type.
170 public Event(final EventType type) {
175 * Gets the {@link Channel} subscriber.
179 public Channel getSubscriber() {
184 * Sets subscriber for event.
189 public void setSubscriber(final Channel subscriber) {
190 this.subscriber = subscriber;
196 * @return String representation of event data.
198 public String getData() {
208 public void setData(final String data) {
215 * @return The type of the event.
217 public EventType getType() {
225 private enum EventType {
226 REGISTER, DEREGISTER, NOTIFY;
230 * Prepare data in printable form and transform it to String.
234 * @return Data in printable form.
236 private String prepareXmlFrom(
237 final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
238 Document doc = createDocument();
239 Element notificationElement = doc.createElementNS(
240 "urn:ietf:params:xml:ns:netconf:notification:1.0",
242 doc.appendChild(notificationElement);
244 Element eventTimeElement = doc.createElement("eventTime");
245 eventTimeElement.setTextContent(toRFC3339(new Date()));
246 notificationElement.appendChild(eventTimeElement);
248 Element dataChangedNotificationEventElement = doc.createElementNS(
249 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote",
250 "data-changed-notification");
251 addValuesToDataChangedNotificationEventElement(doc,
252 dataChangedNotificationEventElement, change);
253 notificationElement.appendChild(dataChangedNotificationEventElement);
256 ByteArrayOutputStream out = new ByteArrayOutputStream();
257 Transformer transformer = FACTORY.newTransformer();
258 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
259 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
260 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
261 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
262 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
263 transformer.transform(new DOMSource(doc), new StreamResult(
264 new OutputStreamWriter(out, Charsets.UTF_8)));
265 byte[] charData = out.toByteArray();
266 return new String(charData, "UTF-8");
267 } catch (TransformerException | UnsupportedEncodingException e) {
268 String msg = "Error during transformation of Document into String";
275 * Formats data specified by RFC3339.
279 * @return Data specified by RFC3339.
281 private String toRFC3339(final Date d) {
282 return RFC3339_PATTERN.matcher(rfc3339.format(d)).replaceAll("$1:$2");
286 * Creates {@link Document} document.
288 * @return {@link Document} document.
290 private Document createDocument() {
291 final DocumentBuilder bob;
293 bob = DBF.newDocumentBuilder();
294 } catch (ParserConfigurationException e) {
297 return bob.newDocument();
301 * Adds values to data changed notification event element.
305 * @param dataChangedNotificationEventElement
308 * {@link DataChangeEvent}
310 private void addValuesToDataChangedNotificationEventElement(final Document doc,
311 final Element dataChangedNotificationEventElement,
312 final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
313 addValuesFromDataToElement(doc, change.getCreatedConfigurationData(),
314 dataChangedNotificationEventElement, Store.CONFIG,
316 addValuesFromDataToElement(doc, change.getCreatedOperationalData(),
317 dataChangedNotificationEventElement, Store.OPERATION,
319 if (change.getCreatedConfigurationData().isEmpty()) {
320 addValuesFromDataToElement(doc,
321 change.getUpdatedConfigurationData(),
322 dataChangedNotificationEventElement, Store.CONFIG,
325 if (change.getCreatedOperationalData().isEmpty()) {
326 addValuesFromDataToElement(doc, change.getUpdatedOperationalData(),
327 dataChangedNotificationEventElement, Store.OPERATION,
330 addValuesFromDataToElement(doc, change.getRemovedConfigurationData(),
331 dataChangedNotificationEventElement, Store.CONFIG,
333 addValuesFromDataToElement(doc, change.getRemovedOperationalData(),
334 dataChangedNotificationEventElement, Store.OPERATION,
339 * Adds values from data to element.
344 * Set of {@link InstanceIdentifier}.
352 private void addValuesFromDataToElement(final Document doc,
353 final Set<InstanceIdentifier> data, final Element element, final Store store,
354 final Operation operation) {
355 if (data == null || data.isEmpty()) {
358 for (InstanceIdentifier path : data) {
359 Node node = createDataChangeEventElement(doc, path, null, store,
361 element.appendChild(node);
366 * Adds values from data to element.
371 * Map of {@link InstanceIdentifier} and {@link CompositeNode}.
379 private void addValuesFromDataToElement(final Document doc,
380 final Map<InstanceIdentifier, CompositeNode> data, final Element element,
381 final Store store, final Operation operation) {
382 if (data == null || data.isEmpty()) {
385 for (Entry<InstanceIdentifier, CompositeNode> entry : data.entrySet()) {
386 Node node = createDataChangeEventElement(doc, entry.getKey(),
387 entry.getValue(), store, operation);
388 element.appendChild(node);
393 * Creates changed event element from data.
398 * Path to data in data store.
400 * {@link CompositeNode}
405 * @return {@link Node} node represented by changed event element.
407 private Node createDataChangeEventElement(final Document doc,
408 final InstanceIdentifier path, final CompositeNode data, final Store store,
409 final Operation operation) {
410 Element dataChangeEventElement = doc.createElement("data-change-event");
412 Element pathElement = doc.createElement("path");
413 addPathAsValueToElement(path, pathElement);
414 dataChangeEventElement.appendChild(pathElement);
416 Element storeElement = doc.createElement("store");
417 storeElement.setTextContent(store.value);
418 dataChangeEventElement.appendChild(storeElement);
420 Element operationElement = doc.createElement("operation");
421 operationElement.setTextContent(operation.value);
422 dataChangeEventElement.appendChild(operationElement);
425 Element dataElement = doc.createElement("data");
426 Node dataAnyXml = translateToXml(path, data);
427 Node adoptedNode = doc.adoptNode(dataAnyXml);
428 dataElement.appendChild(adoptedNode);
429 dataChangeEventElement.appendChild(dataElement);
432 return dataChangeEventElement;
436 * Translates {@link CompositeNode} data to XML format.
439 * Path to data in data store.
441 * {@link CompositeNode}
442 * @return Data in XML format.
444 private Node translateToXml(final InstanceIdentifier path, final CompositeNode data) {
445 DataNodeContainer schemaNode = ControllerContext.getInstance()
446 .getDataNodeContainerFor(path);
447 if (schemaNode == null) {
449 "Path '{}' contains node with unsupported type (supported type is Container or List) or some node was not found.",
454 Document xml = xmlMapper.write(data, schemaNode);
455 return xml.getFirstChild();
456 } catch (UnsupportedDataTypeException e) {
458 "Error occured during translation of notification to XML.",
465 * Adds path as value to element.
468 * Path to data in data store.
472 private void addPathAsValueToElement(final InstanceIdentifier path,
473 final Element element) {
474 // Map< key = namespace, value = prefix>
475 Map<String, String> prefixes = new HashMap<>();
476 InstanceIdentifier instanceIdentifier = path;
477 StringBuilder textContent = new StringBuilder();
479 // FIXME: BUG-1281: this is duplicated code from yangtools (BUG-1275)
480 for (PathArgument pathArgument : instanceIdentifier.getPathArguments()) {
481 textContent.append("/");
482 writeIdentifierWithNamespacePrefix(element, textContent,
483 pathArgument.getNodeType(), prefixes);
484 if (pathArgument instanceof NodeIdentifierWithPredicates) {
485 Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument)
487 for (QName keyValue : predicates.keySet()) {
488 String predicateValue = String.valueOf(predicates
490 textContent.append("[");
491 writeIdentifierWithNamespacePrefix(element, textContent,
493 textContent.append("='");
494 textContent.append(predicateValue);
495 textContent.append("'");
496 textContent.append("]");
498 } else if (pathArgument instanceof NodeWithValue) {
499 textContent.append("[.='");
500 textContent.append(((NodeWithValue) pathArgument).getValue());
501 textContent.append("'");
502 textContent.append("]");
505 element.setTextContent(textContent.toString());
509 * Writes identifier that consists of prefix and QName.
518 * Map of namespaces and prefixes.
520 private static void writeIdentifierWithNamespacePrefix(final Element element,
521 final StringBuilder textContent, final QName qName, final Map<String, String> prefixes) {
522 String namespace = qName.getNamespace().toString();
523 String prefix = prefixes.get(namespace);
524 if (prefix == null) {
525 prefix = qName.getPrefix();
526 if (prefix == null || prefix.isEmpty()
527 || prefixes.containsValue(prefix)) {
528 prefix = generateNewPrefix(prefixes.values());
532 element.setAttribute("xmlns:" + prefix, namespace);
533 textContent.append(prefix);
534 prefixes.put(namespace, prefix);
536 textContent.append(":");
537 textContent.append(qName.getLocalName());
541 * Generates new prefix which consists of four random characters <a-z>.
544 * Collection of prefixes.
545 * @return New prefix which consists of four random characters <a-z>.
547 private static String generateNewPrefix(final Collection<String> prefixes) {
548 StringBuilder result = null;
549 Random random = new Random();
551 result = new StringBuilder();
552 for (int i = 0; i < 4; i++) {
553 int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
554 result.append(Character.toChars(randomNumber));
556 } while (prefixes.contains(result.toString()));
558 return result.toString();
562 * Gets path pointed to data in data store.
564 * @return Path pointed to data in data store.
566 public InstanceIdentifier getPath() {
571 * Sets {@link ListenerRegistration} registration.
573 * @param registration
574 * ListenerRegistration<DataChangeListener>
576 public void setRegistration(
577 final ListenerRegistration<DataChangeListener> registration) {
578 this.registration = registration;
582 * Gets the name of the stream.
584 * @return The name of the stream.
586 public String getStreamName() {
591 * Removes all subscribers and unregisters event bus change recorder form
594 public void close() throws Exception {
595 subscribers = new ConcurrentSet<>();
596 registration.close();
598 eventBus.unregister(eventBusChangeRecorder);
602 * Checks if {@link ListenerRegistration} registration exist.
604 * @return True if exist, false otherwise.
606 public boolean isListening() {
607 return registration == null ? false : true;
611 * Creates event of type {@link EventType#REGISTER}, set {@link Channel}
612 * subscriber to the event and post event into event bus.
617 public void addSubscriber(final Channel subscriber) {
618 if (!subscriber.isActive()) {
619 LOG.debug("Channel is not active between websocket server and subscriber {}"
620 + subscriber.remoteAddress());
622 Event event = new Event(EventType.REGISTER);
623 event.setSubscriber(subscriber);
624 eventBus.post(event);
628 * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel}
629 * subscriber to the event and posts event into event bus.
633 public void removeSubscriber(final Channel subscriber) {
634 LOG.debug("Subscriber {} is removed.", subscriber.remoteAddress());
635 Event event = new Event(EventType.DEREGISTER);
636 event.setSubscriber(subscriber);
637 eventBus.post(event);
641 * Checks if exists at least one {@link Channel} subscriber.
643 * @return True if exist at least one {@link Channel} subscriber, false
646 public boolean hasSubscribers() {
647 return !subscribers.isEmpty();
651 * Consists of two types {@link Store#CONFIG} and {@link Store#OPERATION}.
653 private static enum Store {
654 CONFIG("config"), OPERATION("operation");
656 private final String value;
658 private Store(final String value) {
664 * Consists of three types {@link Operation#CREATED},
665 * {@link Operation#UPDATED} and {@link Operation#DELETED}.
667 private static enum Operation {
668 CREATED("created"), UPDATED("updated"), DELETED("deleted");
670 private final String value;
672 private Operation(final String value) {