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