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