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