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