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