Move SubscribeToStreamUtil to rests.services.impl
[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 java.net.URI;
11 import java.time.Instant;
12 import java.util.HashMap;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Map.Entry;
16 import java.util.Optional;
17 import javax.ws.rs.Path;
18 import javax.ws.rs.core.UriInfo;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
21 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
22 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
23 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
24 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
25 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
26 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMDataBrokerHandler;
27 import org.opendaylight.restconf.nb.rfc8040.handlers.NotificationServiceHandler;
28 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
29 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
30 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
31 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
34 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
35 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * Implementation of {@link RestconfStreamsSubscriptionService}.
42  */
43 @Path("/")
44 public class RestconfStreamsSubscriptionServiceImpl implements RestconfStreamsSubscriptionService {
45
46     private static final Logger LOG = LoggerFactory.getLogger(RestconfStreamsSubscriptionServiceImpl.class);
47
48     private HandlersHolder handlersHolder;
49
50     /**
51      * Initialize holder of handlers with holders as parameters.
52      *
53      * @param domDataBrokerHandler
54      *             handler of {@link DOMDataBroker}
55      * @param notificationServiceHandler
56      *             handler of {@link DOMNotificationService}
57      * @param schemaHandler
58      *             handler of {@link SchemaContext}
59      * @param transactionChainHandler
60      *             handler of {@link DOMTransactionChain}
61      */
62     public RestconfStreamsSubscriptionServiceImpl(final DOMDataBrokerHandler domDataBrokerHandler,
63             final NotificationServiceHandler notificationServiceHandler, final SchemaContextHandler schemaHandler,
64             final TransactionChainHandler transactionChainHandler) {
65         this.handlersHolder = new HandlersHolder(domDataBrokerHandler, notificationServiceHandler,
66                 transactionChainHandler, schemaHandler);
67     }
68
69     @Override
70     public synchronized void updateHandlers(final Object... handlers) {
71         for (final Object object : handlers) {
72             if (object instanceof HandlersHolder) {
73                 handlersHolder = (HandlersHolder) object;
74             }
75         }
76     }
77
78     @Override
79     public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
80         final NotificationQueryParams notificationQueryParams = NotificationQueryParams.fromUriInfo(uriInfo);
81
82         URI response = null;
83         if (identifier.contains(RestconfStreamsConstants.DATA_SUBSCRIPTION)) {
84             response = SubscribeToStreamUtil.subscribeToDataStream(identifier, uriInfo, notificationQueryParams,
85                     this.handlersHolder);
86         } else if (identifier.contains(RestconfStreamsConstants.NOTIFICATION_STREAM)) {
87             response = SubscribeToStreamUtil.subscribeToYangStream(identifier, uriInfo, notificationQueryParams,
88                     this.handlersHolder);
89         }
90
91         if (response != null) {
92             // prepare node with value of location
93             final InstanceIdentifierContext<?> iid =
94                     SubscribeToStreamUtil.prepareIIDSubsStreamOutput(this.handlersHolder.getSchemaHandler());
95             final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
96                     ImmutableLeafNodeBuilder.create().withValue(response.toString());
97             builder.withNodeIdentifier(NodeIdentifier.create(RestconfStreamsConstants.LOCATION_QNAME));
98
99             // prepare new header with location
100             final Map<String, Object> headers = new HashMap<>();
101             headers.put("Location", response);
102
103             return new NormalizedNodeContext(iid, builder.build(), headers);
104         }
105
106         final String msg = "Bad type of notification of sal-remote";
107         LOG.warn(msg);
108         throw new RestconfDocumentedException(msg);
109     }
110
111     /**
112      * Holder of all handlers for notifications.
113      */
114     public static final class HandlersHolder {
115
116         private final DOMDataBrokerHandler domDataBrokerHandler;
117         private final NotificationServiceHandler notificationServiceHandler;
118         private final TransactionChainHandler transactionChainHandler;
119         private final SchemaContextHandler schemaHandler;
120
121         private HandlersHolder(final DOMDataBrokerHandler domDataBrokerHandler,
122                 final NotificationServiceHandler notificationServiceHandler,
123                 final TransactionChainHandler transactionChainHandler, final SchemaContextHandler schemaHandler) {
124             this.domDataBrokerHandler = domDataBrokerHandler;
125             this.notificationServiceHandler = notificationServiceHandler;
126             this.transactionChainHandler = transactionChainHandler;
127             this.schemaHandler = schemaHandler;
128         }
129
130         /**
131          * Get {@link DOMDataBrokerHandler}.
132          *
133          * @return the domDataBrokerHandler
134          */
135         public DOMDataBrokerHandler getDomDataBrokerHandler() {
136             return this.domDataBrokerHandler;
137         }
138
139         /**
140          * Get {@link NotificationServiceHandler}.
141          *
142          * @return the notificationServiceHandler
143          */
144         public NotificationServiceHandler getNotificationServiceHandler() {
145             return this.notificationServiceHandler;
146         }
147
148         /**
149          * Get {@link TransactionChainHandler}.
150          *
151          * @return the transactionChainHandler
152          */
153         public TransactionChainHandler getTransactionChainHandler() {
154             return this.transactionChainHandler;
155         }
156
157         /**
158          * Get {@link SchemaContextHandler}.
159          *
160          * @return the schemaHandler
161          */
162         public SchemaContextHandler getSchemaHandler() {
163             return this.schemaHandler;
164         }
165     }
166
167     /**
168      * Parser and holder of query paramteres from uriInfo for notifications.
169      */
170     public static final class NotificationQueryParams {
171
172         private final Instant start;
173         private final Instant stop;
174         private final String filter;
175
176         private NotificationQueryParams(final Instant start, final Instant stop, final String filter) {
177             this.start = start == null ? Instant.now() : start;
178             this.stop = stop;
179             this.filter = filter;
180         }
181
182         static NotificationQueryParams fromUriInfo(final UriInfo uriInfo) {
183             Instant start = null;
184             boolean startTimeUsed = false;
185             Instant stop = null;
186             boolean stopTimeUsed = false;
187             String filter = null;
188             boolean filterUsed = false;
189
190             for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
191                 switch (entry.getKey()) {
192                     case "start-time":
193                         if (!startTimeUsed) {
194                             startTimeUsed = true;
195                             start = SubscribeToStreamUtil.parseDateFromQueryParam(entry);
196                         } else {
197                             throw new RestconfDocumentedException("Start-time parameter can be used only once.");
198                         }
199                         break;
200                     case "stop-time":
201                         if (!stopTimeUsed) {
202                             stopTimeUsed = true;
203                             stop = SubscribeToStreamUtil.parseDateFromQueryParam(entry);
204                         } else {
205                             throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
206                         }
207                         break;
208                     case "filter":
209                         if (!filterUsed) {
210                             filterUsed = true;
211                             filter = entry.getValue().iterator().next();
212                         }
213                         break;
214                     default:
215                         throw new RestconfDocumentedException(
216                                 "Bad parameter used with notifications: " + entry.getKey());
217                 }
218             }
219             if (!startTimeUsed && stopTimeUsed) {
220                 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
221             }
222
223             return new NotificationQueryParams(start, stop, filter);
224         }
225
226         /**
227          * Get start-time query parameter.
228          *
229          * @return start-time
230          */
231         public @NonNull Instant getStart() {
232             return start;
233         }
234
235         /**
236          * Get stop-time query parameter.
237          *
238          * @return stop-time
239          */
240         public Optional<Instant> getStop() {
241             return Optional.ofNullable(stop);
242         }
243
244         /**
245          * Get filter query parameter.
246          *
247          * @return filter
248          */
249         public Optional<String> getFilter() {
250             return Optional.ofNullable(filter);
251         }
252     }
253 }