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