Use parameters in StreamSubscriptionServiceImpl
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / SubscribeToStreamUtil.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.Strings.isNullOrEmpty;
11
12 import java.net.URI;
13 import java.util.HashMap;
14 import java.util.Map;
15 import java.util.concurrent.ExecutionException;
16 import javax.ws.rs.core.UriBuilder;
17 import javax.ws.rs.core.UriInfo;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
20 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
21 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteOperations;
22 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
23 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
24 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
25 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
26 import org.opendaylight.restconf.nb.rfc8040.rests.services.impl.RestconfStreamsSubscriptionServiceImpl.HandlersHolder;
27 import org.opendaylight.restconf.nb.rfc8040.rests.services.impl.RestconfStreamsSubscriptionServiceImpl.NotificationQueryParams;
28 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
29 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenerAdapter;
30 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
31 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
32 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
33 import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil;
34 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
35 import org.opendaylight.yangtools.yang.common.ErrorTag;
36 import org.opendaylight.yangtools.yang.common.ErrorType;
37 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
38 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Subscribe to stream util class.
44  */
45 abstract class SubscribeToStreamUtil {
46     /**
47      * Implementation of SubscribeToStreamUtil for Server-sent events.
48      */
49     private static final class ServerSentEvents extends SubscribeToStreamUtil {
50         static final ServerSentEvents INSTANCE = new ServerSentEvents();
51
52         @Override
53         public URI prepareUriByStreamName(final UriInfo uriInfo, final String streamName) {
54             final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
55             return uriBuilder.replacePath(RestconfConstants.BASE_URI_PATTERN + '/'
56                     + RestconfConstants.NOTIF + '/' + streamName).build();
57         }
58     }
59
60     /**
61      * Implementation of SubscribeToStreamUtil for Web sockets.
62      */
63     private static final class WebSockets extends SubscribeToStreamUtil {
64         static final WebSockets INSTANCE = new WebSockets();
65
66         @Override
67         public URI prepareUriByStreamName(final UriInfo uriInfo, final String streamName) {
68             final String scheme = uriInfo.getAbsolutePath().getScheme();
69             final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
70             switch (scheme) {
71                 case "https":
72                     // Secured HTTP goes to Secured WebSockets
73                     uriBuilder.scheme("wss");
74                     break;
75                 case "http":
76                 default:
77                     // Unsecured HTTP and others go to unsecured WebSockets
78                     uriBuilder.scheme("ws");
79             }
80             return uriBuilder.replacePath(RestconfConstants.BASE_URI_PATTERN + '/' + streamName).build();
81         }
82     }
83
84
85     private static final Logger LOG = LoggerFactory.getLogger(SubscribeToStreamUtil.class);
86
87     SubscribeToStreamUtil() {
88         // Hidden on purpose
89     }
90
91     static SubscribeToStreamUtil serverSentEvents() {
92         return ServerSentEvents.INSTANCE;
93     }
94
95     static SubscribeToStreamUtil webSockets() {
96         return WebSockets.INSTANCE;
97     }
98
99     /**
100      * Prepare URL from base name and stream name.
101      *
102      * @param uriInfo base URL information
103      * @param streamName name of stream for create
104      * @return final URL
105      */
106     abstract @NonNull URI prepareUriByStreamName(UriInfo uriInfo, String streamName);
107
108     /**
109      * Register listener by streamName in identifier to listen to yang notifications, and put or delete information
110      * about listener to DS according to ietf-restconf-monitoring.
111      *
112      * @param identifier              Name of the stream.
113      * @param uriInfo                 URI information.
114      * @param notificationQueryParams Query parameters of notification.
115      * @param handlersHolder          Holder of handlers for notifications.
116      * @return Stream location for listening.
117      */
118     final @NonNull URI subscribeToYangStream(final String identifier, final UriInfo uriInfo,
119             final NotificationQueryParams notificationQueryParams, final HandlersHolder handlersHolder) {
120         final String streamName = ListenersBroker.createStreamNameFromUri(identifier);
121         if (isNullOrEmpty(streamName)) {
122             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
123         }
124
125         final NotificationListenerAdapter notificationListenerAdapter = ListenersBroker.getInstance()
126             .getNotificationListenerFor(streamName)
127             .orElseThrow(() -> new RestconfDocumentedException(
128                 String.format("Stream with name %s was not found.", streamName),
129                 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT));
130
131         final EffectiveModelContext schemaContext = handlersHolder.getSchemaHandler().get();
132         final URI uri = prepareUriByStreamName(uriInfo, streamName);
133         notificationListenerAdapter.listen(handlersHolder.getNotificationServiceHandler());
134         notificationListenerAdapter.setQueryParams(
135                 notificationQueryParams.startTime(),
136                 notificationQueryParams.stopTime(),
137                 notificationQueryParams.filter(),
138                 false, notificationQueryParams.isSkipNotificationData());
139         final DOMDataBroker dataBroker = handlersHolder.getDataBroker();
140         notificationListenerAdapter.setCloseVars(dataBroker, handlersHolder.getSchemaHandler());
141         final MapEntryNode mapToStreams = RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
142                     notificationListenerAdapter.getSchemaPath().lastNodeIdentifier(),
143                     schemaContext.getNotifications(), notificationQueryParams.startTime(),
144                     notificationListenerAdapter.getOutputType(), uri);
145
146         // FIXME: how does this correlate with the transaction notificationListenerAdapter.close() will do?
147         final DOMDataTreeWriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
148         writeDataToDS(writeTransaction, mapToStreams);
149         submitData(writeTransaction);
150         return uri;
151     }
152
153     /**
154      * Register listener by streamName in identifier to listen to data change notifications, and put or delete
155      * information about listener to DS according to ietf-restconf-monitoring.
156      *
157      * @param identifier              Identifier as stream name.
158      * @param uriInfo                 Base URI information.
159      * @param notificationQueryParams Query parameters of notification.
160      * @param handlersHolder          Holder of handlers for notifications.
161      * @return Location for listening.
162      */
163     final URI subscribeToDataStream(final String identifier, final UriInfo uriInfo,
164             final NotificationQueryParams notificationQueryParams, final HandlersHolder handlersHolder) {
165         final Map<String, String> mapOfValues = mapValuesFromUri(identifier);
166
167         final String datastoreParam = mapOfValues.get(RestconfStreamsConstants.DATASTORE_PARAM_NAME);
168         if (isNullOrEmpty(datastoreParam)) {
169             final String message = "Stream name does not contain datastore value (pattern /datastore=)";
170             LOG.debug(message);
171             throw new RestconfDocumentedException(message, ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
172         }
173
174         // FIXME: this is kept only for compatibility, we are not using this parameter
175         if (isNullOrEmpty(mapOfValues.get(RestconfStreamsConstants.SCOPE_PARAM_NAME))) {
176             final String message = "Stream name does not contain scope value (pattern /scope=)";
177             LOG.warn(message);
178             throw new RestconfDocumentedException(message, ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
179         }
180
181         final String streamName = ListenersBroker.createStreamNameFromUri(identifier);
182         final ListenerAdapter listener = ListenersBroker.getInstance().getDataChangeListenerFor(streamName)
183             .orElseThrow(() -> new RestconfDocumentedException("No listener found for stream " + streamName,
184                 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
185
186         listener.setQueryParams(
187                 notificationQueryParams.startTime(),
188                 notificationQueryParams.stopTime(),
189                 notificationQueryParams.filter(),
190                 false, notificationQueryParams.isSkipNotificationData());
191
192         final DOMDataBroker dataBroker = handlersHolder.getDataBroker();
193         final SchemaContextHandler schemaHandler = handlersHolder.getSchemaHandler();
194         listener.setCloseVars(dataBroker, schemaHandler);
195         listener.listen(dataBroker, LogicalDatastoreType.valueOf(datastoreParam));
196
197         final URI uri = prepareUriByStreamName(uriInfo, streamName);
198         final EffectiveModelContext schemaContext = schemaHandler.get();
199         final String serializedPath = IdentifierCodec.serialize(listener.getPath(), schemaContext);
200
201         final MapEntryNode mapToStreams =
202             RestconfMappingNodeUtil.mapDataChangeNotificationStreamByIetfRestconfMonitoring(listener.getPath(),
203                 notificationQueryParams.startTime(), listener.getOutputType(), uri, schemaContext, serializedPath);
204         final DOMDataTreeWriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
205         writeDataToDS(writeTransaction, mapToStreams);
206         submitData(writeTransaction);
207         return uri;
208     }
209
210     // FIXME: callers are utter duplicates, refactor them
211     private static void writeDataToDS(final DOMDataTreeWriteOperations tx, final MapEntryNode mapToStreams) {
212         // FIXME: use put() here
213         tx.merge(LogicalDatastoreType.OPERATIONAL, Rfc8040.restconfStateStreamPath(mapToStreams.getIdentifier()),
214             mapToStreams);
215     }
216
217     private static void submitData(final DOMDataTreeWriteTransaction readWriteTransaction) {
218         try {
219             readWriteTransaction.commit().get();
220         } catch (final InterruptedException | ExecutionException e) {
221             throw new RestconfDocumentedException("Problem while putting data to DS.", e);
222         }
223     }
224
225     /**
226      * Prepare map of URI parameter-values.
227      *
228      * @param identifier String identification of URI.
229      * @return Map od URI parameters and values.
230      */
231     private static Map<String, String> mapValuesFromUri(final String identifier) {
232         final HashMap<String, String> result = new HashMap<>();
233         for (final String token : RestconfConstants.SLASH_SPLITTER.split(identifier)) {
234             final String[] paramToken = token.split("=");
235             if (paramToken.length == 2) {
236                 result.put(paramToken[0], paramToken[1]);
237             }
238         }
239         return result;
240     }
241 }