Split out RFC8040-only constructs from yang-common
[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
12 import java.net.URI;
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;
45
46 /**
47  * Implementation of {@link RestconfStreamsSubscriptionService}.
48  */
49 @Path("/")
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);
58
59     private final SubscribeToStreamUtil streamUtils;
60     private final HandlersHolder handlersHolder;
61
62     /**
63      * Initialize holder of handlers with holders as parameters.
64      *
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}}
71      */
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();
78     }
79
80     @Override
81     public NormalizedNodePayload subscribeToStream(final String identifier, final UriInfo uriInfo) {
82         final NotificationQueryParams notificationQueryParams = NotificationQueryParams.fromUriInfo(uriInfo);
83
84         final URI response;
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);
89         } else {
90             final String msg = "Bad type of notification of sal-remote";
91             LOG.warn(msg);
92             throw new RestconfDocumentedException(msg);
93         }
94
95         // prepare node with value of location
96         return NormalizedNodePayload.ofLocation(prepareIIDSubsStreamOutput(handlersHolder.getSchemaHandler()),
97             LOCATION_NODEID, response);
98     }
99
100     /**
101      * Prepare InstanceIdentifierContext for Location leaf.
102      *
103      * @param schemaHandler Schema context handler.
104      * @return InstanceIdentifier of Location leaf.
105      */
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");
113
114         return new InstanceIdentifierContext<SchemaNode>(LOCATION_PATH, location, null, schemaHandler.get());
115     }
116
117     /**
118      * Holder of all handlers for notifications.
119      */
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;
125
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;
131         }
132
133         /**
134          * Get {@link DOMDataBroker}.
135          *
136          * @return the dataBroker
137          */
138         public DOMDataBroker getDataBroker() {
139             return dataBroker;
140         }
141
142         /**
143          * Get {@link DOMNotificationService}.
144          *
145          * @return the notificationService
146          */
147         public DOMNotificationService getNotificationServiceHandler() {
148             return notificationService;
149         }
150
151         /**
152          * Get {@link SchemaContextHandler}.
153          *
154          * @return the schemaHandler
155          */
156         public SchemaContextHandler getSchemaHandler() {
157             return schemaHandler;
158         }
159     }
160
161     /**
162      * Parser and holder of query paramteres from uriInfo for notifications.
163      */
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();
174
175         private final Instant start;
176         private final Instant stop;
177         private final String filter;
178         private final boolean skipNotificationData;
179
180         private NotificationQueryParams(final Instant start, final Instant stop, final String filter,
181                 final boolean skipNotificationData) {
182             this.start = start == null ? Instant.now() : start;
183             this.stop = stop;
184             this.filter = filter;
185             this.skipNotificationData = skipNotificationData;
186         }
187
188         static NotificationQueryParams fromUriInfo(final UriInfo uriInfo) {
189             Instant start = null;
190             boolean startTimeUsed = false;
191             Instant stop = null;
192             boolean stopTimeUsed = false;
193             String filter = null;
194             boolean filterUsed = false;
195             boolean skipNotificationDataUsed = false;
196             boolean skipNotificationData = false;
197
198             for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
199                 switch (entry.getKey()) {
200                     case "start-time":
201                         if (!startTimeUsed) {
202                             startTimeUsed = true;
203                             start = parseDateFromQueryParam(entry);
204                         } else {
205                             throw new RestconfDocumentedException("Start-time parameter can be used only once.");
206                         }
207                         break;
208                     case "stop-time":
209                         if (!stopTimeUsed) {
210                             stopTimeUsed = true;
211                             stop = parseDateFromQueryParam(entry);
212                         } else {
213                             throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
214                         }
215                         break;
216                     case "filter":
217                         if (!filterUsed) {
218                             filterUsed = true;
219                             filter = entry.getValue().iterator().next();
220                         }
221                         break;
222                     case "odl-skip-notification-data":
223                         if (!skipNotificationDataUsed) {
224                             skipNotificationDataUsed = true;
225                             skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
226                         } else {
227                             throw new RestconfDocumentedException(
228                                     "Odl-skip-notification-data parameter can be used only once.");
229                         }
230                         break;
231                     default:
232                         throw new RestconfDocumentedException(
233                                 "Bad parameter used with notifications: " + entry.getKey());
234                 }
235             }
236             if (!startTimeUsed && stopTimeUsed) {
237                 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
238             }
239
240             return new NotificationQueryParams(start, stop, filter, skipNotificationData);
241         }
242
243
244         /**
245          * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
246          * to {@link Instant} format.
247          *
248          * @param entry Start-time or stop-time as string in {@link DateAndTime} format.
249          * @return Parsed {@link Instant} by entry.
250          */
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;
255             try {
256                 accessor = FORMATTER.parse(value);
257             } catch (final DateTimeParseException e) {
258                 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
259             }
260             return Instant.from(accessor);
261         }
262
263         /**
264          * Get start-time query parameter.
265          *
266          * @return start-time
267          */
268         public @NonNull Instant getStart() {
269             return start;
270         }
271
272         /**
273          * Get stop-time query parameter.
274          *
275          * @return stop-time
276          */
277         public Optional<Instant> getStop() {
278             return Optional.ofNullable(stop);
279         }
280
281         /**
282          * Get filter query parameter.
283          *
284          * @return filter
285          */
286         public Optional<String> getFilter() {
287             return Optional.ofNullable(filter);
288         }
289
290         /**
291          * Check whether this query should notify changes without data.
292          *
293          * @return true if this query should notify about changes with  data
294          */
295         public boolean isSkipNotificationData() {
296             return skipNotificationData;
297         }
298     }
299 }