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