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