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;
11 import static java.util.Objects.requireNonNull;
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.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
28 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.nb.rfc8040.FilterParameter;
32 import org.opendaylight.restconf.nb.rfc8040.StartTimeParameter;
33 import org.opendaylight.restconf.nb.rfc8040.StopTimeParameter;
34 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
35 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
36 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
37 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
38 import org.opendaylight.restconf.nb.rfc8040.streams.Configuration;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Implementation of {@link RestconfStreamsSubscriptionService}.
55 public class RestconfStreamsSubscriptionServiceImpl implements RestconfStreamsSubscriptionService {
56 private static final Logger LOG = LoggerFactory.getLogger(RestconfStreamsSubscriptionServiceImpl.class);
57 private static final QName LOCATION_QNAME =
58 QName.create("subscribe:to:notification", "2016-10-28", "location").intern();
59 private static final NodeIdentifier LOCATION_NODEID = NodeIdentifier.create(LOCATION_QNAME);
60 private static final QName NOTIFI_QNAME = QName.create(LOCATION_QNAME, "notifi").intern();
61 private static final YangInstanceIdentifier LOCATION_PATH =
62 YangInstanceIdentifier.create(NodeIdentifier.create(NOTIFI_QNAME), LOCATION_NODEID);
64 private final SubscribeToStreamUtil streamUtils;
65 private final HandlersHolder handlersHolder;
68 * Initialize holder of handlers with holders as parameters.
70 * @param dataBroker {@link DOMDataBroker}
71 * @param notificationService {@link DOMNotificationService}
72 * @param schemaHandler
73 * handler of {@link SchemaContext}
74 * @param configuration
75 * configuration for restconf {@link Configuration}}
77 public RestconfStreamsSubscriptionServiceImpl(final DOMDataBroker dataBroker,
78 final DOMNotificationService notificationService, final SchemaContextHandler schemaHandler,
79 final Configuration configuration) {
80 handlersHolder = new HandlersHolder(dataBroker, notificationService, schemaHandler);
81 streamUtils = configuration.isUseSSE() ? SubscribeToStreamUtil.serverSentEvents()
82 : SubscribeToStreamUtil.webSockets();
86 public NormalizedNodePayload subscribeToStream(final String identifier, final UriInfo uriInfo) {
87 final NotificationQueryParams notificationQueryParams = NotificationQueryParams.fromUriInfo(uriInfo);
90 if (identifier.contains(RestconfStreamsConstants.DATA_SUBSCRIPTION)) {
91 response = streamUtils.subscribeToDataStream(identifier, uriInfo, notificationQueryParams, handlersHolder);
92 } else if (identifier.contains(RestconfStreamsConstants.NOTIFICATION_STREAM)) {
93 response = streamUtils.subscribeToYangStream(identifier, uriInfo, notificationQueryParams, handlersHolder);
95 final String msg = "Bad type of notification of sal-remote";
97 throw new RestconfDocumentedException(msg);
100 // prepare node with value of location
101 return NormalizedNodePayload.ofLocation(prepareIIDSubsStreamOutput(handlersHolder.getSchemaHandler()),
102 LOCATION_NODEID, response);
106 * Prepare InstanceIdentifierContext for Location leaf.
108 * @param schemaHandler Schema context handler.
109 * @return InstanceIdentifier of Location leaf.
111 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput(final SchemaContextHandler schemaHandler) {
112 final Optional<Module> module = schemaHandler.get().findModule(NOTIFI_QNAME.getModule());
113 checkState(module.isPresent());
114 final DataSchemaNode notify = module.get().dataChildByName(NOTIFI_QNAME);
115 checkState(notify instanceof ContainerSchemaNode, "Unexpected non-container %s", notify);
116 final DataSchemaNode location = ((ContainerSchemaNode) notify).dataChildByName(LOCATION_QNAME);
117 checkState(location != null, "Missing location");
119 return new InstanceIdentifierContext<SchemaNode>(LOCATION_PATH, location, null, schemaHandler.get());
123 * Holder of all handlers for notifications.
125 // FIXME: why do we even need this class?!
126 public static final class HandlersHolder {
127 private final DOMDataBroker dataBroker;
128 private final DOMNotificationService notificationService;
129 private final SchemaContextHandler schemaHandler;
131 private HandlersHolder(final DOMDataBroker dataBroker, final DOMNotificationService notificationService,
132 final SchemaContextHandler schemaHandler) {
133 this.dataBroker = dataBroker;
134 this.notificationService = notificationService;
135 this.schemaHandler = schemaHandler;
139 * Get {@link DOMDataBroker}.
141 * @return the dataBroker
143 public DOMDataBroker getDataBroker() {
148 * Get {@link DOMNotificationService}.
150 * @return the notificationService
152 public DOMNotificationService getNotificationServiceHandler() {
153 return notificationService;
157 * Get {@link SchemaContextHandler}.
159 * @return the schemaHandler
161 public SchemaContextHandler getSchemaHandler() {
162 return schemaHandler;
167 * Parser and holder of query paramteres from uriInfo for notifications.
169 public static final class NotificationQueryParams {
170 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
171 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
172 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
173 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
174 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
175 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
176 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
177 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
178 .appendOffset("+HH:MM", "Z").toFormatter();
180 private final @NonNull Instant startTime;
181 private final Instant stopTime;
182 private final String filter;
183 private final boolean skipNotificationData;
185 private NotificationQueryParams(final Instant startTime, final Instant stopTime, final String filter,
186 final boolean skipNotificationData) {
187 this.startTime = requireNonNull(startTime);
188 this.stopTime = stopTime;
189 this.filter = filter;
190 this.skipNotificationData = skipNotificationData;
193 static NotificationQueryParams fromUriInfo(final UriInfo uriInfo) {
194 Instant startTime = null;
195 Instant stopTime = null;
196 String filter = null;
197 boolean skipNotificationData = false;
199 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
200 final String paramName = entry.getKey();
201 final List<String> paramValues = entry.getValue();
202 if (paramName.equals(StartTimeParameter.uriName())) {
203 switch (paramValues.size()) {
207 startTime = parseDateFromQueryParam(paramValues.get(0));
210 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
212 } else if (paramName.equals(StopTimeParameter.uriName())) {
213 switch (paramValues.size()) {
217 stopTime = parseDateFromQueryParam(paramValues.get(0));
220 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
222 } else if (paramName.equals(FilterParameter.uriName())) {
223 if (!paramValues.isEmpty()) {
224 // FIXME: use FilterParameter
225 filter = paramValues.get(0);
227 } else if (paramName.equals("odl-skip-notification-data")) {
228 switch (paramValues.size()) {
232 skipNotificationData = Boolean.parseBoolean(paramValues.get(0));
235 throw new RestconfDocumentedException(
236 "Odl-skip-notification-data parameter can be used only once.");
239 throw new RestconfDocumentedException("Bad parameter used with notifications: " + paramName);
242 if (startTime == null && stopTime != null) {
243 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
246 return new NotificationQueryParams(startTime == null ? Instant.now() : startTime, stopTime, filter,
247 skipNotificationData);
252 * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
253 * to {@link Instant} format.
255 * @param uriValue Start-time or stop-time as string in {@link DateAndTime} format.
256 * @return Parsed {@link Instant} by entry.
258 private static @NonNull Instant parseDateFromQueryParam(final String uriValue) {
259 final TemporalAccessor accessor;
261 accessor = FORMATTER.parse(new DateAndTime(uriValue).getValue());
262 } catch (final DateTimeParseException | IllegalArgumentException e) {
263 throw new RestconfDocumentedException("Cannot parse of value in date: " + uriValue, e);
265 return Instant.from(accessor);
269 * Get start-time query parameter.
273 public @NonNull Instant startTime() {
278 * Get stop-time query parameter.
282 public @Nullable Instant stopTime() {
287 * Get filter query parameter.
291 public @Nullable String filter() {
296 * Check whether this query should notify changes without data.
298 * @return true if this query should notify about changes with data
300 public boolean isSkipNotificationData() {
301 return skipNotificationData;