b438f36b0223c50b501916933b8b4a412c40d7c3
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / listeners / ListenerAdapter.java
1 /*
2  * Copyright (c) 2014, 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 java.time.Instant;
12 import java.util.Collection;
13 import java.util.List;
14 import java.util.Optional;
15 import java.util.stream.Collectors;
16 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
17 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
18 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
19 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
20 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
21 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
23 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
24 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source.
30  */
31 public class ListenerAdapter extends AbstractCommonSubscriber<YangInstanceIdentifier, Collection<DataTreeCandidate>>
32         implements ClusteredDOMDataTreeChangeListener {
33     private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class);
34     private static final DataTreeCandidateFormatterFactory JSON_FORMATTER_FACTORY =
35             JSONDataTreeCandidateFormatter.createFactory(JSONCodecFactorySupplier.RFC7951);
36
37     /**
38      * Creates new {@link ListenerAdapter} listener specified by path and stream name and register for subscribing.
39      *
40      * @param path       Path to data in data store.
41      * @param streamName The name of the stream.
42      * @param outputType Type of output on notification (JSON, XML).
43      */
44     @VisibleForTesting
45     public ListenerAdapter(final YangInstanceIdentifier path, final String streamName,
46             final NotificationOutputType outputType) {
47         super(path.getLastPathArgument().getNodeType(), streamName, path, outputType, getFormatterFactory(outputType));
48     }
49
50     private static DataTreeCandidateFormatterFactory getFormatterFactory(final NotificationOutputType outputType) {
51         switch (outputType) {
52             case JSON:
53                 return JSON_FORMATTER_FACTORY;
54             case XML:
55                 return XMLDataTreeCandidateFormatter.FACTORY;
56             default:
57                 throw new IllegalArgumentException("Unsupported outputType" + outputType);
58         }
59     }
60
61     @Override
62     public void onInitialData() {
63         // No-op
64     }
65
66     @Override
67     @SuppressWarnings("checkstyle:IllegalCatch")
68     public void onDataTreeChanged(final List<DataTreeCandidate> dataTreeCandidates) {
69         final Instant now = Instant.now();
70         if (!checkStartStop(now)) {
71             return;
72         }
73
74         final Optional<String> maybeData;
75         try {
76             maybeData = formatter().eventData(schemaHandler.get(), dataTreeCandidates, now, getLeafNodesOnly(),
77                     isSkipNotificationData());
78         } catch (final Exception e) {
79             LOG.error("Failed to process notification {}",
80                     dataTreeCandidates.stream().map(Object::toString).collect(Collectors.joining(",")), e);
81             return;
82         }
83
84         if (maybeData.isPresent()) {
85             post(maybeData.get());
86         }
87     }
88
89     /**
90      * Get path pointed to data in data store.
91      *
92      * @return Path pointed to data in data store.
93      */
94     public YangInstanceIdentifier getPath() {
95         return path();
96     }
97
98     /**
99      * Register data change listener in DOM data broker and set it to listener on stream.
100      *
101      * @param domDataBroker data broker for register data change listener
102      * @param datastore     {@link LogicalDatastoreType}
103      */
104     public final synchronized void listen(final DOMDataBroker domDataBroker, final LogicalDatastoreType datastore) {
105         if (!isListening()) {
106             final DOMDataTreeChangeService changeService = domDataBroker.getExtensions()
107                 .getInstance(DOMDataTreeChangeService.class);
108             if (changeService == null) {
109                 throw new UnsupportedOperationException("DOMDataBroker does not support the DOMDataTreeChangeService");
110             }
111
112             setRegistration(changeService.registerDataTreeChangeListener(
113                 new DOMDataTreeIdentifier(datastore, getPath()), this));
114         }
115     }
116 }