4177ca19a67318316a9a49aa9265c4971dba5d3d
[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         return switch (outputType) {
52             case JSON -> JSON_FORMATTER_FACTORY;
53             case XML -> XMLDataTreeCandidateFormatter.FACTORY;
54         };
55     }
56
57     @Override
58     public void onInitialData() {
59         // No-op
60     }
61
62     @Override
63     @SuppressWarnings("checkstyle:IllegalCatch")
64     public void onDataTreeChanged(final List<DataTreeCandidate> dataTreeCandidates) {
65         final Instant now = Instant.now();
66         if (!checkStartStop(now)) {
67             return;
68         }
69
70         final Optional<String> maybeData;
71         try {
72             maybeData = formatter().eventData(schemaHandler.get(), dataTreeCandidates, now, getLeafNodesOnly(),
73                     isSkipNotificationData());
74         } catch (final Exception e) {
75             LOG.error("Failed to process notification {}",
76                     dataTreeCandidates.stream().map(Object::toString).collect(Collectors.joining(",")), e);
77             return;
78         }
79
80         if (maybeData.isPresent()) {
81             post(maybeData.get());
82         }
83     }
84
85     /**
86      * Get path pointed to data in data store.
87      *
88      * @return Path pointed to data in data store.
89      */
90     public YangInstanceIdentifier getPath() {
91         return path();
92     }
93
94     /**
95      * Register data change listener in DOM data broker and set it to listener on stream.
96      *
97      * @param domDataBroker data broker for register data change listener
98      * @param datastore     {@link LogicalDatastoreType}
99      */
100     public final synchronized void listen(final DOMDataBroker domDataBroker, final LogicalDatastoreType datastore) {
101         if (!isListening()) {
102             final DOMDataTreeChangeService changeService = domDataBroker.getExtensions()
103                 .getInstance(DOMDataTreeChangeService.class);
104             if (changeService == null) {
105                 throw new UnsupportedOperationException("DOMDataBroker does not support the DOMDataTreeChangeService");
106             }
107
108             setRegistration(changeService.registerDataTreeChangeListener(
109                 new DOMDataTreeIdentifier(datastore, getPath()), this));
110         }
111     }
112 }