Use ControllerContext non-statically
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / restconf / impl / RestconfImpl.java
1 /*
2  * Copyright (c) 2014 - 2016 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.netconf.sal.restconf.impl;
10
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Predicates;
16 import com.google.common.base.Splitter;
17 import com.google.common.base.Strings;
18 import com.google.common.base.Throwables;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterables;
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.time.Instant;
26 import java.time.format.DateTimeFormatter;
27 import java.time.format.DateTimeFormatterBuilder;
28 import java.time.format.DateTimeParseException;
29 import java.time.temporal.ChronoField;
30 import java.time.temporal.TemporalAccessor;
31 import java.util.AbstractMap.SimpleImmutableEntry;
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.Locale;
39 import java.util.Map;
40 import java.util.Map.Entry;
41 import java.util.Objects;
42 import java.util.Set;
43 import java.util.concurrent.CancellationException;
44 import java.util.concurrent.ExecutionException;
45 import javax.ws.rs.core.Context;
46 import javax.ws.rs.core.Response;
47 import javax.ws.rs.core.Response.ResponseBuilder;
48 import javax.ws.rs.core.Response.Status;
49 import javax.ws.rs.core.UriBuilder;
50 import javax.ws.rs.core.UriInfo;
51 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
52 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
53 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
54 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
55 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
58 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
59 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
60 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
61 import org.opendaylight.netconf.sal.rest.api.Draft02;
62 import org.opendaylight.netconf.sal.rest.api.RestconfService;
63 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
66 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
67 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
68 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
69 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
70 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
71 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
72 import org.opendaylight.restconf.common.patch.PatchContext;
73 import org.opendaylight.restconf.common.patch.PatchStatusContext;
74 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
76 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
77 import org.opendaylight.yangtools.yang.common.QName;
78 import org.opendaylight.yangtools.yang.common.QNameModule;
79 import org.opendaylight.yangtools.yang.common.Revision;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
85 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
88 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
95 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
96 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
98 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
103 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
106 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.Module;
110 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
111 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
112 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
113 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
115 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
116 import org.slf4j.Logger;
117 import org.slf4j.LoggerFactory;
118
119 public final class RestconfImpl implements RestconfService {
120
121     private static final RestconfImpl INSTANCE = new RestconfImpl();
122
123     /**
124      * Notifications are served on port 8181.
125      */
126     private static final int NOTIFICATION_PORT = 8181;
127
128     private static final int CHAR_NOT_FOUND = -1;
129
130     private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
131
132     private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
133
134     private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
135
136     private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
137
138     private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
139
140     private static final String DATASTORE_PARAM_NAME = "datastore";
141
142     private static final String SCOPE_PARAM_NAME = "scope";
143
144     private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
145
146     private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
147
148     private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
149
150     private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
151         NETCONF_BASE_PAYLOAD_NAME).intern();
152
153     private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
154         Revision.of("2014-07-08"));
155
156     private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
157             new AugmentationIdentifier(ImmutableSet.of(
158                 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
159                 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
160
161     public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
162     private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
163
164     public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
165     private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
166
167     private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
168             .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
169             .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
170             .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
171             .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
172             .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
173             .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
174             .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
175             .appendOffset("+HH:MM", "Z").toFormatter();
176
177     private BrokerFacade broker;
178
179     private ControllerContext controllerContext;
180
181     public void setBroker(final BrokerFacade broker) {
182         this.broker = broker;
183     }
184
185     public void setControllerContext(final ControllerContext controllerContext) {
186         this.controllerContext = controllerContext;
187     }
188
189     private RestconfImpl() {
190     }
191
192     public static RestconfImpl getInstance() {
193         return INSTANCE;
194     }
195
196     @Override
197     public NormalizedNodeContext getModules(final UriInfo uriInfo) {
198         final Set<Module> allModules = this.controllerContext.getAllModules();
199         final MapNode allModuleMap = makeModuleMapNode(allModules);
200
201         final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
202
203         final Module restconfModule = getRestconfModule();
204         final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
205                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
206         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
207
208         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
209                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
210         moduleContainerBuilder.withChild(allModuleMap);
211
212         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
213                 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
214     }
215
216     /**
217      * Valid only for mount point.
218      */
219     @Override
220     public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
221         Preconditions.checkNotNull(identifier);
222         if (!identifier.contains(ControllerContext.MOUNT)) {
223             final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
224                     + " URI has to end with " + ControllerContext.MOUNT;
225             LOG.debug(errMsg + " for " + identifier);
226             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
227         }
228
229         final InstanceIdentifierContext<?> mountPointIdentifier =
230                 this.controllerContext.toMountPointIdentifier(identifier);
231         final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
232         final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
233         final MapNode mountPointModulesMap = makeModuleMapNode(modules);
234
235         final Module restconfModule = getRestconfModule();
236         final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
237                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
238         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
239
240         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
241                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
242         moduleContainerBuilder.withChild(mountPointModulesMap);
243
244         return new NormalizedNodeContext(
245                 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
246                         this.controllerContext.getGlobalSchema()),
247                 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
248     }
249
250     @Override
251     public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
252         Preconditions.checkNotNull(identifier);
253         final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
254         Module module = null;
255         DOMMountPoint mountPoint = null;
256         final SchemaContext schemaContext;
257         if (identifier.contains(ControllerContext.MOUNT)) {
258             final InstanceIdentifierContext<?> mountPointIdentifier =
259                     this.controllerContext.toMountPointIdentifier(identifier);
260             mountPoint = mountPointIdentifier.getMountPoint();
261             module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
262                 nameRev.getValue());
263             schemaContext = mountPoint.getSchemaContext();
264         } else {
265             module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
266             schemaContext = this.controllerContext.getGlobalSchema();
267         }
268
269         if (module == null) {
270             final String errMsg = "Module with name '" + nameRev.getKey() + "' and revision '"
271                     + nameRev.getValue() + "' was not found.";
272             LOG.debug(errMsg);
273             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
274         }
275
276         final Module restconfModule = getRestconfModule();
277         final Set<Module> modules = Collections.singleton(module);
278         final MapNode moduleMap = makeModuleMapNode(modules);
279
280         final DataSchemaNode moduleSchemaNode = this.controllerContext
281                 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
282         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
283
284         return new NormalizedNodeContext(
285                 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
286                 QueryParametersParser.parseWriterParameters(uriInfo));
287     }
288
289     @Override
290     public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
291         final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
292         final Set<String> availableStreams = Notificator.getStreamNames();
293         final Module restconfModule = getRestconfModule();
294         final DataSchemaNode streamSchemaNode = this.controllerContext
295                 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
296         Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
297
298         final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
299                 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
300
301         for (final String streamName : availableStreams) {
302             listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
303         }
304
305         final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
306                 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
307         Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
308
309         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
310                 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
311         streamsContainerBuilder.withChild(listStreamsBuilder.build());
312
313         return new NormalizedNodeContext(
314                 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
315                 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
316     }
317
318     @Override
319     public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
320         final Set<Module> allModules = this.controllerContext.getAllModules();
321         return operationsFromModulesToNormalizedContext(allModules, null);
322     }
323
324     @Override
325     public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
326         Set<Module> modules = null;
327         DOMMountPoint mountPoint = null;
328         if (identifier.contains(ControllerContext.MOUNT)) {
329             final InstanceIdentifierContext<?> mountPointIdentifier =
330                     this.controllerContext.toMountPointIdentifier(identifier);
331             mountPoint = mountPointIdentifier.getMountPoint();
332             modules = this.controllerContext.getAllModules(mountPoint);
333
334         } else {
335             final String errMsg =
336                     "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
337             LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
338             throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
339                     ErrorTag.INVALID_VALUE);
340         }
341
342         return operationsFromModulesToNormalizedContext(modules, mountPoint);
343     }
344
345     /**
346      * Special case only for GET restconf/operations use (since moment of
347      * pre-Beryllium Yang parser and Yang model API removal). The method is
348      * creating fake schema context with fake module and fake data by use own
349      * implementations of schema nodes and module.
350      *
351      * @param modules
352      *            set of modules for get RPCs from every module
353      * @param mountPoint
354      *            mount point, if in use otherwise null
355      * @return {@link NormalizedNodeContext}
356      */
357     private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
358             final DOMMountPoint mountPoint) {
359
360         final Collection<Module> neededModules = new ArrayList<>(modules.size());
361         final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
362
363         for (final Module m : modules) {
364             final Set<RpcDefinition> rpcs = m.getRpcs();
365             if (!rpcs.isEmpty()) {
366                 neededModules.add(m);
367
368                 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
369                 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
370             }
371         }
372
373         final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
374         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
375                 Builders.containerBuilder(fakeCont);
376
377         for (final LeafSchemaNode leaf : fakeRpcSchema) {
378             containerBuilder.withChild(Builders.leafBuilder(leaf).build());
379         }
380
381         final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
382         neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
383         fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
384
385         final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
386         final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
387                 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
388         return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
389     }
390
391     private Module getRestconfModule() {
392         final Module restconfModule = this.controllerContext.getRestconfModule();
393         if (restconfModule == null) {
394             LOG.debug("ietf-restconf module was not found.");
395             throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
396                     ErrorTag.OPERATION_NOT_SUPPORTED);
397         }
398
399         return restconfModule;
400     }
401
402     private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
403         final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
404         String moduleNameAndRevision = "";
405         if (mountIndex >= 0) {
406             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
407         } else {
408             moduleNameAndRevision = identifier;
409         }
410
411         final Splitter splitter = Splitter.on('/').omitEmptyStrings();
412         final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
413         if (pathArgs.size() < 2) {
414             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
415             throw new RestconfDocumentedException(
416                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
417                     ErrorTag.INVALID_VALUE);
418         }
419
420         try {
421             return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
422         } catch (final DateTimeParseException e) {
423             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
424             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
425                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
426         }
427     }
428
429     @Override
430     public Object getRoot() {
431         return null;
432     }
433
434     @Override
435     public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
436             final UriInfo uriInfo) {
437         final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
438         final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
439         final CheckedFuture<DOMRpcResult, DOMRpcException> response;
440         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
441         final SchemaContext schemaContext;
442
443         if (mountPoint != null) {
444             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
445             if (!mountRpcServices.isPresent()) {
446                 LOG.debug("Error: Rpc service is missing.");
447                 throw new RestconfDocumentedException("Rpc service is missing.");
448             }
449             schemaContext = mountPoint.getSchemaContext();
450             response = mountRpcServices.get().invokeRpc(type, payload.getData());
451         } else {
452             if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
453                 if (identifier.contains(CREATE_DATA_SUBSCR)) {
454                     response = invokeSalRemoteRpcSubscribeRPC(payload);
455                 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
456                     response = invokeSalRemoteRpcNotifiStrRPC(payload);
457                 } else {
458                     final String msg = "Not supported operation";
459                     LOG.warn(msg);
460                     throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
461                 }
462             } else {
463                 response = this.broker.invokeRpc(type, payload.getData());
464             }
465             schemaContext = this.controllerContext.getGlobalSchema();
466         }
467
468         final DOMRpcResult result = checkRpcResponse(response);
469
470         RpcDefinition resultNodeSchema = null;
471         final NormalizedNode<?, ?> resultData;
472         if (result != null && result.getResult() != null) {
473             resultData = result.getResult();
474             resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
475         } else {
476             resultData = null;
477         }
478
479         return new NormalizedNodeContext(
480                 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
481                 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
482     }
483
484     @Override
485     public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
486         if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
487             throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
488         }
489
490         String identifierEncoded = null;
491         DOMMountPoint mountPoint = null;
492         final SchemaContext schemaContext;
493         if (identifier.contains(ControllerContext.MOUNT)) {
494             // mounted RPC call - look up mount instance.
495             final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
496             mountPoint = mountPointId.getMountPoint();
497             schemaContext = mountPoint.getSchemaContext();
498             final int startOfRemoteRpcName =
499                     identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
500             final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
501             identifierEncoded = remoteRpcName;
502
503         } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
504             final String slashErrorMsg = String.format(
505                     "Identifier %n%s%ncan\'t contain slash "
506                             + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
507                     identifier);
508             LOG.debug(slashErrorMsg);
509             throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
510         } else {
511             identifierEncoded = identifier;
512             schemaContext = this.controllerContext.getGlobalSchema();
513         }
514
515         final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
516
517         RpcDefinition rpc = null;
518         if (mountPoint == null) {
519             rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
520         } else {
521             rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
522         }
523
524         if (rpc == null) {
525             LOG.debug("RPC " + identifierDecoded + " does not exist.");
526             throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
527         }
528
529         if (!rpc.getInput().getChildNodes().isEmpty()) {
530             LOG.debug("RPC " + rpc + " does not need input value.");
531             throw new RestconfDocumentedException("RPC " + rpc + " does not take any input value.",
532                     ErrorType.RPC, ErrorTag.INVALID_VALUE);
533         }
534
535         final CheckedFuture<DOMRpcResult, DOMRpcException> response;
536         if (mountPoint != null) {
537             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
538             if (!mountRpcServices.isPresent()) {
539                 throw new RestconfDocumentedException("Rpc service is missing.");
540             }
541             response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
542         } else {
543             response = this.broker.invokeRpc(rpc.getPath(), null);
544         }
545
546         final DOMRpcResult result = checkRpcResponse(response);
547
548         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
549                 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
550     }
551
552     @SuppressWarnings("checkstyle:avoidHidingCauseException")
553     private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
554         if (response == null) {
555             return null;
556         }
557         try {
558             final DOMRpcResult retValue = response.get();
559             if (retValue.getErrors().isEmpty()) {
560                 return retValue;
561             }
562             LOG.debug("RpcError message", retValue.getErrors());
563             throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
564         } catch (final InterruptedException e) {
565             final String errMsg = "The operation was interrupted while executing and did not complete.";
566             LOG.debug("Rpc Interrupt - " + errMsg, e);
567             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
568         } catch (final ExecutionException e) {
569             LOG.debug("Execution RpcError: ", e);
570             Throwable cause = e.getCause();
571             if (cause != null) {
572                 while (cause.getCause() != null) {
573                     cause = cause.getCause();
574                 }
575
576                 if (cause instanceof IllegalArgumentException) {
577                     throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
578                             ErrorTag.INVALID_VALUE);
579                 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
580                     throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
581                             ErrorTag.OPERATION_NOT_SUPPORTED);
582                 }
583                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
584                         cause);
585             } else {
586                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
587                         e);
588             }
589         } catch (final CancellationException e) {
590             final String errMsg = "The operation was cancelled while executing.";
591             LOG.debug("Cancel RpcExecution: " + errMsg, e);
592             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
593         }
594     }
595
596     private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
597         if (inputSchema != null && payload.getData() == null) {
598             // expected a non null payload
599             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
600         } else if (inputSchema == null && payload.getData() != null) {
601             // did not expect any input
602             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
603         }
604     }
605
606     private CheckedFuture<DOMRpcResult, DOMRpcException>
607             invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
608         final ContainerNode value = (ContainerNode) payload.getData();
609         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
610         final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
611             new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
612                 "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, controllerContext);
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 ("report-all-tagged".equals(withDefa)) {
706                 tagged = true;
707                 withDefa = null;
708             }
709             if ("report-all".equals(withDefa)) {
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 (final 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     @VisibleForTesting
898     public 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 (!Objects.deepEquals(uriKeyValue, 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         if (uriInfo != null) {
940             for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
941                 switch (entry.getKey()) {
942                     case "insert":
943                         if (!insertUsed) {
944                             insertUsed = true;
945                             insert = entry.getValue().iterator().next();
946                         } else {
947                             throw new RestconfDocumentedException("Insert parameter can be used only once.");
948                         }
949                         break;
950                     case "point":
951                         if (!pointUsed) {
952                             pointUsed = true;
953                             point = entry.getValue().iterator().next();
954                         } else {
955                             throw new RestconfDocumentedException("Point parameter can be used only once.");
956                         }
957                         break;
958                     default:
959                         throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
960                 }
961             }
962         }
963
964         if (pointUsed && !insertUsed) {
965             throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
966         }
967         if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
968             throw new RestconfDocumentedException(
969                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
970         }
971
972         CheckedFuture<Void, TransactionCommitFailedException> future;
973         if (mountPoint != null) {
974             future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
975                     point);
976         } else {
977             future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
978                     payload.getData(), insert, point);
979         }
980
981         try {
982             future.checkedGet();
983         } catch (final RestconfDocumentedException e) {
984             throw e;
985         } catch (final TransactionCommitFailedException e) {
986             LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
987             throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
988         }
989
990         LOG.trace("Successfuly created data.");
991
992         final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
993         // FIXME: Provide path to result.
994         final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
995         if (location != null) {
996             responseBuilder.location(location);
997         }
998         return responseBuilder.build();
999     }
1000
1001     @SuppressWarnings("checkstyle:IllegalCatch")
1002     private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1003             final YangInstanceIdentifier normalizedII) {
1004         if (uriInfo == null) {
1005             // This is null if invoked internally
1006             return null;
1007         }
1008
1009         final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1010         uriBuilder.path("config");
1011         try {
1012             uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1013         } catch (final Exception e) {
1014             LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1015             return null;
1016         }
1017         return uriBuilder.build();
1018     }
1019
1020     @Override
1021     public Response deleteConfigurationData(final String identifier) {
1022         final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1023         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1024         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1025
1026         final CheckedFuture<Void, TransactionCommitFailedException> future;
1027         if (mountPoint != null) {
1028             future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1029         } else {
1030             future = this.broker.commitConfigurationDataDelete(normalizedII);
1031         }
1032
1033         try {
1034             future.checkedGet();
1035         } catch (final TransactionCommitFailedException e) {
1036             final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1037                     Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1038             if (searchedException.isPresent()) {
1039                 throw new RestconfDocumentedException("Data specified for delete doesn't exist.",
1040                         ErrorType.APPLICATION, ErrorTag.DATA_MISSING, e);
1041             }
1042
1043             final String errMsg = "Error while deleting data";
1044             LOG.info(errMsg, e);
1045             throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1046         }
1047
1048         return Response.status(Status.OK).build();
1049     }
1050
1051     /**
1052      * Subscribes to some path in schema context (stream) to listen on changes
1053      * on this stream.
1054      *
1055      * <p>
1056      * Additional parameters for subscribing to stream are loaded via rpc input
1057      * parameters:
1058      * <ul>
1059      * <li>datastore - default CONFIGURATION (other values of
1060      * {@link LogicalDatastoreType} enum type)</li>
1061      * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1062      * </ul>
1063      */
1064     @Override
1065     public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1066         boolean startTimeUsed = false;
1067         boolean stopTimeUsed = false;
1068         Instant start = Instant.now();
1069         Instant stop = null;
1070         boolean filterUsed = false;
1071         String filter = null;
1072         boolean leafNodesOnlyUsed = false;
1073         boolean leafNodesOnly = false;
1074
1075         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1076             switch (entry.getKey()) {
1077                 case "start-time":
1078                     if (!startTimeUsed) {
1079                         startTimeUsed = true;
1080                         start = parseDateFromQueryParam(entry);
1081                     } else {
1082                         throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1083                     }
1084                     break;
1085                 case "stop-time":
1086                     if (!stopTimeUsed) {
1087                         stopTimeUsed = true;
1088                         stop = parseDateFromQueryParam(entry);
1089                     } else {
1090                         throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1091                     }
1092                     break;
1093                 case "filter":
1094                     if (!filterUsed) {
1095                         filterUsed = true;
1096                         filter = entry.getValue().iterator().next();
1097                     } else {
1098                         throw new RestconfDocumentedException("Filter parameter can be used only once.");
1099                     }
1100                     break;
1101                 case "odl-leaf-nodes-only":
1102                     if (!leafNodesOnlyUsed) {
1103                         leafNodesOnlyUsed = true;
1104                         leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1105                     } else {
1106                         throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1107                     }
1108                     break;
1109                 default:
1110                     throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1111             }
1112         }
1113         if (!startTimeUsed && stopTimeUsed) {
1114             throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1115         }
1116         URI response = null;
1117         if (identifier.contains(DATA_SUBSCR)) {
1118             response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1119         } else if (identifier.contains(NOTIFICATION_STREAM)) {
1120             response = notifStream(identifier, uriInfo, start, stop, filter);
1121         }
1122
1123         if (response != null) {
1124             // prepare node with value of location
1125             final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1126             final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1127                     ImmutableLeafNodeBuilder.create().withValue(response.toString());
1128             builder.withNodeIdentifier(
1129                     NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1130
1131             // prepare new header with location
1132             final Map<String, Object> headers = new HashMap<>();
1133             headers.put("Location", response);
1134
1135             return new NormalizedNodeContext(iid, builder.build(), headers);
1136         }
1137
1138         final String msg = "Bad type of notification of sal-remote";
1139         LOG.warn(msg);
1140         throw new RestconfDocumentedException(msg);
1141     }
1142
1143     private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1144         final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1145         final String value = event.getValue();
1146         final TemporalAccessor p;
1147         try {
1148             p = FORMATTER.parse(value);
1149         } catch (final DateTimeParseException e) {
1150             throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1151         }
1152         return Instant.from(p);
1153     }
1154
1155     /**
1156      * Prepare instance identifier.
1157      *
1158      * @return {@link InstanceIdentifierContext} of location leaf for
1159      *         notification
1160      */
1161     private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1162         final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1163         final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1164         final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1165                 .findModule(qnameBase.getModule()).orElse(null)
1166                 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1167         final List<PathArgument> path = new ArrayList<>();
1168         path.add(NodeIdentifier.create(qnameBase));
1169         path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1170
1171         return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1172                 schemaCtx);
1173     }
1174
1175     /**
1176      * Register notification listener by stream name.
1177      *
1178      * @param identifier
1179      *            stream name
1180      * @param uriInfo
1181      *            uriInfo
1182      * @param stop
1183      *            stop-time of getting notification
1184      * @param start
1185      *            start-time of getting notification
1186      * @param filter
1187      *            indicate which subset of all possible events are of interest
1188      * @return {@link URI} of location
1189      */
1190     private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1191             final Instant stop, final String filter) {
1192         final String streamName = Notificator.createStreamNameFromUri(identifier);
1193         if (Strings.isNullOrEmpty(streamName)) {
1194             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1195         }
1196         final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1197         if (listeners == null || listeners.isEmpty()) {
1198             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1199                     ErrorTag.UNKNOWN_ELEMENT);
1200         }
1201
1202         for (final NotificationListenerAdapter listener : listeners) {
1203             this.broker.registerToListenNotification(listener);
1204             listener.setQueryParams(start,
1205                     java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1206         }
1207
1208         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1209
1210         final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1211         final int notificationPort = webSocketServerInstance.getPort();
1212
1213
1214         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1215
1216         return uriToWebsocketServerBuilder.replacePath(streamName).build();
1217     }
1218
1219     private String getWsScheme(UriInfo uriInfo) {
1220         URI uri = uriInfo.getAbsolutePath();
1221         if (uri == null) {
1222             return "ws";
1223         }
1224         String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1225         return subscriptionScheme.equals("https") ? "wss" : "ws";
1226     }
1227
1228     /**
1229      * Register data change listener by stream name.
1230      *
1231      * @param identifier
1232      *            stream name
1233      * @param uriInfo
1234      *            uri info
1235      * @param stop
1236      *            start-time of getting notification
1237      * @param start
1238      *            stop-time of getting notification
1239      * @param filter
1240      *            indicate which subset of all possible events are of interest
1241      * @return {@link URI} of location
1242      */
1243     private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1244             final String filter, final boolean leafNodesOnly) {
1245         final String streamName = Notificator.createStreamNameFromUri(identifier);
1246         if (Strings.isNullOrEmpty(streamName)) {
1247             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1248         }
1249
1250         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1251         if (listener == null) {
1252             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1253                     ErrorTag.UNKNOWN_ELEMENT);
1254         }
1255         listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1256                 java.util.Optional.ofNullable(filter), leafNodesOnly);
1257
1258         final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1259         final LogicalDatastoreType datastore =
1260                 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1261         if (datastore == null) {
1262             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1263                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1264         }
1265         final DataChangeScope scope =
1266                 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1267         if (scope == null) {
1268             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1269                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1270         }
1271
1272         this.broker.registerToListenDataChanges(datastore, scope, listener);
1273
1274         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1275
1276         final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1277         final int notificationPort = webSocketServerInstance.getPort();
1278
1279         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1280
1281         return uriToWebsocketServerBuilder.replacePath(streamName).build();
1282     }
1283
1284     @SuppressWarnings("checkstyle:IllegalCatch")
1285     @Override
1286     public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1287                                                      final UriInfo uriInfo) {
1288         if (context == null) {
1289             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1290         }
1291
1292         try {
1293             return this.broker.patchConfigurationDataWithinTransaction(context);
1294         } catch (final Exception e) {
1295             LOG.debug("Patch transaction failed", e);
1296             throw new RestconfDocumentedException(e.getMessage(), e);
1297         }
1298     }
1299
1300     @SuppressWarnings("checkstyle:IllegalCatch")
1301     @Override
1302     public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1303         if (context == null) {
1304             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1305         }
1306
1307         try {
1308             return this.broker.patchConfigurationDataWithinTransaction(context);
1309         } catch (final Exception e) {
1310             LOG.debug("Patch transaction failed", e);
1311             throw new RestconfDocumentedException(e.getMessage(), e);
1312         }
1313     }
1314
1315     /**
1316      * Load parameter for subscribing to stream from input composite node.
1317      *
1318      * @param value
1319      *            contains value
1320      * @return enum object if its string value is equal to {@code paramName}. In
1321      *         other cases null.
1322      */
1323     private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1324             final String paramName) {
1325         final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1326             SAL_REMOTE_AUG_IDENTIFIER);
1327         if (!optAugNode.isPresent()) {
1328             return null;
1329         }
1330         final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1331         if (!(augNode instanceof AugmentationNode)) {
1332             return null;
1333         }
1334         final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode)
1335             .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1336         if (!enumNode.isPresent()) {
1337             return null;
1338         }
1339         final Object rawValue = enumNode.get().getValue();
1340         if (!(rawValue instanceof String)) {
1341             return null;
1342         }
1343
1344         return resolveAsEnum(classDescriptor, (String) rawValue);
1345     }
1346
1347     /**
1348      * Checks whether {@code value} is one of the string representation of
1349      * enumeration {@code classDescriptor}.
1350      *
1351      * @return enum object if string value of {@code classDescriptor}
1352      *         enumeration is equal to {@code value}. Other cases null.
1353      */
1354     private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1355         if (Strings.isNullOrEmpty(value)) {
1356             return null;
1357         }
1358         return resolveAsEnum(classDescriptor, value);
1359     }
1360
1361     private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1362         final T[] enumConstants = classDescriptor.getEnumConstants();
1363         if (enumConstants != null) {
1364             for (final T enm : classDescriptor.getEnumConstants()) {
1365                 if (((Enum<?>) enm).name().equals(value)) {
1366                     return enm;
1367                 }
1368             }
1369         }
1370         return null;
1371     }
1372
1373     private static Map<String, String> resolveValuesFromUri(final String uri) {
1374         final Map<String, String> result = new HashMap<>();
1375         final String[] tokens = uri.split("/");
1376         for (int i = 1; i < tokens.length; i++) {
1377             final String[] parameterTokens = tokens[i].split("=");
1378             if (parameterTokens.length == 2) {
1379                 result.put(parameterTokens[0], parameterTokens[1]);
1380             }
1381         }
1382         return result;
1383     }
1384
1385     private MapNode makeModuleMapNode(final Set<Module> modules) {
1386         Preconditions.checkNotNull(modules);
1387         final Module restconfModule = getRestconfModule();
1388         final DataSchemaNode moduleSchemaNode = this.controllerContext
1389                 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1390         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1391
1392         final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1393                 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1394
1395         for (final Module module : modules) {
1396             listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1397         }
1398         return listModuleBuilder.build();
1399     }
1400
1401     protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1402         Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1403                 "moduleSchemaNode has to be of type ListSchemaNode");
1404         final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1405         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1406                 Builders.mapEntryBuilder(listModuleSchemaNode);
1407
1408         List<DataSchemaNode> instanceDataChildrenByName =
1409                 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1410         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1411         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1412         moduleNodeValues
1413                 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1414
1415         instanceDataChildrenByName =
1416                 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1417         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1418         Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1419         final java.util.Optional<Revision> revision = module.getQNameModule().getRevision();
1420         if (revision.isPresent()) {
1421             moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1422                 .withValue(revision.get().toString()).build());
1423         }
1424
1425         instanceDataChildrenByName =
1426                 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1427         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1428         Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1429         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1430                 .withValue(module.getNamespace().toString()).build());
1431
1432         instanceDataChildrenByName =
1433                 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1434         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1435         Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1436         final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1437                 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1438         for (final FeatureDefinition feature : module.getFeatures()) {
1439             featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1440                     .withValue(feature.getQName().getLocalName()).build());
1441         }
1442         moduleNodeValues.withChild(featuresBuilder.build());
1443
1444         return moduleNodeValues.build();
1445     }
1446
1447     protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1448         Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1449                 "streamSchemaNode has to be of type ListSchemaNode");
1450         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1451         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1452                 Builders.mapEntryBuilder(listStreamSchemaNode);
1453
1454         List<DataSchemaNode> instanceDataChildrenByName =
1455                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1456         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1457         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1458         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1459
1460         instanceDataChildrenByName =
1461                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1462         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1463         Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1464         streamNodeValues.withChild(
1465                 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1466
1467         instanceDataChildrenByName =
1468                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1469         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1470         Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1471         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1472                 .withValue(Boolean.valueOf(true)).build());
1473
1474         instanceDataChildrenByName =
1475                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1476         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1477         Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1478         streamNodeValues.withChild(
1479                 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1480
1481         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1482         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1483         Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1484         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1485
1486         return streamNodeValues.build();
1487     }
1488
1489     /**
1490      * Prepare stream for notification.
1491      *
1492      * @param payload
1493      *            contains list of qnames of notifications
1494      * @return - checked future object
1495      */
1496     private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1497             final NormalizedNodeContext payload) {
1498         final ContainerNode data = (ContainerNode) payload.getData();
1499         LeafSetNode leafSet = null;
1500         String outputType = "XML";
1501         for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1502             if (dataChild instanceof LeafSetNode) {
1503                 leafSet = (LeafSetNode) dataChild;
1504             } else if (dataChild instanceof AugmentationNode) {
1505                 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1506             }
1507         }
1508
1509         final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1510         final List<SchemaPath> paths = new ArrayList<>();
1511         String streamName = CREATE_NOTIFICATION_STREAM + "/";
1512
1513         StringBuilder streamNameBuilder = new StringBuilder(streamName);
1514         final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1515         while (iterator.hasNext()) {
1516             final QName valueQName = QName.create((String) iterator.next().getValue());
1517             final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1518             Preconditions.checkNotNull(module,
1519                     "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1520             NotificationDefinition notifiDef = null;
1521             for (final NotificationDefinition notification : module.getNotifications()) {
1522                 if (notification.getQName().equals(valueQName)) {
1523                     notifiDef = notification;
1524                     break;
1525                 }
1526             }
1527             final String moduleName = module.getName();
1528             Preconditions.checkNotNull(notifiDef,
1529                     "Notification " + valueQName + "doesn't exist in module " + moduleName);
1530             paths.add(notifiDef.getPath());
1531             streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1532             if (iterator.hasNext()) {
1533                 streamNameBuilder.append(',');
1534             }
1535         }
1536
1537         streamName = streamNameBuilder.toString();
1538
1539         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1540         final QName outputQname = QName.create(rpcQName, "output");
1541         final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1542
1543         final ContainerNode output =
1544                 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1545                         .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1546
1547         if (!Notificator.existNotificationListenerFor(streamName)) {
1548             Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1549         }
1550
1551         final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1552
1553         return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1554     }
1555 }