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