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