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