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