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