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