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