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;
12 import com.google.common.collect.ImmutableMap;
14 import java.time.Instant;
15 import java.time.format.DateTimeFormatter;
16 import java.time.format.DateTimeFormatterBuilder;
17 import java.time.format.DateTimeParseException;
18 import java.time.temporal.ChronoField;
19 import java.time.temporal.TemporalAccessor;
20 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.Optional;
23 import javax.ws.rs.Path;
24 import javax.ws.rs.core.UriInfo;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
27 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
28 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
29 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
32 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
33 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
34 import org.opendaylight.restconf.nb.rfc8040.streams.Configuration;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
39 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
40 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * Implementation of {@link RestconfStreamsSubscriptionService}.
52 public class RestconfStreamsSubscriptionServiceImpl implements RestconfStreamsSubscriptionService {
53 private static final Logger LOG = LoggerFactory.getLogger(RestconfStreamsSubscriptionServiceImpl.class);
54 private static final QName LOCATION_QNAME =
55 QName.create("subscribe:to:notification", "2016-10-28", "location").intern();
56 private static final NodeIdentifier LOCATION_NODEID = NodeIdentifier.create(LOCATION_QNAME);
57 private static final QName NOTIFI_QNAME = QName.create(LOCATION_QNAME, "notifi").intern();
58 private static final YangInstanceIdentifier LOCATION_PATH =
59 YangInstanceIdentifier.create(NodeIdentifier.create(NOTIFI_QNAME), LOCATION_NODEID);
61 private final SubscribeToStreamUtil streamUtils;
62 private final HandlersHolder handlersHolder;
65 * Initialize holder of handlers with holders as parameters.
67 * @param dataBroker {@link DOMDataBroker}
68 * @param notificationService {@link DOMNotificationService}
69 * @param schemaHandler
70 * handler of {@link SchemaContext}
71 * @param configuration
72 * configuration for restconf {@link Configuration}}
74 public RestconfStreamsSubscriptionServiceImpl(final DOMDataBroker dataBroker,
75 final DOMNotificationService notificationService, final SchemaContextHandler schemaHandler,
76 final Configuration configuration) {
77 handlersHolder = new HandlersHolder(dataBroker, notificationService, schemaHandler);
78 streamUtils = configuration.isUseSSE() ? SubscribeToStreamUtil.serverSentEvents()
79 : SubscribeToStreamUtil.webSockets();
83 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
84 final NotificationQueryParams notificationQueryParams = NotificationQueryParams.fromUriInfo(uriInfo);
87 if (identifier.contains(RestconfStreamsConstants.DATA_SUBSCRIPTION)) {
88 response = streamUtils.subscribeToDataStream(identifier, uriInfo, notificationQueryParams, handlersHolder);
89 } else if (identifier.contains(RestconfStreamsConstants.NOTIFICATION_STREAM)) {
90 response = streamUtils.subscribeToYangStream(identifier, uriInfo, notificationQueryParams, handlersHolder);
92 final String msg = "Bad type of notification of sal-remote";
94 throw new RestconfDocumentedException(msg);
97 // prepare node with value of location
98 return new NormalizedNodeContext(prepareIIDSubsStreamOutput(handlersHolder.getSchemaHandler()),
99 ImmutableNodes.leafNode(LOCATION_NODEID, response.toString()), ImmutableMap.of("Location", response));
103 * Prepare InstanceIdentifierContext for Location leaf.
105 * @param schemaHandler Schema context handler.
106 * @return InstanceIdentifier of Location leaf.
108 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput(final SchemaContextHandler schemaHandler) {
109 final Optional<Module> module = schemaHandler.get().findModule(NOTIFI_QNAME.getModule());
110 checkState(module.isPresent());
111 final DataSchemaNode notify = module.get().dataChildByName(NOTIFI_QNAME);
112 checkState(notify instanceof ContainerSchemaNode, "Unexpected non-container %s", notify);
113 final DataSchemaNode location = ((ContainerSchemaNode) notify).dataChildByName(LOCATION_QNAME);
114 checkState(location != null, "Missing location");
116 return new InstanceIdentifierContext<SchemaNode>(LOCATION_PATH, location, null, schemaHandler.get());
120 * Holder of all handlers for notifications.
122 // FIXME: why do we even need this class?!
123 public static final class HandlersHolder {
124 private final DOMDataBroker dataBroker;
125 private final DOMNotificationService notificationService;
126 private final SchemaContextHandler schemaHandler;
128 private HandlersHolder(final DOMDataBroker dataBroker, final DOMNotificationService notificationService,
129 final SchemaContextHandler schemaHandler) {
130 this.dataBroker = dataBroker;
131 this.notificationService = notificationService;
132 this.schemaHandler = schemaHandler;
136 * Get {@link DOMDataBroker}.
138 * @return the dataBroker
140 public DOMDataBroker getDataBroker() {
145 * Get {@link DOMNotificationService}.
147 * @return the notificationService
149 public DOMNotificationService getNotificationServiceHandler() {
150 return notificationService;
154 * Get {@link SchemaContextHandler}.
156 * @return the schemaHandler
158 public SchemaContextHandler getSchemaHandler() {
159 return schemaHandler;
164 * Parser and holder of query paramteres from uriInfo for notifications.
166 public static final class NotificationQueryParams {
167 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
168 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
169 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
170 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
171 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
172 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
173 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
174 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
175 .appendOffset("+HH:MM", "Z").toFormatter();
177 private final Instant start;
178 private final Instant stop;
179 private final String filter;
180 private final boolean skipNotificationData;
182 private NotificationQueryParams(final Instant start, final Instant stop, final String filter,
183 final boolean skipNotificationData) {
184 this.start = start == null ? Instant.now() : start;
186 this.filter = filter;
187 this.skipNotificationData = skipNotificationData;
190 static NotificationQueryParams fromUriInfo(final UriInfo uriInfo) {
191 Instant start = null;
192 boolean startTimeUsed = false;
194 boolean stopTimeUsed = false;
195 String filter = null;
196 boolean filterUsed = false;
197 boolean skipNotificationDataUsed = false;
198 boolean skipNotificationData = false;
200 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
201 switch (entry.getKey()) {
203 if (!startTimeUsed) {
204 startTimeUsed = true;
205 start = parseDateFromQueryParam(entry);
207 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
213 stop = parseDateFromQueryParam(entry);
215 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
221 filter = entry.getValue().iterator().next();
224 case "odl-skip-notification-data":
225 if (!skipNotificationDataUsed) {
226 skipNotificationDataUsed = true;
227 skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
229 throw new RestconfDocumentedException(
230 "Odl-skip-notification-data parameter can be used only once.");
234 throw new RestconfDocumentedException(
235 "Bad parameter used with notifications: " + entry.getKey());
238 if (!startTimeUsed && stopTimeUsed) {
239 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
242 return new NotificationQueryParams(start, stop, filter, skipNotificationData);
247 * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
248 * to {@link Instant} format.
250 * @param entry Start-time or stop-time as string in {@link DateAndTime} format.
251 * @return Parsed {@link Instant} by entry.
253 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
254 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
255 final String value = event.getValue();
256 final TemporalAccessor accessor;
258 accessor = FORMATTER.parse(value);
259 } catch (final DateTimeParseException e) {
260 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
262 return Instant.from(accessor);
266 * Get start-time query parameter.
270 public @NonNull Instant getStart() {
275 * Get stop-time query parameter.
279 public Optional<Instant> getStop() {
280 return Optional.ofNullable(stop);
284 * Get filter query parameter.
288 public Optional<String> getFilter() {
289 return Optional.ofNullable(filter);
293 * Check whether this query should notify changes without data.
295 * @return true if this query should notify about changes with data
297 public boolean isSkipNotificationData() {
298 return skipNotificationData;