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