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