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