2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.streams.listeners;
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;
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;
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.opendaylight.yangtools.yang.common.QName;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
41 * Features of subscribing part of both notifications.
43 abstract class AbstractCommonSubscriber<T> extends AbstractNotificationsData implements BaseListenerInterface {
44 private static final Logger LOG = LoggerFactory.getLogger(AbstractCommonSubscriber.class);
45 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
46 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
47 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
48 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
49 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
50 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
51 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
52 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
53 .appendOffset("+HH:MM", "Z").toFormatter();
55 private final EventFormatterFactory<T> formatterFactory;
56 private final NotificationOutputType outputType;
57 private final String streamName;
60 private final Set<StreamSessionHandler> subscribers = new HashSet<>();
62 private Registration registration;
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;
72 AbstractCommonSubscriber(final QName lastQName, final String streamName, final NotificationOutputType outputType,
73 final EventFormatterFactory<T> formatterFactory) {
75 this.streamName = requireNonNull(streamName);
76 checkArgument(!streamName.isEmpty());
78 this.outputType = requireNonNull(outputType);
79 this.formatterFactory = requireNonNull(formatterFactory);
80 formatter = formatterFactory.getFormatter();
84 public final String getStreamName() {
89 public final String getOutputType() {
90 return outputType.getName();
94 public final synchronized boolean hasSubscribers() {
95 return !subscribers.isEmpty();
99 public final synchronized Set<StreamSessionHandler> getSubscribers() {
100 return new HashSet<>(subscribers);
104 public final synchronized void close() throws InterruptedException, ExecutionException {
105 if (registration != null) {
106 registration.close();
109 deleteDataInDS().get();
114 public synchronized void addSubscriber(final StreamSessionHandler subscriber) {
115 final boolean isConnected = subscriber.isConnected();
116 checkState(isConnected);
117 LOG.debug("Subscriber {} is added.", subscriber);
118 subscribers.add(subscriber);
122 public synchronized void removeSubscriber(final StreamSessionHandler subscriber) {
123 subscribers.remove(subscriber);
124 LOG.debug("Subscriber {} is removed", subscriber);
125 if (!hasSubscribers()) {
126 ListenersBroker.getInstance().removeAndCloseListener(this);
130 public final Instant getStart() {
135 * Set query parameters for listener.
137 * @param params NotificationQueryParams to use.
139 public final void setQueryParams(final NotificationQueryParams params) {
140 final var startTime = params.startTime();
141 start = startTime == null ? Instant.now() : parseDateAndTime(startTime.value());
143 final var stopTime = params.stopTime();
144 stop = stopTime == null ? null : parseDateAndTime(stopTime.value());
146 final var leafNodes = params.leafNodesOnly();
147 leafNodesOnly = leafNodes != null && leafNodes.value();
149 final var skipData = params.skipNotificationData();
150 skipNotificationData = skipData != null && skipData.value();
152 final var changedLeafNodes = params.changedLeafNodesOnly();
153 changedLeafNodesOnly = changedLeafNodes != null && changedLeafNodes.value();
155 final var filter = params.filter();
156 final String filterValue = filter == null ? null : filter.paramValue();
157 if (filterValue != null && !filterValue.isEmpty()) {
159 formatter = formatterFactory.getFormatter(filterValue);
160 } catch (XPathExpressionException e) {
161 throw new IllegalArgumentException("Failed to get filter", e);
164 formatter = formatterFactory.getFormatter();
169 * Check whether this query should only notify about leaf node changes.
171 * @return true if this query should only notify about leaf node changes
173 final boolean getLeafNodesOnly() {
174 return leafNodesOnly;
178 * Check whether this query should only notify about leaf node changes and report only changed nodes.
180 * @return true if this query should only notify about leaf node changes and report only changed nodes
182 final boolean getChangedLeafNodesOnly() {
183 return changedLeafNodesOnly;
187 * Check whether this query should notify changes without data.
189 * @return true if this query should notify about changes with data
191 final boolean isSkipNotificationData() {
192 return skipNotificationData;
195 final EventFormatter<T> formatter() {
200 * Sets {@link Registration} registration.
202 * @param registration a listener registration registration.
205 final void setRegistration(final Registration registration) {
206 this.registration = requireNonNull(registration);
210 * Checks if {@link Registration} registration exists.
212 * @return {@code true} if exists, {@code false} otherwise.
215 final boolean isListening() {
216 return registration != null;
220 * Post data to subscribed SSE session handlers.
222 * @param data Data of incoming notifications.
224 synchronized void post(final String data) {
225 final Iterator<StreamSessionHandler> iterator = subscribers.iterator();
226 while (iterator.hasNext()) {
227 final StreamSessionHandler subscriber = iterator.next();
228 final boolean isConnected = subscriber.isConnected();
230 subscriber.sendDataMessage(data);
231 LOG.debug("Data was sent to subscriber {} on connection {}:", this, subscriber);
233 // removal is probably not necessary, because it will be removed explicitly soon after invocation of
234 // onWebSocketClosed(..) in handler; but just to be sure ...
236 LOG.debug("Subscriber for {} was removed - web-socket session is not open.", this);
241 @SuppressWarnings("checkstyle:IllegalCatch")
242 final boolean checkStartStop(final Instant now) {
244 if (start.compareTo(now) < 0 && stop.compareTo(now) > 0) {
247 if (stop.compareTo(now) < 0) {
250 } catch (final Exception e) {
251 throw new RestconfDocumentedException("Problem with unregister listener." + e);
254 } else if (start != null) {
255 if (start.compareTo(now) < 0) {
266 public final String toString() {
267 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
270 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
271 return helper.add("stream-name", streamName).add("output-type", getOutputType());
275 * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
276 * to {@link Instant} format.
278 * @param dateAndTime Start-time or stop-time as {@link DateAndTime} object.
279 * @return Parsed {@link Instant} by entry.
281 private static @NonNull Instant parseDateAndTime(final DateAndTime dateAndTime) {
282 final TemporalAccessor accessor;
284 accessor = FORMATTER.parse(dateAndTime.getValue());
285 } catch (final DateTimeParseException e) {
286 throw new RestconfDocumentedException("Cannot parse of value in date: " + dateAndTime, e);
288 return Instant.from(accessor);