Use parameters in StreamSubscriptionServiceImpl
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfStreamsSubscriptionServiceImpl.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.rests.services.impl;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import java.net.URI;
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;
50
51 /**
52  * Implementation of {@link RestconfStreamsSubscriptionService}.
53  */
54 @Path("/")
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);
63
64     private final SubscribeToStreamUtil streamUtils;
65     private final HandlersHolder handlersHolder;
66
67     /**
68      * Initialize holder of handlers with holders as parameters.
69      *
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}}
76      */
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();
83     }
84
85     @Override
86     public NormalizedNodePayload subscribeToStream(final String identifier, final UriInfo uriInfo) {
87         final NotificationQueryParams notificationQueryParams = NotificationQueryParams.fromUriInfo(uriInfo);
88
89         final URI response;
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);
94         } else {
95             final String msg = "Bad type of notification of sal-remote";
96             LOG.warn(msg);
97             throw new RestconfDocumentedException(msg);
98         }
99
100         // prepare node with value of location
101         return NormalizedNodePayload.ofLocation(prepareIIDSubsStreamOutput(handlersHolder.getSchemaHandler()),
102             LOCATION_NODEID, response);
103     }
104
105     /**
106      * Prepare InstanceIdentifierContext for Location leaf.
107      *
108      * @param schemaHandler Schema context handler.
109      * @return InstanceIdentifier of Location leaf.
110      */
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");
118
119         return new InstanceIdentifierContext<SchemaNode>(LOCATION_PATH, location, null, schemaHandler.get());
120     }
121
122     /**
123      * Holder of all handlers for notifications.
124      */
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;
130
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;
136         }
137
138         /**
139          * Get {@link DOMDataBroker}.
140          *
141          * @return the dataBroker
142          */
143         public DOMDataBroker getDataBroker() {
144             return dataBroker;
145         }
146
147         /**
148          * Get {@link DOMNotificationService}.
149          *
150          * @return the notificationService
151          */
152         public DOMNotificationService getNotificationServiceHandler() {
153             return notificationService;
154         }
155
156         /**
157          * Get {@link SchemaContextHandler}.
158          *
159          * @return the schemaHandler
160          */
161         public SchemaContextHandler getSchemaHandler() {
162             return schemaHandler;
163         }
164     }
165
166     /**
167      * Parser and holder of query paramteres from uriInfo for notifications.
168      */
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();
179
180         private final @NonNull Instant startTime;
181         private final Instant stopTime;
182         private final String filter;
183         private final boolean skipNotificationData;
184
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;
191         }
192
193         static NotificationQueryParams fromUriInfo(final UriInfo uriInfo) {
194             Instant startTime = null;
195             Instant stopTime = null;
196             String filter = null;
197             boolean skipNotificationData = false;
198
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()) {
204                         case 0:
205                             break;
206                         case 1:
207                             startTime = parseDateFromQueryParam(paramValues.get(0));
208                             break;
209                         default:
210                             throw new RestconfDocumentedException("Start-time parameter can be used only once.");
211                     }
212                 } else if (paramName.equals(StopTimeParameter.uriName())) {
213                     switch (paramValues.size()) {
214                         case 0:
215                             break;
216                         case 1:
217                             stopTime = parseDateFromQueryParam(paramValues.get(0));
218                             break;
219                         default:
220                             throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
221                     }
222                 } else if (paramName.equals(FilterParameter.uriName())) {
223                     if (!paramValues.isEmpty()) {
224                         // FIXME: use FilterParameter
225                         filter = paramValues.get(0);
226                     }
227                 } else if (paramName.equals("odl-skip-notification-data")) {
228                     switch (paramValues.size()) {
229                         case 0:
230                             break;
231                         case 1:
232                             skipNotificationData = Boolean.parseBoolean(paramValues.get(0));
233                             break;
234                         default:
235                             throw new RestconfDocumentedException(
236                                 "Odl-skip-notification-data parameter can be used only once.");
237                     }
238                 } else {
239                     throw new RestconfDocumentedException("Bad parameter used with notifications: " + paramName);
240                 }
241             }
242             if (startTime == null && stopTime != null) {
243                 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
244             }
245
246             return new NotificationQueryParams(startTime == null ? Instant.now() : startTime, stopTime, filter,
247                 skipNotificationData);
248         }
249
250
251         /**
252          * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
253          * to {@link Instant} format.
254          *
255          * @param uriValue Start-time or stop-time as string in {@link DateAndTime} format.
256          * @return Parsed {@link Instant} by entry.
257          */
258         private static @NonNull Instant parseDateFromQueryParam(final String uriValue) {
259             final TemporalAccessor accessor;
260             try {
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);
264             }
265             return Instant.from(accessor);
266         }
267
268         /**
269          * Get start-time query parameter.
270          *
271          * @return start-time
272          */
273         public @NonNull Instant startTime() {
274             return startTime;
275         }
276
277         /**
278          * Get stop-time query parameter.
279          *
280          * @return stop-time
281          */
282         public @Nullable Instant stopTime() {
283             return stopTime;
284         }
285
286         /**
287          * Get filter query parameter.
288          *
289          * @return filter
290          */
291         public @Nullable String filter() {
292             return filter;
293         }
294
295         /**
296          * Check whether this query should notify changes without data.
297          *
298          * @return true if this query should notify about changes with  data
299          */
300         public boolean isSkipNotificationData() {
301             return skipNotificationData;
302         }
303     }
304 }