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