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