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