Split out restconf-api
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / listeners / AbstractCommonSubscriber.java
1 /*
2  * Copyright (c) 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 com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.base.MoreObjects;
15 import java.time.Instant;
16 import java.time.format.DateTimeFormatter;
17 import java.time.format.DateTimeFormatterBuilder;
18 import java.time.format.DateTimeParseException;
19 import java.time.temporal.ChronoField;
20 import java.time.temporal.TemporalAccessor;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.Set;
24 import java.util.concurrent.ExecutionException;
25 import javax.xml.xpath.XPathExpressionException;
26 import org.checkerframework.checker.lock.qual.GuardedBy;
27 import org.checkerframework.checker.lock.qual.Holding;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
30 import org.opendaylight.restconf.nb.rfc8040.NotificationQueryParams;
31 import org.opendaylight.restconf.nb.rfc8040.streams.StreamSessionHandler;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
33 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
34 import org.opendaylight.yangtools.concepts.Registration;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * Features of subscribing part of both notifications.
41  */
42 abstract class AbstractCommonSubscriber<P, T> extends AbstractNotificationsData implements BaseListenerInterface {
43     private static final Logger LOG = LoggerFactory.getLogger(AbstractCommonSubscriber.class);
44     private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
45         .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
46         .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
47         .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
48         .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
49         .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
50         .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
51         .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
52         .appendOffset("+HH:MM", "Z").toFormatter();
53
54     private final EventFormatterFactory<T> formatterFactory;
55     private final NotificationOutputType outputType;
56     private final String streamName;
57     private final P path;
58
59     @GuardedBy("this")
60     private final Set<StreamSessionHandler> subscribers = new HashSet<>();
61     @GuardedBy("this")
62     private Registration registration;
63
64     // FIXME: these should be final
65     private Instant start = null;
66     private Instant stop = null;
67     private boolean leafNodesOnly = false;
68     private boolean skipNotificationData = false;
69     private boolean changedLeafNodesOnly = false;
70     private EventFormatter<T> formatter;
71
72     AbstractCommonSubscriber(final QName lastQName, final String streamName, final P path,
73             final NotificationOutputType outputType, final EventFormatterFactory<T> formatterFactory) {
74         super(lastQName);
75         this.streamName = requireNonNull(streamName);
76         checkArgument(!streamName.isEmpty());
77         this.path = requireNonNull(path);
78
79         this.outputType = requireNonNull(outputType);
80         this.formatterFactory = requireNonNull(formatterFactory);
81         formatter = formatterFactory.getFormatter();
82     }
83
84     @Override
85     public final String getStreamName() {
86         return streamName;
87     }
88
89     @Override
90     public final String getOutputType() {
91         return outputType.getName();
92     }
93
94     @Override
95     public final synchronized boolean hasSubscribers() {
96         return !subscribers.isEmpty();
97     }
98
99     @Override
100     public final synchronized Set<StreamSessionHandler> getSubscribers() {
101         return new HashSet<>(subscribers);
102     }
103
104     @Override
105     public final synchronized void close() throws InterruptedException, ExecutionException {
106         if (registration != null) {
107             registration.close();
108             registration = null;
109         }
110         deleteDataInDS().get();
111         subscribers.clear();
112     }
113
114     @Override
115     public synchronized void addSubscriber(final StreamSessionHandler subscriber) {
116         final boolean isConnected = subscriber.isConnected();
117         checkState(isConnected);
118         LOG.debug("Subscriber {} is added.", subscriber);
119         subscribers.add(subscriber);
120     }
121
122     @Override
123     public synchronized void removeSubscriber(final StreamSessionHandler subscriber) {
124         final boolean isConnected = subscriber.isConnected();
125         checkState(isConnected);
126         LOG.debug("Subscriber {} is removed", subscriber);
127         subscribers.remove(subscriber);
128         if (!hasSubscribers()) {
129             ListenersBroker.getInstance().removeAndCloseListener(this);
130         }
131     }
132
133     public final Instant getStart() {
134         return start;
135     }
136
137     /**
138      * Set query parameters for listener.
139      *
140      * @param params NotificationQueryParams to use.
141      */
142     public final void setQueryParams(final NotificationQueryParams params) {
143         final var startTime = params.startTime();
144         start = startTime == null ? Instant.now() : parseDateAndTime(startTime.value());
145
146         final var stopTime = params.stopTime();
147         stop = stopTime == null ? null : parseDateAndTime(stopTime.value());
148
149         final var leafNodes = params.leafNodesOnly();
150         leafNodesOnly = leafNodes == null ? false : leafNodes.value();
151
152         final var skipData = params.skipNotificationData();
153         skipNotificationData = skipData == null ? false : skipData.value();
154
155         final var changedLeafNodes = params.changedLeafNodesOnly();
156         changedLeafNodesOnly = changedLeafNodes == null ? false : changedLeafNodes.value();
157
158         final var filter = params.filter();
159         final String filterValue = filter == null ? null : filter.paramValue();
160         if (filterValue != null && !filterValue.isEmpty()) {
161             try {
162                 formatter = formatterFactory.getFormatter(filterValue);
163             } catch (XPathExpressionException e) {
164                 throw new IllegalArgumentException("Failed to get filter", e);
165             }
166         } else {
167             formatter = formatterFactory.getFormatter();
168         }
169     }
170
171     final P path() {
172         return path;
173     }
174
175     /**
176      * Check whether this query should only notify about leaf node changes.
177      *
178      * @return true if this query should only notify about leaf node changes
179      */
180     final boolean getLeafNodesOnly() {
181         return leafNodesOnly;
182     }
183
184     /**
185      * Check whether this query should only notify about leaf node changes and report only changed nodes.
186      *
187      * @return true if this query should only notify about leaf node changes and report only changed nodes
188      */
189     final boolean getChangedLeafNodesOnly() {
190         return changedLeafNodesOnly;
191     }
192
193     /**
194      * Check whether this query should notify changes without data.
195      *
196      * @return true if this query should notify about changes with  data
197      */
198     final boolean isSkipNotificationData() {
199         return skipNotificationData;
200     }
201
202     final EventFormatter<T> formatter() {
203         return formatter;
204     }
205
206     /**
207      * Sets {@link Registration} registration.
208      *
209      * @param registration a listener registration registration.
210      */
211     @Holding("this")
212     final void setRegistration(final Registration registration) {
213         this.registration = requireNonNull(registration);
214     }
215
216     /**
217      * Checks if {@link Registration} registration exists.
218      *
219      * @return {@code true} if exists, {@code false} otherwise.
220      */
221     @Holding("this")
222     final boolean isListening() {
223         return registration != null;
224     }
225
226     /**
227      * Post data to subscribed SSE session handlers.
228      *
229      * @param data Data of incoming notifications.
230      */
231     synchronized void post(final String data) {
232         final Iterator<StreamSessionHandler> iterator = subscribers.iterator();
233         while (iterator.hasNext()) {
234             final StreamSessionHandler subscriber = iterator.next();
235             final boolean isConnected = subscriber.isConnected();
236             if (isConnected) {
237                 subscriber.sendDataMessage(data);
238                 LOG.debug("Data was sent to subscriber {} on connection {}:", this, subscriber);
239             } else {
240                 // removal is probably not necessary, because it will be removed explicitly soon after invocation of
241                 // onWebSocketClosed(..) in handler; but just to be sure ...
242                 iterator.remove();
243                 LOG.debug("Subscriber for {} was removed - web-socket session is not open.", this);
244             }
245         }
246     }
247
248     @SuppressWarnings("checkstyle:IllegalCatch")
249     final boolean checkStartStop(final Instant now) {
250         if (stop != null) {
251             if (start.compareTo(now) < 0 && stop.compareTo(now) > 0) {
252                 return true;
253             }
254             if (stop.compareTo(now) < 0) {
255                 try {
256                     close();
257                 } catch (final Exception e) {
258                     throw new RestconfDocumentedException("Problem with unregister listener." + e);
259                 }
260             }
261         } else if (start != null) {
262             if (start.compareTo(now) < 0) {
263                 start = null;
264                 return true;
265             }
266         } else {
267             return true;
268         }
269         return false;
270     }
271
272     @Override
273     public final String toString() {
274         return MoreObjects.toStringHelper(this)
275             .add("path", path)
276             .add("stream-name", streamName)
277             .add("output-type", getOutputType())
278             .toString();
279     }
280
281     /**
282      * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
283      * to {@link Instant} format.
284      *
285      * @param uriValue Start-time or stop-time as string in {@link DateAndTime} format.
286      * @return Parsed {@link Instant} by entry.
287      */
288     private static @NonNull Instant parseDateAndTime(final DateAndTime dateAndTime) {
289         final TemporalAccessor accessor;
290         try {
291             accessor = FORMATTER.parse(dateAndTime.getValue());
292         } catch (final DateTimeParseException e) {
293             throw new RestconfDocumentedException("Cannot parse of value in date: " + dateAndTime, e);
294         }
295         return Instant.from(accessor);
296     }
297 }