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