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