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