928abe0eaf61c13431975d96de2a9bbea6d68073
[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.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Lists;
19 import com.google.common.collect.Maps;
20 import com.google.common.collect.Sets;
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.Futures;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.text.DateFormat;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Set;
39 import java.util.concurrent.CancellationException;
40 import java.util.concurrent.CountDownLatch;
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.impl.schema.Builders;
85 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
86 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
87 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
88 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
89 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
90 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
91 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
92 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
94 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
96 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.Module;
100 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
101 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
102 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
103 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
105 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
106 import org.slf4j.Logger;
107 import org.slf4j.LoggerFactory;
108
109 public class RestconfImpl implements RestconfService {
110
111     private static final RestconfImpl INSTANCE = new RestconfImpl();
112
113     /**
114      * Notifications are served on port 8181.
115      */
116     private static final int NOTIFICATION_PORT = 8181;
117
118     private static final int CHAR_NOT_FOUND = -1;
119
120     private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
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 = new SimpleDateFormat("yyyy-MM-dd").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 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 = REVISION_FORMAT.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<RpcDefinition>(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() != null) {
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 insert_used = false;
749         boolean point_used = 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 (!insert_used) {
757                         insert_used = 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 (!point_used) {
765                         point_used = 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 (point_used && !insert_used) {
777             throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
778         }
779         if (point_used && (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         final TryOfPutData tryPutData = new TryOfPutData();
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             final CountDownLatch waiter = new CountDownLatch(1);
823             Futures.addCallback(result.getFutureOfPutData(), new FutureCallback<Void>() {
824
825                 @Override
826                 public void onSuccess(final Void result) {
827                     handlingLoggerPut(null, tryPutData, identifier);
828                     waiter.countDown();
829                 }
830
831                 @Override
832                 public void onFailure(final Throwable t) {
833                     waiter.countDown();
834                     handlingLoggerPut(t, tryPutData, identifier);
835                 }
836             });
837
838             try {
839                 waiter.await();
840             } catch (final Exception e) {
841                 final String msg = "Problem while waiting for response";
842                 LOG.warn(msg);
843                 throw new RestconfDocumentedException(msg, e);
844             }
845
846             if (tryPutData.isDone()) {
847                 break;
848             } else {
849                 throw new RestconfDocumentedException("Problem while PUT operations");
850             }
851         }
852
853         return Response.status(result.getStatus()).build();
854     }
855
856     protected void handlingLoggerPut(final Throwable t, final TryOfPutData tryPutData, final String identifier) {
857         if (t != null) {
858             if (t instanceof OptimisticLockFailedException) {
859                 if (tryPutData.countGet() <= 0) {
860                     LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
861                     throw new RestconfDocumentedException(t.getMessage(), t);
862                 }
863                 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
864                 tryPutData.countDown();
865             } else {
866                 LOG.debug("Update ConfigDataStore fail " + identifier, t);
867                 throw new RestconfDocumentedException(t.getMessage(), t);
868             }
869         } else {
870             LOG.trace("PUT Successful " + identifier);
871             tryPutData.done();
872         }
873     }
874
875     private static void validateTopLevelNodeName(final NormalizedNodeContext node,
876             final YangInstanceIdentifier identifier) {
877
878         final String payloadName = node.getData().getNodeType().getLocalName();
879
880         // no arguments
881         if (identifier.isEmpty()) {
882             // no "data" payload
883             if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
884                 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
885                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
886             }
887             // any arguments
888         } else {
889             final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
890             if (!payloadName.equals(identifierName)) {
891                 throw new RestconfDocumentedException(
892                         "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
893                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
894             }
895         }
896     }
897
898     /**
899      * Validates whether keys in {@code payload} are equal to values of keys in
900      * {@code iiWithData} for list schema node
901      *
902      * @throws RestconfDocumentedException
903      *             if key values or key count in payload and URI isn't equal
904      *
905      */
906     private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
907         Preconditions.checkArgument(payload != null);
908         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
909         final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
910         final SchemaNode schemaNode = iiWithData.getSchemaNode();
911         final NormalizedNode<?, ?> data = payload.getData();
912         if (schemaNode instanceof ListSchemaNode) {
913             final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
914             if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
915                 final Map<QName, Object> uriKeyValues =
916                         ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
917                 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
918             }
919         }
920     }
921
922     private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
923             final List<QName> keyDefinitions) {
924
925         final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
926         for (final QName keyDefinition : keyDefinitions) {
927             final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
928             // should be caught during parsing URI to InstanceIdentifier
929             RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
930                     "Missing key " + keyDefinition + " in URI.");
931
932             final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
933
934             if (!uriKeyValue.equals(dataKeyValue)) {
935                 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
936                         + "' specified in the URI doesn't match the value '" + dataKeyValue
937                         + "' specified in the message body. ";
938                 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
939             }
940         }
941     }
942
943     @Override
944     public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
945             final UriInfo uriInfo) {
946         return createConfigurationData(payload, uriInfo);
947     }
948
949     // FIXME create RestconfIdetifierHelper and move this method there
950     private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
951         Preconditions.checkArgument(payload != null);
952         Preconditions.checkArgument(payload.getData() != null);
953         Preconditions.checkArgument(payload.getData().getNodeType() != null);
954         Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
955         Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
956
957         final QName payloadNodeQname = payload.getData().getNodeType();
958         final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
959         if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
960             return yangIdent;
961         }
962         final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
963         final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
964         if (parentSchemaNode instanceof DataNodeContainer) {
965             final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
966             for (final DataSchemaNode child : cast.getChildNodes()) {
967                 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
968                     return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
969                 }
970             }
971         }
972         if (parentSchemaNode instanceof RpcDefinition) {
973             return yangIdent;
974         }
975         final String errMsg = "Error parsing input: DataSchemaNode has not children ";
976         LOG.info(errMsg + yangIdent);
977         throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
978     }
979
980     @Override
981     public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
982         if (payload == null) {
983             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
984         }
985         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
986         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
987         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
988
989         boolean insert_used = false;
990         boolean point_used = false;
991         String insert = null;
992         String point = null;
993
994         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
995             switch (entry.getKey()) {
996                 case "insert":
997                     if (!insert_used) {
998                         insert_used = true;
999                         insert = entry.getValue().iterator().next();
1000                     } else {
1001                         throw new RestconfDocumentedException("Insert parameter can be used only once.");
1002                     }
1003                     break;
1004                 case "point":
1005                     if (!point_used) {
1006                         point_used = true;
1007                         point = entry.getValue().iterator().next();
1008                     } else {
1009                         throw new RestconfDocumentedException("Point parameter can be used only once.");
1010                     }
1011                     break;
1012                 default:
1013                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
1014             }
1015         }
1016
1017         if (point_used && !insert_used) {
1018             throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
1019         }
1020         if (point_used && (insert.equals("first") || insert.equals("last"))) {
1021             throw new RestconfDocumentedException(
1022                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
1023         }
1024
1025         CheckedFuture<Void, TransactionCommitFailedException> future;
1026         if (mountPoint != null) {
1027             future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
1028                     point);
1029         } else {
1030             future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
1031                     payload.getData(), insert, point);
1032         }
1033
1034         final CountDownLatch waiter = new CountDownLatch(1);
1035         Futures.addCallback(future, new FutureCallback<Void>() {
1036
1037             @Override
1038             public void onSuccess(final Void result) {
1039                 handlerLoggerPost(null, uriInfo);
1040                 waiter.countDown();
1041             }
1042
1043             @Override
1044             public void onFailure(final Throwable t) {
1045                 waiter.countDown();
1046                 handlerLoggerPost(t, uriInfo);
1047             }
1048         });
1049
1050         try {
1051             waiter.await();
1052         } catch (final Exception e) {
1053             final String msg = "Problem while waiting for response";
1054             LOG.warn(msg);
1055             throw new RestconfDocumentedException(msg, e);
1056         }
1057
1058         final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1059         // FIXME: Provide path to result.
1060         final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1061         if (location != null) {
1062             responseBuilder.location(location);
1063         }
1064         return responseBuilder.build();
1065     }
1066
1067     protected void handlerLoggerPost(final Throwable t, final UriInfo uriInfo) {
1068         if (t != null) {
1069             final String errMsg = "Error creating data ";
1070             LOG.warn(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), t);
1071             throw new RestconfDocumentedException(errMsg, t);
1072         } else {
1073             LOG.trace("Successfuly create data.");
1074         }
1075     }
1076
1077     private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1078             final YangInstanceIdentifier normalizedII) {
1079         if (uriInfo == null) {
1080             // This is null if invoked internally
1081             return null;
1082         }
1083
1084         final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1085         uriBuilder.path("config");
1086         try {
1087             uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1088         } catch (final Exception e) {
1089             LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1090             return null;
1091         }
1092         return uriBuilder.build();
1093     }
1094
1095     @Override
1096     public Response deleteConfigurationData(final String identifier) {
1097         final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1098         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1099         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1100
1101         final CheckedFuture<Void, TransactionCommitFailedException> future;
1102         if (mountPoint != null) {
1103             future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1104         } else {
1105             future = this.broker.commitConfigurationDataDelete(normalizedII);
1106         }
1107
1108         final CountDownLatch waiter = new CountDownLatch(1);
1109         final ResultOperation result = new ResultOperation();
1110         Futures.addCallback(future, new FutureCallback<Void>() {
1111
1112             @Override
1113             public void onSuccess(final Void result) {
1114                 LOG.trace("Successfuly delete data.");
1115                 waiter.countDown();
1116             }
1117
1118             @Override
1119             public void onFailure(final Throwable t) {
1120                 waiter.countDown();
1121                 result.setFailed(t);
1122             }
1123
1124         });
1125
1126         try {
1127             waiter.await();
1128         } catch (final Exception e) {
1129             final String msg = "Problem while waiting for response";
1130             LOG.warn(msg);
1131             throw new RestconfDocumentedException(msg, e);
1132         }
1133         if (result.failed() != null) {
1134             final Throwable t = result.failed();
1135             final String errMsg = "Error while deleting data";
1136             LOG.info(errMsg, t);
1137             throw new RestconfDocumentedException(errMsg, RestconfError.ErrorType.APPLICATION,
1138                     RestconfError.ErrorTag.OPERATION_FAILED, t);
1139         }
1140         return Response.status(Status.OK).build();
1141     }
1142
1143     private class ResultOperation {
1144         private Throwable t = null;
1145
1146         public void setFailed(final Throwable t) {
1147             this.t = t;
1148         }
1149
1150         public Throwable failed() {
1151             return this.t;
1152         }
1153     }
1154
1155     /**
1156      * Subscribes to some path in schema context (stream) to listen on changes
1157      * on this stream.
1158      *
1159      * Additional parameters for subscribing to stream are loaded via rpc input
1160      * parameters:
1161      * <ul>
1162      * <li>datastore - default CONFIGURATION (other values of
1163      * {@link LogicalDatastoreType} enum type)</li>
1164      * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1165      * </ul>
1166      */
1167     @Override
1168     public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1169         boolean startTime_used = false;
1170         boolean stopTime_used = false;
1171         boolean filter_used = false;
1172         Date start = null;
1173         Date stop = null;
1174         String filter = null;
1175
1176         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1177             switch (entry.getKey()) {
1178                 case "start-time":
1179                     if (!startTime_used) {
1180                         startTime_used = true;
1181                         start = parseDateFromQueryParam(entry);
1182                     } else {
1183                         throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1184                     }
1185                     break;
1186                 case "stop-time":
1187                     if (!stopTime_used) {
1188                         stopTime_used = true;
1189                         stop = parseDateFromQueryParam(entry);
1190                     } else {
1191                         throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1192                     }
1193                     break;
1194                 case "filter":
1195                     if (!filter_used) {
1196                         filter_used = true;
1197                         filter = entry.getValue().iterator().next();
1198                     } else {
1199                         throw new RestconfDocumentedException("Filter parameter can be used only once.");
1200                     }
1201                     break;
1202                 default:
1203                     throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1204             }
1205         }
1206         if (!startTime_used && stopTime_used) {
1207             throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1208         }
1209         URI response = null;
1210         if (identifier.contains(DATA_SUBSCR)) {
1211             response = dataSubs(identifier, uriInfo, start, stop, filter);
1212         } else if (identifier.contains(NOTIFICATION_STREAM)) {
1213             response = notifStream(identifier, uriInfo, start, stop, filter);
1214         }
1215
1216         if (response != null) {
1217             // prepare node with value of location
1218             final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1219             final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1220                     ImmutableLeafNodeBuilder.create().withValue(response.toString());
1221             builder.withNodeIdentifier(
1222                     NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1223
1224             // prepare new header with location
1225             final Map<String, Object> headers = new HashMap<>();
1226             headers.put("Location", response);
1227
1228             return new NormalizedNodeContext(iid, builder.build(), headers);
1229         }
1230
1231         final String msg = "Bad type of notification of sal-remote";
1232         LOG.warn(msg);
1233         throw new RestconfDocumentedException(msg);
1234     }
1235
1236     private Date parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1237         final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1238         String numOf_ms = "";
1239         final String value = event.getValue();
1240         if (value.contains(".")) {
1241             numOf_ms = numOf_ms + ".";
1242             final int lastChar = value.contains("Z") ? value.indexOf("Z") : (value.contains("+") ? value.indexOf("+")
1243                     : (value.contains("-") ? value.indexOf("-") : value.length()));
1244             for (int i = 0; i < (lastChar - value.indexOf(".") - 1); i++) {
1245                 numOf_ms = numOf_ms + "S";
1246             }
1247         }
1248         String zone = "";
1249         if (!value.contains("Z")) {
1250             zone = zone + "XXX";
1251         }
1252         final DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" + numOf_ms + zone);
1253
1254         try {
1255             return dateFormatter.parse(value.contains("Z") ? value.replace('T', ' ').substring(0, value.indexOf("Z"))
1256                     : value.replace('T', ' '));
1257         } catch (final ParseException e) {
1258             throw new RestconfDocumentedException("Cannot parse of value in date: " + value + e);
1259         }
1260     }
1261
1262     /**
1263      * @return {@link InstanceIdentifierContext} of location leaf for
1264      *         notification
1265      */
1266     private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1267         final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1268         final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1269         final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1270                 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1271                 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1272         final List<PathArgument> path = new ArrayList<>();
1273         path.add(NodeIdentifier.create(qnameBase));
1274         path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1275
1276         return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1277                 schemaCtx);
1278     }
1279
1280     /**
1281      * Register notification listener by stream name
1282      *
1283      * @param identifier
1284      *            - stream name
1285      * @param uriInfo
1286      *            - uriInfo
1287      * @param stop
1288      *            - stop-time of getting notification
1289      * @param start
1290      *            - start-time of getting notification
1291      * @param filter
1292      *            - indicate wh ich subset of allpossible events are of interest
1293      * @return {@link URI} of location
1294      */
1295     private URI notifStream(final String identifier, final UriInfo uriInfo, final Date start, final Date stop,
1296             final String filter) {
1297         final String streamName = Notificator.createStreamNameFromUri(identifier);
1298         if (Strings.isNullOrEmpty(streamName)) {
1299             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1300         }
1301         final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1302         if ((listeners == null) || listeners.isEmpty()) {
1303             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1304                     ErrorTag.UNKNOWN_ELEMENT);
1305         }
1306
1307         for (final NotificationListenerAdapter listener : listeners) {
1308             this.broker.registerToListenNotification(listener);
1309             listener.setQueryParams(start, stop, filter);
1310         }
1311
1312         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1313         int notificationPort = NOTIFICATION_PORT;
1314         try {
1315             final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1316             notificationPort = webSocketServerInstance.getPort();
1317         } catch (final NullPointerException e) {
1318             WebSocketServer.createInstance(NOTIFICATION_PORT);
1319         }
1320         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1321         final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1322
1323         return uriToWebsocketServer;
1324     }
1325
1326     /**
1327      * Register data change listener by stream name
1328      *
1329      * @param identifier
1330      *            - stream name
1331      * @param uriInfo
1332      *            - uri info
1333      * @param stop
1334      *            - start-time of getting notification
1335      * @param start
1336      *            - stop-time of getting notification
1337      * @param filter
1338      *            - indicate which subset of all possible events are of interest
1339      * @return {@link URI} of location
1340      */
1341     private URI dataSubs(final String identifier, final UriInfo uriInfo, final Date start, final Date stop,
1342             final String filter) {
1343         final String streamName = Notificator.createStreamNameFromUri(identifier);
1344         if (Strings.isNullOrEmpty(streamName)) {
1345             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1346         }
1347
1348         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1349         if (listener == null) {
1350             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1351                     ErrorTag.UNKNOWN_ELEMENT);
1352         }
1353         listener.setQueryParams(start, stop, filter);
1354
1355         final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1356         final LogicalDatastoreType datastore =
1357                 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1358         if (datastore == null) {
1359             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1360                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1361         }
1362         final DataChangeScope scope =
1363                 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1364         if (scope == null) {
1365             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1366                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1367         }
1368
1369         this.broker.registerToListenDataChanges(datastore, scope, listener);
1370
1371         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1372         int notificationPort = NOTIFICATION_PORT;
1373         try {
1374             final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1375             notificationPort = webSocketServerInstance.getPort();
1376         } catch (final NullPointerException e) {
1377             WebSocketServer.createInstance(NOTIFICATION_PORT);
1378         }
1379         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1380         final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1381
1382         return uriToWebsocketServer;
1383     }
1384
1385     @Override
1386     public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
1387             final UriInfo uriInfo) {
1388         if (context == null) {
1389             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1390         }
1391
1392         try {
1393             return this.broker.patchConfigurationDataWithinTransaction(context);
1394         } catch (final Exception e) {
1395             LOG.debug("Patch transaction failed", e);
1396             throw new RestconfDocumentedException(e.getMessage());
1397         }
1398     }
1399
1400     @Override
1401     public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1402         if (context == null) {
1403             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1404         }
1405
1406         try {
1407             return this.broker.patchConfigurationDataWithinTransaction(context);
1408         } catch (final Exception e) {
1409             LOG.debug("Patch transaction failed", e);
1410             throw new RestconfDocumentedException(e.getMessage());
1411         }
1412     }
1413
1414     /**
1415      * Load parameter for subscribing to stream from input composite node
1416      *
1417      * @param value
1418      *            contains value
1419      * @return enum object if its string value is equal to {@code paramName}. In
1420      *         other cases null.
1421      */
1422     private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1423             final String paramName) {
1424         final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1425                 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1426         if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1427             return null;
1428         }
1429         final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1430                 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1431         if (!enumNode.isPresent()) {
1432             return null;
1433         }
1434         final Object rawValue = enumNode.get().getValue();
1435         if (!(rawValue instanceof String)) {
1436             return null;
1437         }
1438
1439         return resolveAsEnum(classDescriptor, (String) rawValue);
1440     }
1441
1442     /**
1443      * Checks whether {@code value} is one of the string representation of
1444      * enumeration {@code classDescriptor}
1445      *
1446      * @return enum object if string value of {@code classDescriptor}
1447      *         enumeration is equal to {@code value}. Other cases null.
1448      */
1449     private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1450         if (Strings.isNullOrEmpty(value)) {
1451             return null;
1452         }
1453         return resolveAsEnum(classDescriptor, value);
1454     }
1455
1456     private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1457         final T[] enumConstants = classDescriptor.getEnumConstants();
1458         if (enumConstants != null) {
1459             for (final T enm : classDescriptor.getEnumConstants()) {
1460                 if (((Enum<?>) enm).name().equals(value)) {
1461                     return enm;
1462                 }
1463             }
1464         }
1465         return null;
1466     }
1467
1468     private static Map<String, String> resolveValuesFromUri(final String uri) {
1469         final Map<String, String> result = new HashMap<>();
1470         final String[] tokens = uri.split("/");
1471         for (int i = 1; i < tokens.length; i++) {
1472             final String[] parameterTokens = tokens[i].split("=");
1473             if (parameterTokens.length == 2) {
1474                 result.put(parameterTokens[0], parameterTokens[1]);
1475             }
1476         }
1477         return result;
1478     }
1479
1480     private MapNode makeModuleMapNode(final Set<Module> modules) {
1481         Preconditions.checkNotNull(modules);
1482         final Module restconfModule = getRestconfModule();
1483         final DataSchemaNode moduleSchemaNode = this.controllerContext
1484                 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1485         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1486
1487         final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1488                 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1489
1490         for (final Module module : modules) {
1491             listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1492         }
1493         return listModuleBuilder.build();
1494     }
1495
1496     protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1497         Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1498                 "moduleSchemaNode has to be of type ListSchemaNode");
1499         final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1500         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1501                 Builders.mapEntryBuilder(listModuleSchemaNode);
1502
1503         List<DataSchemaNode> instanceDataChildrenByName =
1504                 ControllerContext.findInstanceDataChildrenByName((listModuleSchemaNode), "name");
1505         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1506         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1507         moduleNodeValues
1508                 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1509
1510         instanceDataChildrenByName =
1511                 ControllerContext.findInstanceDataChildrenByName((listModuleSchemaNode), "revision");
1512         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1513         Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1514         final String revision = REVISION_FORMAT.format(module.getRevision());
1515         moduleNodeValues
1516                 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1517
1518         instanceDataChildrenByName =
1519                 ControllerContext.findInstanceDataChildrenByName((listModuleSchemaNode), "namespace");
1520         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1521         Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1522         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1523                 .withValue(module.getNamespace().toString()).build());
1524
1525         instanceDataChildrenByName =
1526                 ControllerContext.findInstanceDataChildrenByName((listModuleSchemaNode), "feature");
1527         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1528         Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1529         final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1530                 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1531         for (final FeatureDefinition feature : module.getFeatures()) {
1532             featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1533                     .withValue(feature.getQName().getLocalName()).build());
1534         }
1535         moduleNodeValues.withChild(featuresBuilder.build());
1536
1537         return moduleNodeValues.build();
1538     }
1539
1540     protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1541         Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1542                 "streamSchemaNode has to be of type ListSchemaNode");
1543         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1544         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1545                 Builders.mapEntryBuilder(listStreamSchemaNode);
1546
1547         List<DataSchemaNode> instanceDataChildrenByName =
1548                 ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "name");
1549         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1550         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1551         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1552
1553         instanceDataChildrenByName =
1554                 ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "description");
1555         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1556         Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1557         streamNodeValues.withChild(
1558                 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1559
1560         instanceDataChildrenByName =
1561                 ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "replay-support");
1562         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1563         Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1564         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1565                 .withValue(Boolean.valueOf(true)).build());
1566
1567         instanceDataChildrenByName =
1568                 ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "replay-log-creation-time");
1569         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1570         Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1571         streamNodeValues.withChild(
1572                 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1573
1574         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "events");
1575         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1576         Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1577         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1578
1579         return streamNodeValues.build();
1580     }
1581
1582     /**
1583      * Prepare stream for notification
1584      *
1585      * @param payload
1586      *            - contains list of qnames of notifications
1587      * @return - checked future object
1588      */
1589     private CheckedFuture<DOMRpcResult, DOMRpcException>
1590             invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1591         final ContainerNode data = (ContainerNode) payload.getData();
1592         LeafSetNode leafSet = null;
1593         String outputType = "XML";
1594         for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1595             if (dataChild instanceof LeafSetNode) {
1596                 leafSet = (LeafSetNode) dataChild;
1597             } else if (dataChild instanceof AugmentationNode) {
1598                 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1599             }
1600         }
1601
1602         final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1603         final List<SchemaPath> paths = new ArrayList<>();
1604         String streamName = CREATE_NOTIFICATION_STREAM + "/";
1605
1606         final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1607         while (iterator.hasNext()) {
1608             final QName valueQName = QName.create((String) iterator.next().getValue());
1609             final Module module =
1610                     ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1611             Preconditions.checkNotNull(module,
1612                     "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1613             NotificationDefinition notifiDef = null;
1614             for (final NotificationDefinition notification : module.getNotifications()) {
1615                 if (notification.getQName().equals(valueQName)) {
1616                     notifiDef = notification;
1617                     break;
1618                 }
1619             }
1620             final String moduleName = module.getName();
1621             Preconditions.checkNotNull(notifiDef,
1622                     "Notification " + valueQName + "doesn't exist in module " + moduleName);
1623             paths.add(notifiDef.getPath());
1624             streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1625             if (iterator.hasNext()) {
1626                 streamName = streamName + ",";
1627             }
1628         }
1629
1630         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1631         final QName outputQname = QName.create(rpcQName, "output");
1632         final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1633
1634         final ContainerNode output =
1635                 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1636                         .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1637
1638         if (!Notificator.existNotificationListenerFor(streamName)) {
1639             Notificator.createNotificationListener(paths, streamName, outputType);
1640         }
1641
1642         final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1643
1644         return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1645     }
1646
1647     private class TryOfPutData {
1648         int tries = 2;
1649         boolean done = false;
1650
1651         void countDown() {
1652             this.tries--;
1653         }
1654
1655         void done() {
1656             this.done = true;
1657         }
1658
1659         boolean isDone() {
1660             return this.done;
1661         }
1662
1663         int countGet() {
1664             return this.tries;
1665         }
1666     }
1667 }