22a422f2bc41eb867b2ddb123b0625da171c937d
[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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import java.time.Instant;
15 import java.util.Collection;
16 import java.util.List;
17 import java.util.Optional;
18 import java.util.stream.Collectors;
19 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
20 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
21 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
22 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
23 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
24 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
26 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
27 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source.
33  */
34 public class ListenerAdapter extends AbstractCommonSubscriber<Collection<DataTreeCandidate>>
35         implements ClusteredDOMDataTreeChangeListener {
36     private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class);
37     private static final DataTreeCandidateFormatterFactory JSON_FORMATTER_FACTORY =
38             JSONDataTreeCandidateFormatter.createFactory(JSONCodecFactorySupplier.RFC7951);
39
40     private final YangInstanceIdentifier path;
41
42     /**
43      * Creates new {@link ListenerAdapter} listener specified by path and stream name and register for subscribing.
44      *
45      * @param path       Path to data in data store.
46      * @param streamName The name of the stream.
47      * @param outputType Type of output on notification (JSON, XML).
48      */
49     @VisibleForTesting
50     public ListenerAdapter(final YangInstanceIdentifier path, final String streamName,
51             final NotificationOutputType outputType) {
52         super(streamName, outputType, getFormatterFactory(outputType));
53         this.path = requireNonNull(path);
54     }
55
56     private static DataTreeCandidateFormatterFactory getFormatterFactory(final NotificationOutputType outputType) {
57         return switch (outputType) {
58             case JSON -> JSON_FORMATTER_FACTORY;
59             case XML -> XMLDataTreeCandidateFormatter.FACTORY;
60         };
61     }
62
63     @Override
64     public void onInitialData() {
65         // No-op
66     }
67
68     @Override
69     @SuppressWarnings("checkstyle:IllegalCatch")
70     public void onDataTreeChanged(final List<DataTreeCandidate> dataTreeCandidates) {
71         final Instant now = Instant.now();
72         if (!checkStartStop(now)) {
73             return;
74         }
75
76         final Optional<String> maybeData;
77         try {
78             maybeData = formatter().eventData(databindProvider.currentContext().modelContext(), dataTreeCandidates, now,
79                 getLeafNodesOnly(), isSkipNotificationData(), getChangedLeafNodesOnly());
80         } catch (final Exception e) {
81             LOG.error("Failed to process notification {}",
82                     dataTreeCandidates.stream().map(Object::toString).collect(Collectors.joining(",")), e);
83             return;
84         }
85
86         maybeData.ifPresent(this::post);
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
117     @Override
118     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
119         return super.addToStringAttributes(helper.add("path", path));
120     }
121 }