Take advantage of YangInstanceIdentifier methods
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / restconf / impl / RestconfImpl.java
1 /**
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 2014 Brocade Communication Systems, Inc.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9 package org.opendaylight.controller.sal.restconf.impl;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicate;
14 import com.google.common.base.Predicates;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.base.Throwables;
18 import com.google.common.collect.Iterables;
19 import com.google.common.collect.Lists;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
24 import java.math.BigInteger;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.Date;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.concurrent.CancellationException;
37 import java.util.concurrent.ExecutionException;
38 import javax.ws.rs.core.Response;
39 import javax.ws.rs.core.Response.ResponseBuilder;
40 import javax.ws.rs.core.Response.Status;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.core.UriInfo;
43 import org.apache.commons.lang3.StringUtils;
44 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
45 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
46 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
47 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
48 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
52 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
53 import org.opendaylight.controller.md.sal.rest.common.RestconfValidationUtils;
54 import org.opendaylight.controller.sal.rest.api.Draft02;
55 import org.opendaylight.controller.sal.rest.api.RestconfService;
56 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
57 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
58 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
59 import org.opendaylight.controller.sal.streams.listeners.Notificator;
60 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.common.QNameModule;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
67 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
70 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
76 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
77 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
78 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
79 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
82 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
84 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
86 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.Module;
90 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
91 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
92 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.util.EmptyType;
95 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
96 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
97 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
98 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
99 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
100 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
103
104 public class RestconfImpl implements RestconfService {
105
106     private enum UriParameters {
107         PRETTY_PRINT("prettyPrint"),
108         DEPTH("depth");
109
110         private String uriParameterName;
111
112         UriParameters(final String uriParameterName) {
113             this.uriParameterName = uriParameterName;
114         }
115
116         @Override
117         public String toString() {
118             return uriParameterName;
119         }
120     }
121
122     private static final RestconfImpl INSTANCE = new RestconfImpl();
123
124     private static final int NOTIFICATION_PORT = 8181;
125
126     private static final int CHAR_NOT_FOUND = -1;
127
128     private static final String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
129
130     private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
131
132     private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
133
134     private static final String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
135
136     private BrokerFacade broker;
137
138     private ControllerContext controllerContext;
139
140     private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
141
142     private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
143
144     private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
145
146     private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
147
148     private static final String DATASTORE_PARAM_NAME = "datastore";
149
150     private static final String SCOPE_PARAM_NAME = "scope";
151
152     private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
153
154     private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
155
156     private static final QName NETCONF_BASE_QNAME;
157
158     private static final QNameModule SAL_REMOTE_AUGMENT;
159
160     private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
161
162     static {
163         try {
164             final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
165             NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
166             SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
167                     eventSubscriptionAugRevision);
168             SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
169                     QName.create(SAL_REMOTE_AUGMENT, "datastore")));
170         } catch (final ParseException e) {
171             throw new RestconfDocumentedException(
172                     "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
173                     ErrorTag.OPERATION_FAILED);
174         } catch (final URISyntaxException e) {
175             throw new RestconfDocumentedException(
176                     "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI", ErrorType.APPLICATION,
177                     ErrorTag.OPERATION_FAILED);
178         }
179     }
180
181     public void setBroker(final BrokerFacade broker) {
182         this.broker = broker;
183     }
184
185     public void setControllerContext(final ControllerContext controllerContext) {
186         this.controllerContext = controllerContext;
187     }
188
189     private RestconfImpl() {
190     }
191
192     public static RestconfImpl getInstance() {
193         return INSTANCE;
194     }
195
196     @Override
197     public NormalizedNodeContext getModules(final UriInfo uriInfo) {
198         final Set<Module> allModules = controllerContext.getAllModules();
199         final MapNode allModuleMap = makeModuleMapNode(allModules);
200
201         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
202
203         final Module restconfModule = getRestconfModule();
204         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
205                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
206         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
207
208         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
209                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
210         moduleContainerBuilder.withChild(allModuleMap);
211
212         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
213                 null, schemaContext), moduleContainerBuilder.build());
214     }
215
216     /**
217      * Valid only for mount point
218      */
219     @Override
220     public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
221         Preconditions.checkNotNull(identifier);
222         if ( ! identifier.contains(ControllerContext.MOUNT)) {
223             final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
224                     + " URI has to end with " + ControllerContext.MOUNT;
225             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
226         }
227
228         final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
229         final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
230         final Set<Module> modules = controllerContext.getAllModules(mountPoint);
231         final MapNode mountPointModulesMap = makeModuleMapNode(modules);
232
233         final Module restconfModule = getRestconfModule();
234         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
235                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
236         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
237
238         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
239                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
240         moduleContainerBuilder.withChild(mountPointModulesMap);
241
242         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
243                 mountPoint, controllerContext.getGlobalSchema()), moduleContainerBuilder.build());
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 = controllerContext.toMountPointIdentifier(identifier);
255             mountPoint = mountPointIdentifier.getMountPoint();
256             module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
257             schemaContext = mountPoint.getSchemaContext();
258         } else {
259             module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
260             schemaContext = controllerContext.getGlobalSchema();
261         }
262
263         if (module == null) {
264             final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
265                     + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
266             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
267         }
268
269         final Module restconfModule = getRestconfModule();
270         final Set<Module> modules = Collections.singleton(module);
271         final MapNode moduleMap = makeModuleMapNode(modules);
272
273         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
274                 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
275         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
276
277         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
278                 schemaContext), moduleMap);
279     }
280
281     @Override
282     public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
283         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
284         final Set<String> availableStreams = Notificator.getStreamNames();
285         final Module restconfModule = getRestconfModule();
286         final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
287                 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
288         Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
289
290         final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
291                 .mapBuilder((ListSchemaNode) streamSchemaNode);
292
293         for (final String streamName : availableStreams) {
294             listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
295         }
296
297         final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
298                 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
299         Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
300
301         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
302                 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
303         streamsContainerBuilder.withChild(listStreamsBuilder.build());
304
305
306         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
307                 schemaContext), streamsContainerBuilder.build());
308     }
309
310     @Override
311     public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
312         final Set<Module> allModules = controllerContext.getAllModules();
313         return operationsFromModulesToNormalizedContext(allModules, null);
314     }
315
316     @Override
317     public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
318         Set<Module> modules = null;
319         DOMMountPoint mountPoint = null;
320         if (identifier.contains(ControllerContext.MOUNT)) {
321             final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
322             mountPoint = mountPointIdentifier.getMountPoint();
323             modules = controllerContext.getAllModules(mountPoint);
324
325         } else {
326             final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
327             throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
328         }
329
330         return operationsFromModulesToNormalizedContext(modules, mountPoint);
331     }
332
333     private static final Predicate<GroupingBuilder> GROUPING_FILTER = new Predicate<GroupingBuilder>() {
334         @Override
335         public boolean apply(final GroupingBuilder g) {
336             return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
337         }
338     };
339
340     private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
341             final DOMMountPoint mountPoint) {
342
343         final Module restconfModule = getRestconfModule();
344         final ModuleBuilder restConfModuleBuilder = new ModuleBuilder(restconfModule);
345         final Set<GroupingBuilder> gropingBuilders = restConfModuleBuilder.getGroupingBuilders();
346         final Iterable<GroupingBuilder> filteredGroups = Iterables.filter(gropingBuilders, GROUPING_FILTER);
347         final GroupingBuilder restconfGroupingBuilder = Iterables.getFirst(filteredGroups, null);
348         final ContainerSchemaNodeBuilder restContainerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restconfGroupingBuilder
349                 .getDataChildByName(Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
350         final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restContainerSchemaNodeBuilder
351                 .getDataChildByName(Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
352
353         final ContainerSchemaNodeBuilder fakeOperationsSchemaNodeBuilder = containerSchemaNodeBuilder;
354         final SchemaPath fakeSchemaPath = fakeOperationsSchemaNodeBuilder.getPath().createChild(QName.create("dummy"));
355
356         final List<LeafNode<Object>> operationsAsData = new ArrayList<>();
357
358         for (final Module module : modules) {
359             final Set<RpcDefinition> rpcs = module.getRpcs();
360             for (final RpcDefinition rpc : rpcs) {
361                 final QName rpcQName = rpc.getQName();
362                 final String name = module.getName();
363
364                 final QName qName = QName.create(restconfModule.getQNameModule(), rpcQName.getLocalName());
365                 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, qName, fakeSchemaPath);
366                 final LeafSchemaNodeBuilder fakeRpcSchemaNodeBuilder = leafSchemaNodeBuilder;
367                 fakeRpcSchemaNodeBuilder.setAugmenting(true);
368
369                 final EmptyType instance = EmptyType.getInstance();
370                 fakeRpcSchemaNodeBuilder.setType(instance);
371                 final LeafSchemaNode fakeRpcSchemaNode = fakeRpcSchemaNodeBuilder.build();
372                 fakeOperationsSchemaNodeBuilder.addChildNode(fakeRpcSchemaNode);
373
374                 final LeafNode<Object> leaf = Builders.leafBuilder(fakeRpcSchemaNode).build();
375                 operationsAsData.add(leaf);
376             }
377         }
378
379         final ContainerSchemaNode operContainerSchemaNode = fakeOperationsSchemaNodeBuilder.build();
380         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> operContainerNode = Builders.containerBuilder(operContainerSchemaNode);
381
382         for (final LeafNode<Object> oper : operationsAsData) {
383             operContainerNode.withChild(oper);
384         }
385
386         final Set<Module> fakeRpcModules = Collections.singleton(restConfModuleBuilder.build());
387
388         final YangParserImpl yangParser = new YangParserImpl();
389         final SchemaContext fakeSchemaCx = yangParser.resolveSchemaContext(fakeRpcModules);
390
391         final InstanceIdentifierContext<?> fakeIICx = new InstanceIdentifierContext<>(null, operContainerSchemaNode, mountPoint, fakeSchemaCx);
392
393         return new NormalizedNodeContext(fakeIICx, operContainerNode.build());
394     }
395
396     private Module getRestconfModule() {
397         final Module restconfModule = controllerContext.getRestconfModule();
398         if (restconfModule == null) {
399             throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
400                     ErrorTag.OPERATION_NOT_SUPPORTED);
401         }
402
403         return restconfModule;
404     }
405
406     private QName getModuleNameAndRevision(final String identifier) {
407         final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
408         String moduleNameAndRevision = "";
409         if (mountIndex >= 0) {
410             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
411         } else {
412             moduleNameAndRevision = identifier;
413         }
414
415         final Splitter splitter = Splitter.on("/").omitEmptyStrings();
416         final Iterable<String> split = splitter.split(moduleNameAndRevision);
417         final List<String> pathArgs = Lists.<String> newArrayList(split);
418         if (pathArgs.size() < 2) {
419             throw new RestconfDocumentedException(
420                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
421                     ErrorTag.INVALID_VALUE);
422         }
423
424         try {
425             final String moduleName = pathArgs.get(0);
426             final String revision = pathArgs.get(1);
427             final Date moduleRevision = REVISION_FORMAT.parse(revision);
428             return QName.create(null, moduleRevision, moduleName);
429         } catch (final ParseException e) {
430             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
431                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
432         }
433     }
434
435     @Override
436     public Object getRoot() {
437         return null;
438     }
439
440     @Override
441     public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
442         final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
443         final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
444         final CheckedFuture<DOMRpcResult, DOMRpcException> response;
445         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
446         final SchemaContext schemaContext;
447         if (identifier.contains(MOUNT_POINT_MODULE_NAME) && mountPoint != null) {
448             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
449             if ( ! mountRpcServices.isPresent()) {
450                 throw new RestconfDocumentedException("Rpc service is missing.");
451             }
452             schemaContext = mountPoint.getSchemaContext();
453             response = mountRpcServices.get().invokeRpc(type, payload.getData());
454         } else {
455             if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
456                 response = invokeSalRemoteRpcSubscribeRPC(payload);
457             } else {
458                 response = broker.invokeRpc(type, payload.getData());
459             }
460             schemaContext = controllerContext.getGlobalSchema();
461         }
462
463         final DOMRpcResult result = checkRpcResponse(response);
464
465         RpcDefinition resultNodeSchema = null;
466         final NormalizedNode<?, ?> resultData = result.getResult();
467         if (result != null && result.getResult() != null) {
468             resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
469         }
470
471         return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
472                 resultNodeSchema, mountPoint, schemaContext), resultData);
473     }
474
475     private DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
476         if (response == null) {
477             return null;
478         }
479         try {
480             final DOMRpcResult retValue = response.get();
481             if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
482                 return retValue;
483             }
484             throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
485         } catch (final InterruptedException e) {
486             throw new RestconfDocumentedException(
487                     "The operation was interrupted while executing and did not complete.", ErrorType.RPC,
488                     ErrorTag.PARTIAL_OPERATION);
489         } catch (final ExecutionException e) {
490             Throwable cause = e.getCause();
491             if (cause != null) {
492                 while (cause.getCause() != null) {
493                     cause = cause.getCause();
494                 }
495
496                 if (cause instanceof IllegalArgumentException) {
497                     throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
498                             ErrorTag.INVALID_VALUE);
499                 }
500
501                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
502                         cause);
503             } else {
504                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
505                         e);
506             }
507         } catch (final CancellationException e) {
508             throw new RestconfDocumentedException("The operation was cancelled while executing.", ErrorType.RPC,
509                     ErrorTag.PARTIAL_OPERATION);
510         }
511     }
512
513     private void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
514         if (inputSchema != null && payload.getData() == null) {
515             // expected a non null payload
516             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
517         } else if (inputSchema == null && payload.getData() != null) {
518             // did not expect any input
519             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
520         }
521         // else
522         // {
523         // TODO: Validate "mandatory" and "config" values here??? Or should those be
524         // those be
525         // validate in a more central location inside MD-SAL core.
526         // }
527     }
528
529     private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
530         final ContainerNode value = (ContainerNode) payload.getData();
531         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
532         final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
533                 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
534         final Object pathValue = path.isPresent() ? path.get().getValue() : null;
535
536         if (!(pathValue instanceof YangInstanceIdentifier)) {
537             throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
538                     ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
539         }
540
541         final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
542         String streamName = null;
543         if (!pathIdentifier.isEmpty()) {
544             final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
545
546             LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
547                     DATASTORE_PARAM_NAME);
548             datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
549
550             DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
551             scope = scope == null ? DEFAULT_SCOPE : scope;
552
553             streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
554                     + "/scope=" + scope);
555         }
556
557         if (Strings.isNullOrEmpty(streamName)) {
558             throw new RestconfDocumentedException(
559                     "Path is empty or contains value node which is not Container or List build-in type.",
560                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
561         }
562
563         final QName outputQname = QName.create(rpcQName, "output");
564         final QName streamNameQname = QName.create(rpcQName, "stream-name");
565
566         final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
567                 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
568
569         if (!Notificator.existListenerFor(streamName)) {
570             Notificator.createListener(pathIdentifier, streamName);
571         }
572
573         final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
574
575         return Futures.immediateCheckedFuture(defaultDOMRpcResult);
576     }
577
578     @Override
579     public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
580         if (StringUtils.isNotBlank(noPayload)) {
581             throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
582         }
583
584         String identifierEncoded = null;
585         DOMMountPoint mountPoint = null;
586         final SchemaContext schemaContext;
587         if (identifier.contains(ControllerContext.MOUNT)) {
588             // mounted RPC call - look up mount instance.
589             final InstanceIdentifierContext<?> mountPointId = controllerContext.toMountPointIdentifier(identifier);
590             mountPoint = mountPointId.getMountPoint();
591             schemaContext = mountPoint.getSchemaContext();
592             final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
593                     + ControllerContext.MOUNT.length() + 1;
594             final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
595             identifierEncoded = remoteRpcName;
596
597         } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
598             final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
599                     + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
600             throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
601         } else {
602             identifierEncoded = identifier;
603             schemaContext = controllerContext.getGlobalSchema();
604         }
605
606         final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
607
608         RpcDefinition rpc = null;
609         if (mountPoint == null) {
610             rpc = controllerContext.getRpcDefinition(identifierDecoded);
611         } else {
612             rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
613         }
614
615         if (rpc == null) {
616             throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
617         }
618
619         if (rpc.getInput() != null) {
620             // FIXME : find a correct Error from specification
621             throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
622         }
623
624         final CheckedFuture<DOMRpcResult, DOMRpcException> response;
625         if (mountPoint != null) {
626             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
627             if ( ! mountRpcServices.isPresent()) {
628                 throw new RestconfDocumentedException("Rpc service is missing.");
629             }
630             response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
631         } else {
632             response = broker.invokeRpc(rpc.getPath(), null);
633         }
634
635         final DOMRpcResult result = checkRpcResponse(response);
636
637         DataSchemaNode resultNodeSchema = null;
638         NormalizedNode<?, ?> resultData = null;
639         if (result != null && result.getResult() != null) {
640             resultData = result.getResult();
641             final ContainerSchemaNode rpcDataSchemaNode =
642                     SchemaContextUtil.getRpcDataSchema(schemaContext, rpc.getOutput().getPath());
643             resultNodeSchema = rpcDataSchemaNode.getDataChildByName(result.getResult().getNodeType());
644         }
645
646         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint,
647                 schemaContext), resultData);
648     }
649
650     private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
651         final String[] splittedIdentifier = identifierDecoded.split(":");
652         if (splittedIdentifier.length != 2) {
653             throw new RestconfDocumentedException(identifierDecoded
654                     + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
655                     ErrorTag.INVALID_VALUE);
656         }
657         for (final Module module : schemaContext.getModules()) {
658             if (module.getName().equals(splittedIdentifier[0])) {
659                 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
660                     if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
661                         return rpcDefinition;
662                     }
663                 }
664             }
665         }
666         return null;
667     }
668
669     @Override
670     public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
671         final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
672         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
673         NormalizedNode<?, ?> data = null;
674         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
675         if (mountPoint != null) {
676             data = broker.readConfigurationData(mountPoint, normalizedII);
677         } else {
678             data = broker.readConfigurationData(normalizedII);
679         }
680         if(data == null) {
681             throw new RestconfDocumentedException(
682                 "Request could not be completed because the relevant data model content does not exist.",
683                 ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
684         }
685         return new NormalizedNodeContext(iiWithData, data);
686     }
687
688     // FIXME: Move this to proper place
689     @SuppressWarnings("unused")
690     private Integer parseDepthParameter(final UriInfo info) {
691         final String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
692         if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
693             return null;
694         }
695
696         try {
697             final Integer depth = Integer.valueOf(param);
698             if (depth < 1) {
699                 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
700                         "Invalid depth parameter: " + depth, null,
701                         "The depth parameter must be an integer > 1 or \"unbounded\""));
702             }
703
704             return depth;
705         } catch (final NumberFormatException e) {
706             throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
707                     "Invalid depth parameter: " + e.getMessage(), null,
708                     "The depth parameter must be an integer > 1 or \"unbounded\""));
709         }
710     }
711
712     @Override
713     public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
714         final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
715         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
716         NormalizedNode<?, ?> data = null;
717         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
718         if (mountPoint != null) {
719             data = broker.readOperationalData(mountPoint, normalizedII);
720         } else {
721             data = broker.readOperationalData(normalizedII);
722         }
723         if(data == null) {
724             throw new RestconfDocumentedException(
725                 "Request could not be completed because the relevant data model content does not exist.",
726                 ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
727         }
728         return new NormalizedNodeContext(iiWithData, data);
729     }
730
731     @Override
732     public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
733         Preconditions.checkNotNull(identifier);
734         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
735
736         validateInput(iiWithData.getSchemaNode(), payload);
737         validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
738         validateListKeysEqualityInPayloadAndUri(payload);
739
740         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
741         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
742
743         /*
744          * There is a small window where another write transaction could be updating the same data
745          * simultaneously and we get an OptimisticLockFailedException. This error is likely
746          * transient and The WriteTransaction#submit API docs state that a retry will likely
747          * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
748          * probably will never succeed so we'll fail in that case.
749          *
750          * By retrying we're attempting to hide the internal implementation of the data store and
751          * how it handles concurrent updates from the restconf client. The client has instructed us
752          * to put the data and we should make every effort to do so without pushing optimistic lock
753          * failures back to the client and forcing them to handle it via retry (and having to
754          * document the behavior).
755          */
756         int tries = 2;
757         while(true) {
758             try {
759                 if (mountPoint != null) {
760                     broker.commitConfigurationDataPut(mountPoint, normalizedII, payload.getData()).checkedGet();
761                 } else {
762                     broker.commitConfigurationDataPut(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
763                 }
764
765                 break;
766             } catch (final TransactionCommitFailedException e) {
767                 if(e instanceof OptimisticLockFailedException) {
768                     if(--tries <= 0) {
769                         LOG.debug("Got OptimisticLockFailedException on last try - failing");
770                         throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
771                     }
772
773                     LOG.debug("Got OptimisticLockFailedException - trying again");
774                 } else {
775                     throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
776                 }
777             }
778         }
779
780         return Response.status(Status.OK).build();
781     }
782
783     private void validateTopLevelNodeName(final NormalizedNodeContext node,
784             final YangInstanceIdentifier identifier) {
785
786         final String payloadName = node.getData().getNodeType().getLocalName();
787
788         //no arguments
789         if (identifier.isEmpty()) {
790             //no "data" payload
791             if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
792                 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
793                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
794             }
795         //any arguments
796         } else {
797             final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
798             if (!payloadName.equals(identifierName)) {
799                 throw new RestconfDocumentedException("Payload name (" + payloadName
800                         + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
801                         ErrorTag.MALFORMED_MESSAGE);
802             }
803         }
804     }
805
806     /**
807      * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
808      *
809      * @throws RestconfDocumentedException
810      *             if key values or key count in payload and URI isn't equal
811      *
812      */
813     private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
814         Preconditions.checkArgument(payload != null);
815         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
816         final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
817         final SchemaNode schemaNode = iiWithData.getSchemaNode();
818         final NormalizedNode<?, ?> data = payload.getData();
819         if (schemaNode instanceof ListSchemaNode) {
820             final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
821             if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
822                 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
823                 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
824             }
825         }
826     }
827
828     private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
829             final MapEntryNode payload, final List<QName> keyDefinitions) {
830
831         final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
832         for (final QName keyDefinition : keyDefinitions) {
833             final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
834             // should be caught during parsing URI to InstanceIdentifier
835             RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
836                     "Missing key " + keyDefinition + " in URI.");
837
838             final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
839
840             if ( ! uriKeyValue.equals(dataKeyValue)) {
841                 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
842                         "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
843                 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
844             }
845         }
846     }
847
848     @Override
849     public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
850        return createConfigurationData(payload, uriInfo);
851     }
852
853     // FIXME create RestconfIdetifierHelper and move this method there
854     private YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
855         Preconditions.checkArgument(payload != null);
856         Preconditions.checkArgument(payload.getData() != null);
857         Preconditions.checkArgument(payload.getData().getNodeType() != null);
858         Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
859         Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
860
861         final QName payloadNodeQname = payload.getData().getNodeType();
862         final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
863         if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
864             return yangIdent;
865         }
866         final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
867         final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
868         if(parentSchemaNode instanceof DataNodeContainer) {
869             final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
870             for (final DataSchemaNode child : cast.getChildNodes()) {
871                 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
872                     return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
873                 }
874             }
875         }
876         if (parentSchemaNode instanceof RpcDefinition) {
877             return yangIdent;
878         }
879         final String errMsg = "Error parsing input: DataSchemaNode has not children";
880         throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
881     }
882
883     @Override
884     public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
885         if (payload == null) {
886             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
887         }
888
889         // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
890 //        final URI payloadNS = payload.getData().getNodeType().getNamespace();
891 //        if (payloadNS == null) {
892 //            throw new RestconfDocumentedException(
893 //                    "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
894 //                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
895 //        }
896
897         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
898         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
899         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
900         try {
901             if (mountPoint != null) {
902                 broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
903             } else {
904                 broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
905             }
906         } catch(final RestconfDocumentedException e) {
907             throw e;
908         } catch (final Exception e) {
909             throw new RestconfDocumentedException("Error creating data", e);
910         }
911
912         final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
913         // FIXME: Provide path to result.
914         final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
915         if (location != null) {
916             responseBuilder.location(location);
917         }
918         return responseBuilder.build();
919     }
920
921     private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
922         final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
923         uriBuilder.path("config");
924         try {
925             uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
926         } catch (final Exception e) {
927             LOG.debug("Location for instance identifier"+normalizedII+"wasn't created", e);
928             return null;
929         }
930         return uriBuilder.build();
931     }
932
933     @Override
934     public Response deleteConfigurationData(final String identifier) {
935         final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
936         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
937         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
938
939         try {
940             if (mountPoint != null) {
941                 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
942             } else {
943                 broker.commitConfigurationDataDelete(normalizedII).get();
944             }
945         } catch (final Exception e) {
946             final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
947                     Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
948             if (searchedException.isPresent()) {
949                 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
950             }
951             throw new RestconfDocumentedException("Error while deleting data", e);
952         }
953         return Response.status(Status.OK).build();
954     }
955
956     /**
957      * Subscribes to some path in schema context (stream) to listen on changes on this stream.
958      *
959      * Additional parameters for subscribing to stream are loaded via rpc input parameters:
960      * <ul>
961      * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
962      * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
963      * </ul>
964      */
965     @Override
966     public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
967         final String streamName = Notificator.createStreamNameFromUri(identifier);
968         if (Strings.isNullOrEmpty(streamName)) {
969             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
970         }
971
972         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
973         if (listener == null) {
974             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
975         }
976
977         final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
978         final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
979                 paramToValues.get(DATASTORE_PARAM_NAME));
980         if (datastore == null) {
981             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
982                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
983         }
984         final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
985         if (scope == null) {
986             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
987                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
988         }
989
990         broker.registerToListenDataChanges(datastore, scope, listener);
991
992         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
993         int notificationPort = NOTIFICATION_PORT;
994         try {
995             final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
996             notificationPort = webSocketServerInstance.getPort();
997         } catch (final NullPointerException e) {
998             WebSocketServer.createInstance(NOTIFICATION_PORT);
999         }
1000         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1001         final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1002
1003         return Response.status(Status.OK).location(uriToWebsocketServer).build();
1004     }
1005
1006     /**
1007      * Load parameter for subscribing to stream from input composite node
1008      *
1009      * @param compNode
1010      *            contains value
1011      * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1012      */
1013     private <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1014             final String paramName) {
1015         final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1016         if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1017             return null;
1018         }
1019         final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1020                 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1021         if (!enumNode.isPresent()) {
1022             return null;
1023         }
1024         final Object rawValue = enumNode.get().getValue();
1025         if (!(rawValue instanceof String)) {
1026             return null;
1027         }
1028
1029         return resolveAsEnum(classDescriptor, (String) rawValue);
1030     }
1031
1032     /**
1033      * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1034      *
1035      * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1036      *         null.
1037      */
1038     private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1039         if (Strings.isNullOrEmpty(value)) {
1040             return null;
1041         }
1042         return resolveAsEnum(classDescriptor, value);
1043     }
1044
1045     private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1046         final T[] enumConstants = classDescriptor.getEnumConstants();
1047         if (enumConstants != null) {
1048             for (final T enm : classDescriptor.getEnumConstants()) {
1049                 if (((Enum<?>) enm).name().equals(value)) {
1050                     return enm;
1051                 }
1052             }
1053         }
1054         return null;
1055     }
1056
1057     private Map<String, String> resolveValuesFromUri(final String uri) {
1058         final Map<String, String> result = new HashMap<>();
1059         final String[] tokens = uri.split("/");
1060         for (int i = 1; i < tokens.length; i++) {
1061             final String[] parameterTokens = tokens[i].split("=");
1062             if (parameterTokens.length == 2) {
1063                 result.put(parameterTokens[0], parameterTokens[1]);
1064             }
1065         }
1066         return result;
1067     }
1068
1069     public BigInteger getOperationalReceived() {
1070         // TODO Auto-generated method stub
1071         return null;
1072     }
1073
1074     private MapNode makeModuleMapNode(final Set<Module> modules) {
1075         Preconditions.checkNotNull(modules);
1076         final Module restconfModule = getRestconfModule();
1077         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1078                 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1079         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1080
1081         final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1082                 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1083
1084         for (final Module module : modules) {
1085             listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1086         }
1087         return listModuleBuilder.build();
1088     }
1089
1090     protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1091         Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1092                 "moduleSchemaNode has to be of type ListSchemaNode");
1093         final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1094         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1095                 .mapEntryBuilder(listModuleSchemaNode);
1096
1097         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1098                 (listModuleSchemaNode), "name");
1099         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1100         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1101         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1102                 .build());
1103
1104         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1105                 (listModuleSchemaNode), "revision");
1106         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1107         Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1108         final String revision = REVISION_FORMAT.format(module.getRevision());
1109         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1110                 .build());
1111
1112         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1113                 (listModuleSchemaNode), "namespace");
1114         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1115         Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1116         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1117                 .withValue(module.getNamespace().toString()).build());
1118
1119         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1120                 (listModuleSchemaNode), "feature");
1121         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1122         Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1123         final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1124                 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1125         for (final FeatureDefinition feature : module.getFeatures()) {
1126             featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1127                     .withValue(feature.getQName().getLocalName()).build());
1128         }
1129         moduleNodeValues.withChild(featuresBuilder.build());
1130
1131         return moduleNodeValues.build();
1132     }
1133
1134     protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1135         Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1136                 "streamSchemaNode has to be of type ListSchemaNode");
1137         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1138         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1139                 .mapEntryBuilder(listStreamSchemaNode);
1140
1141         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1142                 (listStreamSchemaNode), "name");
1143         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1144         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1145         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1146                 .build());
1147
1148         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1149                 (listStreamSchemaNode), "description");
1150         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1151         Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1152         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1153                 .withValue("DESCRIPTION_PLACEHOLDER").build());
1154
1155         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1156                 (listStreamSchemaNode), "replay-support");
1157         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1158         Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1159         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1160                 .withValue(Boolean.valueOf(true)).build());
1161
1162         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1163                 (listStreamSchemaNode), "replay-log-creation-time");
1164         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1165         Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1166         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1167                 .withValue("").build());
1168
1169         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1170                 (listStreamSchemaNode), "events");
1171         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1172         Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1173         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1174                 .withValue("").build());
1175
1176         return streamNodeValues.build();
1177     }
1178 }