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