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