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