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