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