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