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