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 com.google.common.base.Preconditions;
12 import java.time.Instant;
13 import java.time.format.DateTimeFormatter;
14 import java.time.format.DateTimeFormatterBuilder;
15 import java.time.format.DateTimeParseException;
16 import java.time.temporal.ChronoField;
17 import java.time.temporal.TemporalAccessor;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.List;
22 import java.util.Map.Entry;
23 import java.util.Optional;
24 import javax.ws.rs.Path;
25 import javax.ws.rs.core.UriInfo;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
28 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
29 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
32 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
33 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMDataBrokerHandler;
34 import org.opendaylight.restconf.nb.rfc8040.handlers.NotificationServiceHandler;
35 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
36 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
37 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
38 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
39 import org.opendaylight.restconf.nb.rfc8040.streams.Configuration;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
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.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
45 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
46 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.Module;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * Implementation of {@link RestconfStreamsSubscriptionService}.
59 public class RestconfStreamsSubscriptionServiceImpl implements RestconfStreamsSubscriptionService {
60 private static final Logger LOG = LoggerFactory.getLogger(RestconfStreamsSubscriptionServiceImpl.class);
62 private final SubscribeToStreamUtil streamUtils;
64 private HandlersHolder handlersHolder;
67 * Initialize holder of handlers with holders as parameters.
69 * @param domDataBrokerHandler
70 * handler of {@link DOMDataBroker}
71 * @param notificationServiceHandler
72 * handler of {@link DOMNotificationService}
73 * @param schemaHandler
74 * handler of {@link SchemaContext}
75 * @param transactionChainHandler
76 * handler of {@link DOMTransactionChain}
77 * @param configuration
78 * configuration for restconf {@link Configuration}}
80 public RestconfStreamsSubscriptionServiceImpl(final DOMDataBrokerHandler domDataBrokerHandler,
81 final NotificationServiceHandler notificationServiceHandler, final SchemaContextHandler schemaHandler,
82 final TransactionChainHandler transactionChainHandler, final Configuration configuration) {
83 this.handlersHolder = new HandlersHolder(domDataBrokerHandler, notificationServiceHandler,
84 transactionChainHandler, schemaHandler);
85 streamUtils = configuration.isUseSSE() ? SubscribeToStreamUtil.serverSentEvents()
86 : SubscribeToStreamUtil.webSockets();
90 public synchronized void updateHandlers(final Object... handlers) {
91 for (final Object object : handlers) {
92 if (object instanceof HandlersHolder) {
93 handlersHolder = (HandlersHolder) object;
99 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
100 final NotificationQueryParams notificationQueryParams = NotificationQueryParams.fromUriInfo(uriInfo);
103 if (identifier.contains(RestconfStreamsConstants.DATA_SUBSCRIPTION)) {
104 response = streamUtils.subscribeToDataStream(identifier, uriInfo, notificationQueryParams,
105 this.handlersHolder);
106 } else if (identifier.contains(RestconfStreamsConstants.NOTIFICATION_STREAM)) {
107 response = streamUtils.subscribeToYangStream(identifier, uriInfo, notificationQueryParams,
108 this.handlersHolder);
110 final String msg = "Bad type of notification of sal-remote";
112 throw new RestconfDocumentedException(msg);
115 // prepare node with value of location
116 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput(this.handlersHolder.getSchemaHandler());
117 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
118 ImmutableLeafNodeBuilder.create().withValue(response.toString());
119 builder.withNodeIdentifier(NodeIdentifier.create(RestconfStreamsConstants.LOCATION_QNAME));
121 // prepare new header with location
122 final Map<String, Object> headers = new HashMap<>();
123 headers.put("Location", response);
125 return new NormalizedNodeContext(iid, builder.build(), headers);
129 * Prepare InstanceIdentifierContext for Location leaf.
131 * @param schemaHandler Schema context handler.
132 * @return InstanceIdentifier of Location leaf.
134 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput(final SchemaContextHandler schemaHandler) {
135 final Optional<Module> module = schemaHandler.get()
136 .findModule(RestconfStreamsConstants.NOTIFI_QNAME.getModule());
137 Preconditions.checkState(module.isPresent());
138 final Optional<DataSchemaNode> notify = module.get()
139 .findDataChildByName(RestconfStreamsConstants.NOTIFI_QNAME);
140 Preconditions.checkState(notify.isPresent());
141 final Optional<DataSchemaNode> location = ((ContainerSchemaNode) notify.get())
142 .findDataChildByName(RestconfStreamsConstants.LOCATION_QNAME);
143 Preconditions.checkState(location.isPresent());
145 final List<PathArgument> path = new ArrayList<>();
146 path.add(NodeIdentifier.create(RestconfStreamsConstants.NOTIFI_QNAME));
147 path.add(NodeIdentifier.create(RestconfStreamsConstants.LOCATION_QNAME));
148 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location.get(),
149 null, schemaHandler.get());
153 * Holder of all handlers for notifications.
155 public static final class HandlersHolder {
157 private final DOMDataBrokerHandler domDataBrokerHandler;
158 private final NotificationServiceHandler notificationServiceHandler;
159 private final TransactionChainHandler transactionChainHandler;
160 private final SchemaContextHandler schemaHandler;
162 private HandlersHolder(final DOMDataBrokerHandler domDataBrokerHandler,
163 final NotificationServiceHandler notificationServiceHandler,
164 final TransactionChainHandler transactionChainHandler, final SchemaContextHandler schemaHandler) {
165 this.domDataBrokerHandler = domDataBrokerHandler;
166 this.notificationServiceHandler = notificationServiceHandler;
167 this.transactionChainHandler = transactionChainHandler;
168 this.schemaHandler = schemaHandler;
172 * Get {@link DOMDataBrokerHandler}.
174 * @return the domDataBrokerHandler
176 public DOMDataBrokerHandler getDomDataBrokerHandler() {
177 return this.domDataBrokerHandler;
181 * Get {@link NotificationServiceHandler}.
183 * @return the notificationServiceHandler
185 public NotificationServiceHandler getNotificationServiceHandler() {
186 return this.notificationServiceHandler;
190 * Get {@link TransactionChainHandler}.
192 * @return the transactionChainHandler
194 public TransactionChainHandler getTransactionChainHandler() {
195 return this.transactionChainHandler;
199 * Get {@link SchemaContextHandler}.
201 * @return the schemaHandler
203 public SchemaContextHandler getSchemaHandler() {
204 return this.schemaHandler;
209 * Parser and holder of query paramteres from uriInfo for notifications.
211 public static final class NotificationQueryParams {
212 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
213 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
214 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
215 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
216 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
217 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
218 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
219 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
220 .appendOffset("+HH:MM", "Z").toFormatter();
222 private final Instant start;
223 private final Instant stop;
224 private final String filter;
225 private final boolean skipNotificationData;
227 private NotificationQueryParams(final Instant start, final Instant stop, final String filter,
228 final boolean skipNotificationData) {
229 this.start = start == null ? Instant.now() : start;
231 this.filter = filter;
232 this.skipNotificationData = skipNotificationData;
235 static NotificationQueryParams fromUriInfo(final UriInfo uriInfo) {
236 Instant start = null;
237 boolean startTimeUsed = false;
239 boolean stopTimeUsed = false;
240 String filter = null;
241 boolean filterUsed = false;
242 boolean skipNotificationDataUsed = false;
243 boolean skipNotificationData = false;
245 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
246 switch (entry.getKey()) {
248 if (!startTimeUsed) {
249 startTimeUsed = true;
250 start = parseDateFromQueryParam(entry);
252 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
258 stop = parseDateFromQueryParam(entry);
260 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
266 filter = entry.getValue().iterator().next();
269 case "odl-skip-notification-data":
270 if (!skipNotificationDataUsed) {
271 skipNotificationDataUsed = true;
272 skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
274 throw new RestconfDocumentedException(
275 "Odl-skip-notification-data parameter can be used only once.");
279 throw new RestconfDocumentedException(
280 "Bad parameter used with notifications: " + entry.getKey());
283 if (!startTimeUsed && stopTimeUsed) {
284 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
287 return new NotificationQueryParams(start, stop, filter, skipNotificationData);
292 * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
293 * to {@link Instant} format.
295 * @param entry Start-time or stop-time as string in {@link DateAndTime} format.
296 * @return Parsed {@link Instant} by entry.
298 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
299 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
300 final String value = event.getValue();
301 final TemporalAccessor accessor;
303 accessor = FORMATTER.parse(value);
304 } catch (final DateTimeParseException e) {
305 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
307 return Instant.from(accessor);
311 * Get start-time query parameter.
315 public @NonNull Instant getStart() {
320 * Get stop-time query parameter.
324 public Optional<Instant> getStop() {
325 return Optional.ofNullable(stop);
329 * Get filter query parameter.
333 public Optional<String> getFilter() {
334 return Optional.ofNullable(filter);
338 * Check whether this query should notify changes without data.
340 * @return true if this query should notify about changes with data
342 public boolean isSkipNotificationData() {
343 return skipNotificationData;