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