Bump versions to 4.0.0-SNAPSHOT
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / restconf / impl / RestconfImpl.java
1 /*
2  * Copyright (c) 2014 - 2016 Brocade Communication Systems, Inc., 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.netconf.sal.restconf.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Predicates;
17 import com.google.common.base.Splitter;
18 import com.google.common.base.Strings;
19 import com.google.common.base.Throwables;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Iterables;
23 import com.google.common.util.concurrent.FluentFuture;
24 import com.google.common.util.concurrent.Futures;
25 import com.google.common.util.concurrent.ListenableFuture;
26 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
27 import java.net.URI;
28 import java.time.Instant;
29 import java.time.format.DateTimeFormatter;
30 import java.time.format.DateTimeFormatterBuilder;
31 import java.time.format.DateTimeParseException;
32 import java.time.temporal.ChronoField;
33 import java.time.temporal.TemporalAccessor;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Locale;
40 import java.util.Map;
41 import java.util.Map.Entry;
42 import java.util.Objects;
43 import java.util.Optional;
44 import java.util.Set;
45 import java.util.concurrent.CancellationException;
46 import java.util.concurrent.ExecutionException;
47 import javax.inject.Inject;
48 import javax.inject.Singleton;
49 import javax.ws.rs.WebApplicationException;
50 import javax.ws.rs.core.Context;
51 import javax.ws.rs.core.Response;
52 import javax.ws.rs.core.Response.ResponseBuilder;
53 import javax.ws.rs.core.Response.Status;
54 import javax.ws.rs.core.UriBuilder;
55 import javax.ws.rs.core.UriInfo;
56 import org.eclipse.jdt.annotation.NonNull;
57 import org.opendaylight.mdsal.common.api.CommitInfo;
58 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
59 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
60 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
61 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
62 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
63 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
64 import org.opendaylight.mdsal.dom.api.DOMRpcService;
65 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
66 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
67 import org.opendaylight.netconf.sal.rest.api.Draft02;
68 import org.opendaylight.netconf.sal.rest.api.RestconfService;
69 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeContext;
70 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext.FoundChild;
71 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
72 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
73 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
74 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
75 import org.opendaylight.restconf.common.OperationsContent;
76 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
77 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
78 import org.opendaylight.restconf.common.patch.PatchContext;
79 import org.opendaylight.restconf.common.patch.PatchStatusContext;
80 import org.opendaylight.restconf.common.util.OperationsResourceUtils;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
82 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope;
83 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
84 import org.opendaylight.yangtools.yang.common.Empty;
85 import org.opendaylight.yangtools.yang.common.ErrorTag;
86 import org.opendaylight.yangtools.yang.common.ErrorType;
87 import org.opendaylight.yangtools.yang.common.QName;
88 import org.opendaylight.yangtools.yang.common.QNameModule;
89 import org.opendaylight.yangtools.yang.common.Revision;
90 import org.opendaylight.yangtools.yang.common.XMLNamespace;
91 import org.opendaylight.yangtools.yang.common.YangConstants;
92 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
93 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
94 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
95 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
96 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
97 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
98 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
99 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
100 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
101 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
102 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
103 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
104 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
105 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
106 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
107 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
108 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
109 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
110 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
111 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
112 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
113 import org.opendaylight.yangtools.yang.data.tree.api.ModifiedNodeDoesNotExistException;
114 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
117 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
118 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
120 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
121 import org.opendaylight.yangtools.yang.model.api.Module;
122 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
123 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
124 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
125 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
126 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
127 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
128 import org.slf4j.Logger;
129 import org.slf4j.LoggerFactory;
130
131 @Singleton
132 public final class RestconfImpl implements RestconfService {
133     /**
134      * Notifications are served on port 8181.
135      */
136     private static final int NOTIFICATION_PORT = 8181;
137
138     private static final int CHAR_NOT_FOUND = -1;
139
140     private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
141
142     private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
143
144     private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
145
146     private static final XMLNamespace NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT =
147         XMLNamespace.of("urn:sal:restconf:event:subscription");
148
149     private static final String DATASTORE_PARAM_NAME = "datastore";
150
151     private static final String SCOPE_PARAM_NAME = "scope";
152
153     private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
154
155     private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
156
157     private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
158
159     private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(XMLNamespace.of(NETCONF_BASE)),
160         NETCONF_BASE_PAYLOAD_NAME).intern();
161
162     private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
163         Revision.of("2014-07-08"));
164
165     private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
166             new AugmentationIdentifier(ImmutableSet.of(
167                 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
168                 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
169
170     public static final String DATA_SUBSCR = "data-change-event-subscription";
171     private static final String CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
172
173     public static final String NOTIFICATION_STREAM = "notification-stream";
174     private static final String CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
175
176     private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
177             .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
178             .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
179             .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
180             .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
181             .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
182             .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
183             .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
184             .appendOffset("+HH:MM", "Z").toFormatter();
185
186     private final BrokerFacade broker;
187
188     private final ControllerContext controllerContext;
189
190     @Inject
191     public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
192         this.broker = broker;
193         this.controllerContext = controllerContext;
194     }
195
196     /**
197      * Factory method.
198      *
199      * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
200      */
201     @Deprecated
202     public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
203         return new RestconfImpl(broker, controllerContext);
204     }
205
206     @Override
207     @Deprecated
208     public NormalizedNodeContext getModules(final UriInfo uriInfo) {
209         final Module restconfModule = getRestconfModule();
210         final var stack = SchemaInferenceStack.of(controllerContext.getGlobalSchema());
211         final var restconf = QName.create(restconfModule.getQNameModule(),
212             Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
213         stack.enterGrouping(restconf);
214         stack.enterSchemaTree(restconf);
215         final var modules = QName.create(restconf, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
216         final var modulesSchemaNode = stack.enterSchemaTree(modules);
217         checkState(modulesSchemaNode instanceof ContainerSchemaNode);
218
219         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
220                 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
221         moduleContainerBuilder.withChild(makeModuleMapNode(controllerContext.getAllModules()));
222
223         return new NormalizedNodeContext(InstanceIdentifierContext.ofStack(stack, null),
224             moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
225     }
226
227     /**
228      * Valid only for mount point.
229      */
230     @Override
231     @Deprecated
232     public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
233         if (!identifier.contains(ControllerContext.MOUNT)) {
234             final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
235                     + " URI has to end with " + ControllerContext.MOUNT;
236             LOG.debug("{} for {}", errMsg, identifier);
237             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
238         }
239
240         final InstanceIdentifierContext mountPointIdentifier =
241                 controllerContext.toMountPointIdentifier(identifier);
242         final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
243         final MapNode mountPointModulesMap = makeModuleMapNode(controllerContext.getAllModules(mountPoint));
244
245         final Module restconfModule = getRestconfModule();
246         final var stack = SchemaInferenceStack.of(controllerContext.getGlobalSchema());
247         final var restconf = QName.create(restconfModule.getQNameModule(),
248             Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
249         stack.enterGrouping(restconf);
250         stack.enterSchemaTree(restconf);
251         final var modules = QName.create(restconf, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
252         final var modulesSchemaNode = stack.enterSchemaTree(modules);
253         checkState(modulesSchemaNode instanceof ContainerSchemaNode);
254
255         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
256                 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
257         moduleContainerBuilder.withChild(mountPointModulesMap);
258
259         return new NormalizedNodeContext(InstanceIdentifierContext.ofStack(stack, null),
260             moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
261     }
262
263     @Override
264     @Deprecated
265     public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
266         final Entry<String, Revision> nameRev = getModuleNameAndRevision(requireNonNull(identifier));
267         final Module module;
268         final DOMMountPoint mountPoint;
269         if (identifier.contains(ControllerContext.MOUNT)) {
270             final InstanceIdentifierContext mountPointIdentifier =
271                     controllerContext.toMountPointIdentifier(identifier);
272             mountPoint = mountPointIdentifier.getMountPoint();
273             module = controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
274                 nameRev.getValue());
275         } else {
276             mountPoint = null;
277             module = controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
278         }
279
280         if (module == null) {
281             LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
282             throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
283                     + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
284         }
285
286         final Module restconfModule = getRestconfModule();
287         final var stack = SchemaInferenceStack.of(controllerContext.getGlobalSchema());
288         final var restconf = QName.create(restconfModule.getQNameModule(),
289             Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
290         stack.enterGrouping(restconf);
291         stack.enterSchemaTree(restconf);
292         stack.enterSchemaTree(QName.create(restconf, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE));
293         stack.enterSchemaTree(QName.create(restconf, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE));
294
295         return new NormalizedNodeContext(InstanceIdentifierContext.ofStack(stack, mountPoint),
296             makeModuleMapNode(Set.of(module)), QueryParametersParser.parseWriterParameters(uriInfo));
297     }
298
299     @Override
300     @Deprecated
301     public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
302         final Set<String> availableStreams = Notificator.getStreamNames();
303         final Module restconfModule = getRestconfModule();
304         final DataSchemaNode streamSchemaNode = controllerContext
305                 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
306         checkState(streamSchemaNode instanceof ListSchemaNode);
307
308         final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listStreamsBuilder =
309                 SchemaAwareBuilders.mapBuilder((ListSchemaNode) streamSchemaNode);
310
311         for (final String streamName : availableStreams) {
312             listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
313         }
314
315         final var stack = SchemaInferenceStack.of(controllerContext.getGlobalSchema());
316         final var restconf = QName.create(restconfModule.getQNameModule(),
317             Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
318         stack.enterGrouping(restconf);
319         stack.enterSchemaTree(restconf);
320         final var streams = QName.create(restconf, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
321         final var streamsContainerSchemaNode = stack.enterSchemaTree(streams);
322         checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
323
324         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
325                 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
326         streamsContainerBuilder.withChild(listStreamsBuilder.build());
327
328         return new NormalizedNodeContext(InstanceIdentifierContext.ofStack(stack),
329                 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
330     }
331
332     @Override
333     @Deprecated
334     public String getOperationsJSON() {
335         return OperationsContent.JSON.bodyFor(controllerContext.getGlobalSchema());
336     }
337
338     @Override
339     @Deprecated
340     public String getOperationsXML() {
341         return OperationsContent.XML.bodyFor(controllerContext.getGlobalSchema());
342     }
343
344     @Override
345     @Deprecated
346     public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
347         if (!identifier.contains(ControllerContext.MOUNT)) {
348             final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
349                     + " end with " +  ControllerContext.MOUNT;
350             LOG.debug("{} for {}", errMsg, identifier);
351             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
352         }
353
354         final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
355         final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
356         final var entry = OperationsResourceUtils.contextForModelContext(modelContext(mountPoint), mountPoint);
357         return new NormalizedNodeContext(entry.getKey(), entry.getValue());
358     }
359
360     private Module getRestconfModule() {
361         final Module restconfModule = controllerContext.getRestconfModule();
362         if (restconfModule == null) {
363             LOG.debug("ietf-restconf module was not found.");
364             throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
365                     ErrorTag.OPERATION_NOT_SUPPORTED);
366         }
367
368         return restconfModule;
369     }
370
371     private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
372         final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
373         String moduleNameAndRevision = "";
374         if (mountIndex >= 0) {
375             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
376         } else {
377             moduleNameAndRevision = identifier;
378         }
379
380         final Splitter splitter = Splitter.on('/').omitEmptyStrings();
381         final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
382         if (pathArgs.size() < 2) {
383             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
384             throw new RestconfDocumentedException(
385                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
386                     ErrorTag.INVALID_VALUE);
387         }
388
389         try {
390             return Map.entry(pathArgs.get(0), Revision.of(pathArgs.get(1)));
391         } catch (final DateTimeParseException e) {
392             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
393             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
394                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
395         }
396     }
397
398     @Override
399     public Object getRoot() {
400         return null;
401     }
402
403     @Override
404     public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
405             final UriInfo uriInfo) {
406         if (payload == null) {
407             // no payload specified, reroute this to no payload invokeRpc implementation
408             return invokeRpc(identifier, uriInfo);
409         }
410
411         final SchemaNode schema = payload.getInstanceIdentifierContext().getSchemaNode();
412         final ListenableFuture<? extends DOMRpcResult> response;
413         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
414         final NormalizedNode input =  nonnullInput(schema, payload.getData());
415         final EffectiveModelContext schemaContext;
416
417         if (mountPoint != null) {
418             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
419             if (mountRpcServices.isEmpty()) {
420                 LOG.debug("Error: Rpc service is missing.");
421                 throw new RestconfDocumentedException("Rpc service is missing.");
422             }
423             schemaContext = modelContext(mountPoint);
424             response = mountRpcServices.get().invokeRpc(schema.getQName(), input);
425         } else {
426             final XMLNamespace namespace = schema.getQName().getNamespace();
427             if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
428                 if (identifier.contains(CREATE_DATA_SUBSCR)) {
429                     response = invokeSalRemoteRpcSubscribeRPC(payload);
430                 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
431                     response = invokeSalRemoteRpcNotifiStrRPC(payload);
432                 } else {
433                     final String msg = "Not supported operation";
434                     LOG.warn(msg);
435                     throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
436                 }
437             } else {
438                 response = broker.invokeRpc(schema.getQName(), input);
439             }
440             schemaContext = controllerContext.getGlobalSchema();
441         }
442
443         final DOMRpcResult result = checkRpcResponse(response);
444
445         final NormalizedNode resultData;
446         if (result != null && result.getResult() != null) {
447             resultData = result.getResult();
448         } else {
449             resultData = null;
450         }
451
452         if (resultData != null && ((ContainerNode) resultData).isEmpty()) {
453             throw new WebApplicationException(Response.Status.NO_CONTENT);
454         }
455
456         final var resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
457         return new NormalizedNodeContext(
458             InstanceIdentifierContext.ofRpcOutput(schemaContext, resultNodeSchema, mountPoint), resultData,
459             QueryParametersParser.parseWriterParameters(uriInfo));
460     }
461
462     @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE",
463             justification = "Looks like a false positive, see below FIXME")
464     private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
465         final DOMMountPoint mountPoint;
466         final String identifierEncoded;
467         final EffectiveModelContext schemaContext;
468         if (identifier.contains(ControllerContext.MOUNT)) {
469             // mounted RPC call - look up mount instance.
470             final InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
471             mountPoint = mountPointId.getMountPoint();
472             schemaContext = modelContext(mountPoint);
473             final int startOfRemoteRpcName =
474                     identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
475             final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
476             identifierEncoded = remoteRpcName;
477
478         } else if (identifier.indexOf('/') == CHAR_NOT_FOUND) {
479             identifierEncoded = identifier;
480             mountPoint = null;
481             schemaContext = controllerContext.getGlobalSchema();
482         } else {
483             LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
484             throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
485                     + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
486                 ErrorTag.INVALID_VALUE);
487         }
488
489         final String identifierDecoded = ControllerContext.urlPathArgDecode(identifierEncoded);
490         final RpcDefinition rpc;
491         if (mountPoint == null) {
492             rpc = controllerContext.getRpcDefinition(identifierDecoded);
493         } else {
494             rpc = findRpc(modelContext(mountPoint), identifierDecoded);
495         }
496
497         if (rpc == null) {
498             LOG.debug("RPC {} does not exist.", identifierDecoded);
499             throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
500         }
501
502         if (!rpc.getInput().getChildNodes().isEmpty()) {
503             LOG.debug("No input specified for RPC {} with an input section", rpc);
504             throw new RestconfDocumentedException("No input specified for RPC " + rpc
505                     + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
506         }
507
508         final ContainerNode input = defaultInput(rpc.getQName());
509         final ListenableFuture<? extends DOMRpcResult> response;
510         if (mountPoint != null) {
511             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
512             if (mountRpcServices.isEmpty()) {
513                 throw new RestconfDocumentedException("Rpc service is missing.");
514             }
515             response = mountRpcServices.get().invokeRpc(rpc.getQName(), input);
516         } else {
517             response = broker.invokeRpc(rpc.getQName(), input);
518         }
519
520         final NormalizedNode result = checkRpcResponse(response).getResult();
521         if (result != null && ((ContainerNode) result).isEmpty()) {
522             throw new WebApplicationException(Response.Status.NO_CONTENT);
523         }
524
525         // FIXME: in reference to the above @SupressFBWarnings: "mountPoint" reference here trips up SpotBugs, as it
526         //        thinks it can only ever be null. Except it can very much be non-null. The core problem is the horrible
527         //        structure of this code where we have a sh*tload of checks for mountpoint above and all over the
528         //        codebase where all that difference should have been properly encapsulated.
529         //
530         //        This is legacy code, so if anybody cares to do that refactor, feel free to contribute, but I am not
531         //        doing that work.
532         final var iic = mountPoint == null ? InstanceIdentifierContext.ofLocalRpcOutput(schemaContext, rpc)
533             : InstanceIdentifierContext.ofMountPointRpcOutput(mountPoint, schemaContext, rpc);
534         return new NormalizedNodeContext(iic, result, QueryParametersParser.parseWriterParameters(uriInfo));
535     }
536
537     private static @NonNull NormalizedNode nonnullInput(final SchemaNode rpc, final NormalizedNode input) {
538         return input != null ? input : defaultInput(rpc.getQName());
539     }
540
541     private static @NonNull ContainerNode defaultInput(final QName rpcName) {
542         return ImmutableNodes.containerNode(YangConstants.operationInputQName(rpcName.getModule()));
543     }
544
545     @SuppressWarnings("checkstyle:avoidHidingCauseException")
546     private static DOMRpcResult checkRpcResponse(final ListenableFuture<? extends DOMRpcResult> response) {
547         if (response == null) {
548             return null;
549         }
550         try {
551             final DOMRpcResult retValue = response.get();
552             if (retValue.getErrors().isEmpty()) {
553                 return retValue;
554             }
555             LOG.debug("RpcError message {}", retValue.getErrors());
556             throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
557         } catch (final InterruptedException e) {
558             final String errMsg = "The operation was interrupted while executing and did not complete.";
559             LOG.debug("Rpc Interrupt - {}", errMsg, e);
560             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
561         } catch (final ExecutionException e) {
562             LOG.debug("Execution RpcError: ", e);
563             Throwable cause = e.getCause();
564             if (cause == null) {
565                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
566                     e);
567             }
568             while (cause.getCause() != null) {
569                 cause = cause.getCause();
570             }
571
572             if (cause instanceof IllegalArgumentException) {
573                 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
574             } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
575                 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
576                     ErrorTag.OPERATION_NOT_SUPPORTED);
577             }
578             throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
579                 cause);
580         } catch (final CancellationException e) {
581             final String errMsg = "The operation was cancelled while executing.";
582             LOG.debug("Cancel RpcExecution: {}", errMsg, e);
583             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
584         }
585     }
586
587     private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
588         if (inputSchema != null && payload.getData() == null) {
589             // expected a non null payload
590             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
591         } else if (inputSchema == null && payload.getData() != null) {
592             // did not expect any input
593             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
594         }
595     }
596
597     private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
598         final ContainerNode value = (ContainerNode) payload.getData();
599         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
600         final Optional<DataContainerChild> path =
601             value.findChildByArg(new NodeIdentifier(QName.create(rpcQName, "path")));
602         final Object pathValue = path.isPresent() ? path.get().body() : null;
603
604         if (!(pathValue instanceof YangInstanceIdentifier)) {
605             LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
606             throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
607                 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
608         }
609
610         final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
611         final String streamName;
612         NotificationOutputType outputType = null;
613         if (!pathIdentifier.isEmpty()) {
614             final String fullRestconfIdentifier =
615                     DATA_SUBSCR + controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
616
617             LogicalDatastoreType datastore =
618                     parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
619             datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
620
621             Scope scope = parseEnumTypeParameter(value, Scope.class, SCOPE_PARAM_NAME);
622             scope = scope == null ? Scope.BASE : scope;
623
624             outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
625             outputType = outputType == null ? NotificationOutputType.XML : outputType;
626
627             streamName = Notificator
628                     .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
629         } else {
630             streamName = CREATE_DATA_SUBSCR;
631         }
632
633         if (Strings.isNullOrEmpty(streamName)) {
634             LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
635                 pathIdentifier);
636             throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
637                     + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
638         }
639
640         if (!Notificator.existListenerFor(streamName)) {
641             Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
642         }
643
644         return Futures.immediateFuture(new DefaultDOMRpcResult(Builders.containerBuilder()
645             .withNodeIdentifier(new NodeIdentifier(QName.create(rpcQName, "output")))
646             .withChild(ImmutableNodes.leafNode(QName.create(rpcQName, "stream-name"), streamName))
647             .build()));
648     }
649
650     private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
651         final String[] splittedIdentifier = identifierDecoded.split(":");
652         if (splittedIdentifier.length != 2) {
653             LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
654             throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
655                     + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
656         }
657         for (final Module module : schemaContext.getModules()) {
658             if (module.getName().equals(splittedIdentifier[0])) {
659                 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
660                     if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
661                         return rpcDefinition;
662                     }
663                 }
664             }
665         }
666         return null;
667     }
668
669     @Override
670     public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
671         boolean withDefaUsed = false;
672         String withDefa = null;
673
674         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
675             switch (entry.getKey()) {
676                 case "with-defaults":
677                     if (!withDefaUsed) {
678                         withDefaUsed = true;
679                         withDefa = entry.getValue().iterator().next();
680                     } else {
681                         throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
682                     }
683                     break;
684                 default:
685                     LOG.info("Unknown key : {}.", entry.getKey());
686                     break;
687             }
688         }
689
690         // TODO: this flag is always ignored
691         boolean tagged = false;
692         if (withDefaUsed) {
693             if ("report-all-tagged".equals(withDefa)) {
694                 tagged = true;
695                 withDefa = null;
696             }
697             if ("report-all".equals(withDefa)) {
698                 withDefa = null;
699             }
700         }
701
702         final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
703         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
704         NormalizedNode data = null;
705         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
706         if (mountPoint != null) {
707             data = broker.readConfigurationData(mountPoint, normalizedII, withDefa);
708         } else {
709             data = broker.readConfigurationData(normalizedII, withDefa);
710         }
711         if (data == null) {
712             throw dataMissing(identifier);
713         }
714         return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
715     }
716
717     @Override
718     public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
719         final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
720         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
721         NormalizedNode data = null;
722         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
723         if (mountPoint != null) {
724             data = broker.readOperationalData(mountPoint, normalizedII);
725         } else {
726             data = broker.readOperationalData(normalizedII);
727         }
728         if (data == null) {
729             throw dataMissing(identifier);
730         }
731         return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
732     }
733
734     private static RestconfDocumentedException dataMissing(final String identifier) {
735         LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
736             identifier);
737         return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
738             + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
739     }
740
741     @Override
742     public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
743             final UriInfo uriInfo) {
744         boolean insertUsed = false;
745         boolean pointUsed = false;
746         String insert = null;
747         String point = null;
748
749         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
750             switch (entry.getKey()) {
751                 case "insert":
752                     if (!insertUsed) {
753                         insertUsed = true;
754                         insert = entry.getValue().iterator().next();
755                     } else {
756                         throw new RestconfDocumentedException("Insert parameter can be used only once.");
757                     }
758                     break;
759                 case "point":
760                     if (!pointUsed) {
761                         pointUsed = true;
762                         point = entry.getValue().iterator().next();
763                     } else {
764                         throw new RestconfDocumentedException("Point parameter can be used only once.");
765                     }
766                     break;
767                 default:
768                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
769             }
770         }
771
772         if (pointUsed && !insertUsed) {
773             throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
774         }
775         if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
776             throw new RestconfDocumentedException(
777                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
778         }
779
780         requireNonNull(identifier);
781
782         final InstanceIdentifierContext iiWithData = payload.getInstanceIdentifierContext();
783
784         validateInput(iiWithData.getSchemaNode(), payload);
785         validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
786         validateListKeysEqualityInPayloadAndUri(payload);
787
788         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
789         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
790
791         /*
792          * There is a small window where another write transaction could be
793          * updating the same data simultaneously and we get an
794          * OptimisticLockFailedException. This error is likely transient and The
795          * WriteTransaction#submit API docs state that a retry will likely
796          * succeed. So we'll try again if that scenario occurs. If it fails a
797          * third time then it probably will never succeed so we'll fail in that
798          * case.
799          *
800          * By retrying we're attempting to hide the internal implementation of
801          * the data store and how it handles concurrent updates from the
802          * restconf client. The client has instructed us to put the data and we
803          * should make every effort to do so without pushing optimistic lock
804          * failures back to the client and forcing them to handle it via retry
805          * (and having to document the behavior).
806          */
807         PutResult result = null;
808         int tries = 2;
809         while (true) {
810             if (mountPoint != null) {
811
812                 result = broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
813                         point);
814             } else {
815                 result = broker.commitConfigurationDataPut(controllerContext.getGlobalSchema(), normalizedII,
816                         payload.getData(), insert, point);
817             }
818
819             try {
820                 result.getFutureOfPutData().get();
821             } catch (final InterruptedException e) {
822                 LOG.debug("Update failed for {}", identifier, e);
823                 throw new RestconfDocumentedException(e.getMessage(), e);
824             } catch (final ExecutionException e) {
825                 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
826                     TransactionCommitFailedException.class);
827                 if (failure instanceof OptimisticLockFailedException) {
828                     if (--tries <= 0) {
829                         LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
830                         throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
831                     }
832
833                     LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
834                     continue;
835                 }
836
837                 LOG.debug("Update failed for {}", identifier, e);
838                 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
839             }
840
841             return Response.status(result.getStatus()).build();
842         }
843     }
844
845     private static void validateTopLevelNodeName(final NormalizedNodeContext node,
846             final YangInstanceIdentifier identifier) {
847
848         final String payloadName = node.getData().getIdentifier().getNodeType().getLocalName();
849
850         // no arguments
851         if (identifier.isEmpty()) {
852             // no "data" payload
853             if (!node.getData().getIdentifier().getNodeType().equals(NETCONF_BASE_QNAME)) {
854                 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
855                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
856             }
857             // any arguments
858         } else {
859             final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
860             if (!payloadName.equals(identifierName)) {
861                 throw new RestconfDocumentedException(
862                         "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
863                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
864             }
865         }
866     }
867
868     /**
869      * Validates whether keys in {@code payload} are equal to values of keys in
870      * {@code iiWithData} for list schema node.
871      *
872      * @throws RestconfDocumentedException
873      *             if key values or key count in payload and URI isn't equal
874      *
875      */
876     private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
877         checkArgument(payload != null);
878         final InstanceIdentifierContext iiWithData = payload.getInstanceIdentifierContext();
879         final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
880         final SchemaNode schemaNode = iiWithData.getSchemaNode();
881         final NormalizedNode data = payload.getData();
882         if (schemaNode instanceof ListSchemaNode) {
883             final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
884             if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
885                 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
886                 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
887             }
888         }
889     }
890
891     @VisibleForTesting
892     public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
893             final List<QName> keyDefinitions) {
894
895         final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
896         for (final QName keyDefinition : keyDefinitions) {
897             final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
898                 // should be caught during parsing URI to InstanceIdentifier
899                 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
900                 "Missing key %s in URI.", keyDefinition);
901
902             final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
903
904             if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
905                 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
906                         + "' specified in the URI doesn't match the value '" + dataKeyValue
907                         + "' specified in the message body. ";
908                 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
909             }
910         }
911     }
912
913     @Override
914     public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
915             final UriInfo uriInfo) {
916         return createConfigurationData(payload, uriInfo);
917     }
918
919     @Override
920     public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
921         if (payload == null) {
922             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
923         }
924         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
925         final InstanceIdentifierContext iiWithData = payload.getInstanceIdentifierContext();
926         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
927
928         boolean insertUsed = false;
929         boolean pointUsed = false;
930         String insert = null;
931         String point = null;
932
933         if (uriInfo != null) {
934             for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
935                 switch (entry.getKey()) {
936                     case "insert":
937                         if (!insertUsed) {
938                             insertUsed = true;
939                             insert = entry.getValue().iterator().next();
940                         } else {
941                             throw new RestconfDocumentedException("Insert parameter can be used only once.");
942                         }
943                         break;
944                     case "point":
945                         if (!pointUsed) {
946                             pointUsed = true;
947                             point = entry.getValue().iterator().next();
948                         } else {
949                             throw new RestconfDocumentedException("Point parameter can be used only once.");
950                         }
951                         break;
952                     default:
953                         throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
954                 }
955             }
956         }
957
958         if (pointUsed && !insertUsed) {
959             throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
960         }
961         if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
962             throw new RestconfDocumentedException(
963                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
964         }
965
966         FluentFuture<? extends CommitInfo> future;
967         if (mountPoint != null) {
968             future = broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
969                     point);
970         } else {
971             future = broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII,
972                     payload.getData(), insert, point);
973         }
974
975         try {
976             future.get();
977         } catch (final InterruptedException e) {
978             LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
979             throw new RestconfDocumentedException(e.getMessage(), e);
980         } catch (final ExecutionException e) {
981             LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
982             throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
983                 TransactionCommitFailedException.class));
984         }
985
986         LOG.trace("Successfuly created data.");
987
988         final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
989         // FIXME: Provide path to result.
990         final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
991         if (location != null) {
992             responseBuilder.location(location);
993         }
994         return responseBuilder.build();
995     }
996
997     @SuppressWarnings("checkstyle:IllegalCatch")
998     private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
999             final YangInstanceIdentifier normalizedII) {
1000         if (uriInfo == null) {
1001             // This is null if invoked internally
1002             return null;
1003         }
1004
1005         final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1006         uriBuilder.path("config");
1007         try {
1008             uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1009         } catch (final Exception e) {
1010             LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1011             return null;
1012         }
1013         return uriBuilder.build();
1014     }
1015
1016     @Override
1017     public Response deleteConfigurationData(final String identifier) {
1018         final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
1019         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1020         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1021
1022         final FluentFuture<? extends CommitInfo> future;
1023         if (mountPoint != null) {
1024             future = broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1025         } else {
1026             future = broker.commitConfigurationDataDelete(normalizedII);
1027         }
1028
1029         try {
1030             future.get();
1031         } catch (final InterruptedException e) {
1032             throw new RestconfDocumentedException(e.getMessage(), e);
1033         } catch (final ExecutionException e) {
1034             final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1035                     Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1036             if (searchedException.isPresent()) {
1037                 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1038                     ErrorTag.DATA_MISSING, e);
1039             }
1040
1041             throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1042                 TransactionCommitFailedException.class));
1043         }
1044
1045         return Response.status(Status.OK).build();
1046     }
1047
1048     /**
1049      * Subscribes to some path in schema context (stream) to listen on changes
1050      * on this stream.
1051      *
1052      * <p>
1053      * Additional parameters for subscribing to stream are loaded via rpc input
1054      * parameters:
1055      * <ul>
1056      * <li>datastore - default CONFIGURATION (other values of
1057      * {@link LogicalDatastoreType} enum type)</li>
1058      * <li>scope - default BASE (other values of {@link Scope})</li>
1059      * </ul>
1060      */
1061     @Override
1062     public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1063         boolean startTimeUsed = false;
1064         boolean stopTimeUsed = false;
1065         Instant start = Instant.now();
1066         Instant stop = null;
1067         boolean filterUsed = false;
1068         String filter = null;
1069         boolean leafNodesOnlyUsed = false;
1070         boolean leafNodesOnly = false;
1071         boolean skipNotificationDataUsed = false;
1072         boolean skipNotificationData = false;
1073
1074         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1075             switch (entry.getKey()) {
1076                 case "start-time":
1077                     if (!startTimeUsed) {
1078                         startTimeUsed = true;
1079                         start = parseDateFromQueryParam(entry);
1080                     } else {
1081                         throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1082                     }
1083                     break;
1084                 case "stop-time":
1085                     if (!stopTimeUsed) {
1086                         stopTimeUsed = true;
1087                         stop = parseDateFromQueryParam(entry);
1088                     } else {
1089                         throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1090                     }
1091                     break;
1092                 case "filter":
1093                     if (!filterUsed) {
1094                         filterUsed = true;
1095                         filter = entry.getValue().iterator().next();
1096                     } else {
1097                         throw new RestconfDocumentedException("Filter parameter can be used only once.");
1098                     }
1099                     break;
1100                 case "odl-leaf-nodes-only":
1101                     if (!leafNodesOnlyUsed) {
1102                         leafNodesOnlyUsed = true;
1103                         leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1104                     } else {
1105                         throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1106                     }
1107                     break;
1108                 case "odl-skip-notification-data":
1109                     if (!skipNotificationDataUsed) {
1110                         skipNotificationDataUsed = true;
1111                         skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
1112                     } else {
1113                         throw new RestconfDocumentedException(
1114                                 "Odl-skip-notification-data parameter can be used only once.");
1115                     }
1116                     break;
1117                 default:
1118                     throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1119             }
1120         }
1121         if (!startTimeUsed && stopTimeUsed) {
1122             throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1123         }
1124         URI response = null;
1125         if (identifier.contains(DATA_SUBSCR)) {
1126             response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly, skipNotificationData);
1127         } else if (identifier.contains(NOTIFICATION_STREAM)) {
1128             response = notifStream(identifier, uriInfo, start, stop, filter);
1129         }
1130
1131         if (response != null) {
1132             // prepare node with value of location
1133
1134             final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1135             final QName locationQName = QName.create(qnameBase, "location");
1136
1137             final var stack = SchemaInferenceStack.of(controllerContext.getGlobalSchema());
1138             stack.enterSchemaTree(qnameBase);
1139             stack.enterSchemaTree(locationQName);
1140
1141             // prepare new header with location
1142             return new NormalizedNodeContext(InstanceIdentifierContext.ofStack(stack),
1143                 ImmutableNodes.leafNode(locationQName, response.toString()), ImmutableMap.of("Location", response));
1144         }
1145
1146         final String msg = "Bad type of notification of sal-remote";
1147         LOG.warn(msg);
1148         throw new RestconfDocumentedException(msg);
1149     }
1150
1151     private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1152         final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1153         final String value = event.getValue();
1154         final TemporalAccessor p;
1155         try {
1156             p = FORMATTER.parse(value);
1157         } catch (final DateTimeParseException e) {
1158             throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1159         }
1160         return Instant.from(p);
1161     }
1162
1163     /**
1164      * Register notification listener by stream name.
1165      *
1166      * @param identifier
1167      *            stream name
1168      * @param uriInfo
1169      *            uriInfo
1170      * @param stop
1171      *            stop-time of getting notification
1172      * @param start
1173      *            start-time of getting notification
1174      * @param filter
1175      *            indicate which subset of all possible events are of interest
1176      * @return {@link URI} of location
1177      */
1178     private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1179             final Instant stop, final String filter) {
1180         final String streamName = Notificator.createStreamNameFromUri(identifier);
1181         if (Strings.isNullOrEmpty(streamName)) {
1182             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1183         }
1184         final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1185         if (listeners == null || listeners.isEmpty()) {
1186             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1187                     ErrorTag.UNKNOWN_ELEMENT);
1188         }
1189
1190         for (final NotificationListenerAdapter listener : listeners) {
1191             broker.registerToListenNotification(listener);
1192             listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false, false);
1193         }
1194
1195         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1196
1197         final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1198         final int notificationPort = webSocketServerInstance.getPort();
1199
1200
1201         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1202
1203         return uriToWebsocketServerBuilder.replacePath(streamName).build();
1204     }
1205
1206     private static String getWsScheme(final UriInfo uriInfo) {
1207         URI uri = uriInfo.getAbsolutePath();
1208         if (uri == null) {
1209             return "ws";
1210         }
1211         String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1212         return subscriptionScheme.equals("https") ? "wss" : "ws";
1213     }
1214
1215     /**
1216      * Register data change listener by stream name.
1217      *
1218      * @param identifier
1219      *            stream name
1220      * @param uriInfo
1221      *            uri info
1222      * @param stop
1223      *            start-time of getting notification
1224      * @param start
1225      *            stop-time of getting notification
1226      * @param filter
1227      *            indicate which subset of all possible events are of interest
1228      * @return {@link URI} of location
1229      */
1230     private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1231             final String filter, final boolean leafNodesOnly, final boolean skipNotificationData) {
1232         final String streamName = Notificator.createStreamNameFromUri(identifier);
1233         if (Strings.isNullOrEmpty(streamName)) {
1234             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1235         }
1236
1237         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1238         if (listener == null) {
1239             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1240                     ErrorTag.UNKNOWN_ELEMENT);
1241         }
1242         listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly,
1243                 skipNotificationData);
1244
1245         final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1246         final LogicalDatastoreType datastore =
1247                 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1248         if (datastore == null) {
1249             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1250                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1251         }
1252         final Scope scope = parserURIEnumParameter(Scope.class, paramToValues.get(SCOPE_PARAM_NAME));
1253         if (scope == null) {
1254             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1255                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1256         }
1257
1258         broker.registerToListenDataChanges(datastore, scope, listener);
1259
1260         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1261
1262         final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1263         final int notificationPort = webSocketServerInstance.getPort();
1264
1265         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1266
1267         return uriToWebsocketServerBuilder.replacePath(streamName).build();
1268     }
1269
1270     @SuppressWarnings("checkstyle:IllegalCatch")
1271     @Override
1272     public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1273                                                      final UriInfo uriInfo) {
1274         if (context == null) {
1275             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1276         }
1277
1278         try {
1279             return broker.patchConfigurationDataWithinTransaction(context);
1280         } catch (final Exception e) {
1281             LOG.debug("Patch transaction failed", e);
1282             throw new RestconfDocumentedException(e.getMessage(), e);
1283         }
1284     }
1285
1286     @SuppressWarnings("checkstyle:IllegalCatch")
1287     @Override
1288     public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1289         if (context == null) {
1290             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1291         }
1292
1293         try {
1294             return broker.patchConfigurationDataWithinTransaction(context);
1295         } catch (final Exception e) {
1296             LOG.debug("Patch transaction failed", e);
1297             throw new RestconfDocumentedException(e.getMessage(), e);
1298         }
1299     }
1300
1301     /**
1302      * Load parameter for subscribing to stream from input composite node.
1303      *
1304      * @param value
1305      *            contains value
1306      * @return enum object if its string value is equal to {@code paramName}. In
1307      *         other cases null.
1308      */
1309     private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1310             final String paramName) {
1311         final Optional<DataContainerChild> optAugNode = value.findChildByArg(SAL_REMOTE_AUG_IDENTIFIER);
1312         if (optAugNode.isEmpty()) {
1313             return null;
1314         }
1315         final DataContainerChild augNode = optAugNode.get();
1316         if (!(augNode instanceof AugmentationNode)) {
1317             return null;
1318         }
1319         final Optional<DataContainerChild> enumNode = ((AugmentationNode) augNode).findChildByArg(
1320                 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1321         if (enumNode.isEmpty()) {
1322             return null;
1323         }
1324         final Object rawValue = enumNode.get().body();
1325         if (!(rawValue instanceof String)) {
1326             return null;
1327         }
1328
1329         return resolveAsEnum(classDescriptor, (String) rawValue);
1330     }
1331
1332     /**
1333      * Checks whether {@code value} is one of the string representation of
1334      * enumeration {@code classDescriptor}.
1335      *
1336      * @return enum object if string value of {@code classDescriptor}
1337      *         enumeration is equal to {@code value}. Other cases null.
1338      */
1339     private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1340         if (Strings.isNullOrEmpty(value)) {
1341             return null;
1342         }
1343         return resolveAsEnum(classDescriptor, value);
1344     }
1345
1346     private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1347         final T[] enumConstants = classDescriptor.getEnumConstants();
1348         if (enumConstants != null) {
1349             for (final T enm : classDescriptor.getEnumConstants()) {
1350                 if (((Enum<?>) enm).name().equals(value)) {
1351                     return enm;
1352                 }
1353             }
1354         }
1355         return null;
1356     }
1357
1358     private static Map<String, String> resolveValuesFromUri(final String uri) {
1359         final Map<String, String> result = new HashMap<>();
1360         final String[] tokens = uri.split("/");
1361         for (int i = 1; i < tokens.length; i++) {
1362             final String[] parameterTokens = tokens[i].split("=");
1363             if (parameterTokens.length == 2) {
1364                 result.put(parameterTokens[0], parameterTokens[1]);
1365             }
1366         }
1367         return result;
1368     }
1369
1370     private MapNode makeModuleMapNode(final Collection<? extends Module> modules) {
1371         requireNonNull(modules);
1372         final Module restconfModule = getRestconfModule();
1373         final DataSchemaNode moduleSchemaNode = controllerContext
1374                 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1375         checkState(moduleSchemaNode instanceof ListSchemaNode);
1376
1377         final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listModuleBuilder =
1378                 SchemaAwareBuilders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1379
1380         for (final Module module : modules) {
1381             listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1382         }
1383         return listModuleBuilder.build();
1384     }
1385
1386     private static MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1387         checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1388                 "moduleSchemaNode has to be of type ListSchemaNode");
1389         final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1390         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1391                 SchemaAwareBuilders.mapEntryBuilder(listModuleSchemaNode);
1392
1393         var instanceDataChildrenByName =
1394                 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1395         final LeafSchemaNode nameSchemaNode = getFirstLeaf(instanceDataChildrenByName);
1396         moduleNodeValues.withChild(
1397             SchemaAwareBuilders.leafBuilder(nameSchemaNode).withValue(module.getName()).build());
1398
1399         final QNameModule qNameModule = module.getQNameModule();
1400
1401         instanceDataChildrenByName =
1402                 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1403         final LeafSchemaNode revisionSchemaNode = getFirstLeaf(instanceDataChildrenByName);
1404         final Optional<Revision> revision = qNameModule.getRevision();
1405         moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder(revisionSchemaNode)
1406                 .withValue(revision.map(Revision::toString).orElse("")).build());
1407
1408         instanceDataChildrenByName =
1409                 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1410         final LeafSchemaNode namespaceSchemaNode = getFirstLeaf(instanceDataChildrenByName);
1411         moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder(namespaceSchemaNode)
1412                 .withValue(qNameModule.getNamespace().toString()).build());
1413
1414         instanceDataChildrenByName =
1415                 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1416         final LeafListSchemaNode featureSchemaNode = getFirst(instanceDataChildrenByName, LeafListSchemaNode.class);
1417         final ListNodeBuilder<Object, SystemLeafSetNode<Object>> featuresBuilder =
1418                 SchemaAwareBuilders.leafSetBuilder(featureSchemaNode);
1419         for (final FeatureDefinition feature : module.getFeatures()) {
1420             featuresBuilder.withChild(SchemaAwareBuilders.leafSetEntryBuilder(featureSchemaNode)
1421                     .withValue(feature.getQName().getLocalName()).build());
1422         }
1423         moduleNodeValues.withChild(featuresBuilder.build());
1424
1425         return moduleNodeValues.build();
1426     }
1427
1428     protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1429         checkArgument(streamSchemaNode instanceof ListSchemaNode,
1430                 "streamSchemaNode has to be of type ListSchemaNode");
1431         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1432         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1433                 SchemaAwareBuilders.mapEntryBuilder(listStreamSchemaNode);
1434
1435         var instanceDataChildrenByName =
1436                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1437         final LeafSchemaNode nameSchemaNode = getFirstLeaf(instanceDataChildrenByName);
1438         streamNodeValues.withChild(
1439             SchemaAwareBuilders.leafBuilder(nameSchemaNode).withValue(streamName).build());
1440
1441         instanceDataChildrenByName =
1442                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1443         final LeafSchemaNode descriptionSchemaNode = getFirstLeaf(instanceDataChildrenByName);
1444         streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder(descriptionSchemaNode)
1445             .withValue("DESCRIPTION_PLACEHOLDER")
1446             .build());
1447
1448         instanceDataChildrenByName =
1449                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1450         final LeafSchemaNode replaySupportSchemaNode = getFirstLeaf(instanceDataChildrenByName);
1451         streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder(replaySupportSchemaNode)
1452                 .withValue(Boolean.TRUE).build());
1453
1454         instanceDataChildrenByName =
1455                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1456         final LeafSchemaNode replayLogCreationTimeSchemaNode = getFirstLeaf(instanceDataChildrenByName);
1457         streamNodeValues.withChild(
1458             SchemaAwareBuilders.leafBuilder(replayLogCreationTimeSchemaNode).withValue("").build());
1459
1460         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1461         final LeafSchemaNode eventsSchemaNode = getFirstLeaf(instanceDataChildrenByName);
1462         streamNodeValues.withChild(
1463             SchemaAwareBuilders.leafBuilder(eventsSchemaNode).withValue(Empty.value()).build());
1464
1465         return streamNodeValues.build();
1466     }
1467
1468     /**
1469      * Prepare stream for notification.
1470      *
1471      * @param payload
1472      *            contains list of qnames of notifications
1473      * @return - checked future object
1474      */
1475     private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1476         final ContainerNode data = (ContainerNode) payload.getData();
1477         LeafSetNode leafSet = null;
1478         String outputType = "XML";
1479         for (final DataContainerChild dataChild : data.body()) {
1480             if (dataChild instanceof LeafSetNode) {
1481                 leafSet = (LeafSetNode) dataChild;
1482             } else if (dataChild instanceof AugmentationNode) {
1483                 outputType = (String) ((AugmentationNode) dataChild).body().iterator().next().body();
1484             }
1485         }
1486
1487         final Collection<LeafSetEntryNode<?>> entryNodes = leafSet.body();
1488         final List<Absolute> paths = new ArrayList<>();
1489
1490         StringBuilder streamNameBuilder = new StringBuilder(CREATE_NOTIFICATION_STREAM).append('/');
1491         final Iterator<LeafSetEntryNode<?>> iterator = entryNodes.iterator();
1492         while (iterator.hasNext()) {
1493             final QName valueQName = QName.create((String) iterator.next().body());
1494             final XMLNamespace namespace = valueQName.getModule().getNamespace();
1495             final Module module = controllerContext.findModuleByNamespace(namespace);
1496             checkNotNull(module, "Module for namespace %s does not exist", namespace);
1497             NotificationDefinition notifiDef = null;
1498             for (final NotificationDefinition notification : module.getNotifications()) {
1499                 if (notification.getQName().equals(valueQName)) {
1500                     notifiDef = notification;
1501                     break;
1502                 }
1503             }
1504             final String moduleName = module.getName();
1505             if (notifiDef == null) {
1506                 throw new IllegalArgumentException("Notification " + valueQName + " does not exist in module "
1507                     + moduleName);
1508             }
1509
1510             paths.add(Absolute.of(notifiDef.getQName()));
1511             streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1512             if (iterator.hasNext()) {
1513                 streamNameBuilder.append(',');
1514             }
1515         }
1516
1517         final String streamName = streamNameBuilder.toString();
1518         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1519
1520         if (!Notificator.existNotificationListenerFor(streamName)) {
1521             Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1522         }
1523
1524         return Futures.immediateFuture(new DefaultDOMRpcResult(Builders.containerBuilder()
1525             .withNodeIdentifier(new NodeIdentifier(QName.create(rpcQName, "output")))
1526             .withChild(ImmutableNodes.leafNode(QName.create(rpcQName, "notification-stream-identifier"), streamName))
1527             .build()));
1528     }
1529
1530     private static LeafSchemaNode getFirstLeaf(final List<FoundChild> children) {
1531         return getFirst(children, LeafSchemaNode.class);
1532     }
1533
1534     private static <T extends DataSchemaNode> T getFirst(final List<FoundChild> children, final Class<T> expected) {
1535         checkState(!children.isEmpty());
1536         final var first = children.get(0);
1537         checkState(expected.isInstance(first.child));
1538         return expected.cast(first.child);
1539     }
1540
1541     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
1542         return mountPoint.getService(DOMSchemaService.class)
1543             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
1544             .orElse(null);
1545     }
1546 }