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