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.rests.services.impl;
10 import static com.google.common.base.Preconditions.checkState;
13 import java.time.Instant;
14 import java.time.format.DateTimeFormatter;
15 import java.time.format.DateTimeFormatterBuilder;
16 import java.time.format.DateTimeParseException;
17 import java.time.temporal.ChronoField;
18 import java.time.temporal.TemporalAccessor;
19 import java.util.List;
20 import java.util.Map.Entry;
21 import java.util.Optional;
22 import javax.ws.rs.Path;
23 import javax.ws.rs.core.UriInfo;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
26 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
27 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
28 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
29 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
30 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
31 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
32 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
33 import org.opendaylight.restconf.nb.rfc8040.streams.Configuration;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
38 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.Module;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * Implementation of {@link RestconfStreamsSubscriptionService}.
50 public class RestconfStreamsSubscriptionServiceImpl implements RestconfStreamsSubscriptionService {
51 private static final Logger LOG = LoggerFactory.getLogger(RestconfStreamsSubscriptionServiceImpl.class);
52 private static final QName LOCATION_QNAME =
53 QName.create("subscribe:to:notification", "2016-10-28", "location").intern();
54 private static final NodeIdentifier LOCATION_NODEID = NodeIdentifier.create(LOCATION_QNAME);
55 private static final QName NOTIFI_QNAME = QName.create(LOCATION_QNAME, "notifi").intern();
56 private static final YangInstanceIdentifier LOCATION_PATH =
57 YangInstanceIdentifier.create(NodeIdentifier.create(NOTIFI_QNAME), LOCATION_NODEID);
59 private final SubscribeToStreamUtil streamUtils;
60 private final HandlersHolder handlersHolder;
63 * Initialize holder of handlers with holders as parameters.
65 * @param dataBroker {@link DOMDataBroker}
66 * @param notificationService {@link DOMNotificationService}
67 * @param schemaHandler
68 * handler of {@link SchemaContext}
69 * @param configuration
70 * configuration for restconf {@link Configuration}}
72 public RestconfStreamsSubscriptionServiceImpl(final DOMDataBroker dataBroker,
73 final DOMNotificationService notificationService, final SchemaContextHandler schemaHandler,
74 final Configuration configuration) {
75 handlersHolder = new HandlersHolder(dataBroker, notificationService, schemaHandler);
76 streamUtils = configuration.isUseSSE() ? SubscribeToStreamUtil.serverSentEvents()
77 : SubscribeToStreamUtil.webSockets();
81 public NormalizedNodePayload subscribeToStream(final String identifier, final UriInfo uriInfo) {
82 final NotificationQueryParams notificationQueryParams = NotificationQueryParams.fromUriInfo(uriInfo);
85 if (identifier.contains(RestconfStreamsConstants.DATA_SUBSCRIPTION)) {
86 response = streamUtils.subscribeToDataStream(identifier, uriInfo, notificationQueryParams, handlersHolder);
87 } else if (identifier.contains(RestconfStreamsConstants.NOTIFICATION_STREAM)) {
88 response = streamUtils.subscribeToYangStream(identifier, uriInfo, notificationQueryParams, handlersHolder);
90 final String msg = "Bad type of notification of sal-remote";
92 throw new RestconfDocumentedException(msg);
95 // prepare node with value of location
96 return NormalizedNodePayload.ofLocation(prepareIIDSubsStreamOutput(handlersHolder.getSchemaHandler()),
97 LOCATION_NODEID, response);
101 * Prepare InstanceIdentifierContext for Location leaf.
103 * @param schemaHandler Schema context handler.
104 * @return InstanceIdentifier of Location leaf.
106 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput(final SchemaContextHandler schemaHandler) {
107 final Optional<Module> module = schemaHandler.get().findModule(NOTIFI_QNAME.getModule());
108 checkState(module.isPresent());
109 final DataSchemaNode notify = module.get().dataChildByName(NOTIFI_QNAME);
110 checkState(notify instanceof ContainerSchemaNode, "Unexpected non-container %s", notify);
111 final DataSchemaNode location = ((ContainerSchemaNode) notify).dataChildByName(LOCATION_QNAME);
112 checkState(location != null, "Missing location");
114 return new InstanceIdentifierContext<SchemaNode>(LOCATION_PATH, location, null, schemaHandler.get());
118 * Holder of all handlers for notifications.
120 // FIXME: why do we even need this class?!
121 public static final class HandlersHolder {
122 private final DOMDataBroker dataBroker;
123 private final DOMNotificationService notificationService;
124 private final SchemaContextHandler schemaHandler;
126 private HandlersHolder(final DOMDataBroker dataBroker, final DOMNotificationService notificationService,
127 final SchemaContextHandler schemaHandler) {
128 this.dataBroker = dataBroker;
129 this.notificationService = notificationService;
130 this.schemaHandler = schemaHandler;
134 * Get {@link DOMDataBroker}.
136 * @return the dataBroker
138 public DOMDataBroker getDataBroker() {
143 * Get {@link DOMNotificationService}.
145 * @return the notificationService
147 public DOMNotificationService getNotificationServiceHandler() {
148 return notificationService;
152 * Get {@link SchemaContextHandler}.
154 * @return the schemaHandler
156 public SchemaContextHandler getSchemaHandler() {
157 return schemaHandler;
162 * Parser and holder of query paramteres from uriInfo for notifications.
164 public static final class NotificationQueryParams {
165 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
166 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
167 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
168 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
169 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
170 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
171 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
172 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
173 .appendOffset("+HH:MM", "Z").toFormatter();
175 private final Instant start;
176 private final Instant stop;
177 private final String filter;
178 private final boolean skipNotificationData;
180 private NotificationQueryParams(final Instant start, final Instant stop, final String filter,
181 final boolean skipNotificationData) {
182 this.start = start == null ? Instant.now() : start;
184 this.filter = filter;
185 this.skipNotificationData = skipNotificationData;
188 static NotificationQueryParams fromUriInfo(final UriInfo uriInfo) {
189 Instant start = null;
190 boolean startTimeUsed = false;
192 boolean stopTimeUsed = false;
193 String filter = null;
194 boolean filterUsed = false;
195 boolean skipNotificationDataUsed = false;
196 boolean skipNotificationData = false;
198 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
199 switch (entry.getKey()) {
201 if (!startTimeUsed) {
202 startTimeUsed = true;
203 start = parseDateFromQueryParam(entry);
205 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
211 stop = parseDateFromQueryParam(entry);
213 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
219 filter = entry.getValue().iterator().next();
222 case "odl-skip-notification-data":
223 if (!skipNotificationDataUsed) {
224 skipNotificationDataUsed = true;
225 skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
227 throw new RestconfDocumentedException(
228 "Odl-skip-notification-data parameter can be used only once.");
232 throw new RestconfDocumentedException(
233 "Bad parameter used with notifications: " + entry.getKey());
236 if (!startTimeUsed && stopTimeUsed) {
237 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
240 return new NotificationQueryParams(start, stop, filter, skipNotificationData);
245 * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
246 * to {@link Instant} format.
248 * @param entry Start-time or stop-time as string in {@link DateAndTime} format.
249 * @return Parsed {@link Instant} by entry.
251 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
252 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
253 final String value = event.getValue();
254 final TemporalAccessor accessor;
256 accessor = FORMATTER.parse(value);
257 } catch (final DateTimeParseException e) {
258 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
260 return Instant.from(accessor);
264 * Get start-time query parameter.
268 public @NonNull Instant getStart() {
273 * Get stop-time query parameter.
277 public Optional<Instant> getStop() {
278 return Optional.ofNullable(stop);
282 * Get filter query parameter.
286 public Optional<String> getFilter() {
287 return Optional.ofNullable(filter);
291 * Check whether this query should notify changes without data.
293 * @return true if this query should notify about changes with data
295 public boolean isSkipNotificationData() {
296 return skipNotificationData;