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