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