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