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