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